From d595d92ad53ce649cae6d935f7eb6dd1da8ad71e Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 14:49:54 -0400 Subject: [PATCH 01/66] Add ancilla sweep engine: single VF2 at k_max + bridge subtraction, stratified product-score ranking --- .gitignore | 1 + qpu_mapper/ancilla_sweep.py | 324 ++++++++++++++++++++++++++++++++++++ tests/test_ancilla_sweep.py | 265 +++++++++++++++++++++++++++++ 3 files changed, 590 insertions(+) create mode 100644 qpu_mapper/ancilla_sweep.py create mode 100644 tests/test_ancilla_sweep.py diff --git a/.gitignore b/.gitignore index 80301f6..b06e2e8 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ htmlcov/ .qpu_mapper_sessions/ qpu_mapper/.qpu_calibration_cache/ qpu_mapper/.qpu_mapper_sessions/ +.scratch/ diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py new file mode 100644 index 0000000..2717e0b --- /dev/null +++ b/qpu_mapper/ancilla_sweep.py @@ -0,0 +1,324 @@ +""" +ancilla_sweep.py — One-shot ancilla (bridge-count) sweep for LUCJ layouts. + +Motivation +---------- +A LUCJ zigzag layout places `k` "bridge" (ancilla) qubits between the alpha +and beta chains, one every four orbitals. The number of bridges is a knob: +more bridges give the ansatz more connectivity but consume more physical +qubits and add error-prone couplings, so the best `k` is device- and +region-dependent. The naive way to explore it is to run one VF2 subgraph +search per candidate `k`. That is wasteful and — worse — *misses layouts*: +each independent search re-solves a differently-shaped template and the +2000-mapping VF2 cap (see ``auto_lucj._MAX_RAW_VF2_MAPPINGS``) bites +differently at each `k`, so a good low-`k` placement that lives inside a +great high-`k` embedding is never enumerated. + +Algorithm (bridge subtraction) +------------------------------ +This module runs VF2 **once**, at the geometric maximum bridge count +``k_max = ceil(norb / 4)``, then derives every lower-`k` candidate by +*removing* bridges from each embedding: + +1. Build the k_max template with + :func:`auto_lucj.create_lucj_zigzag_layout` and collect its embeddings + with :func:`auto_lucj._collect_vf2_mappings`. +2. For every embedding and every ``k'`` from ``k_max_effective`` down to + ``min_bridges``, enumerate all size-``k'`` subsets of the bridges to keep. + The chain qubits never move; only which ancillas (and their two coupling + edges) are retained changes. +3. Deduplicate per stratum (alpha/beta swaps collapse, mirroring + :func:`auto_lucj._deduplicate_layouts`), score, and keep the top-N per `k`. + +Why this is strictly better than per-`k` search: + +* The k_max template is the *most constrained* subgraph, so the VF2 cap + removes the fewest useful embeddings there. +* Every k_max embedding yields all of its lower-`k` variants for free — + including the "good-region k-1 layout" that an independent k-1 search, + starting from the rigid every-4th-orbital template, never generates. +* Subtraction also unlocks *non-standard* bridge-position sets (e.g. keeping + orbital slots ``{0, 8, 12}`` out of ``{0, 4, 8, 12}``) that the fixed + template cannot express at all. + +Scoring: product vs additive +----------------------------- +Each candidate carries two scores: + +* ``additive_score`` — the legacy lightweight sum of readout errors over the + used qubits plus 2Q gate errors over the used edges. It is a **sum**, so it + grows with layout size: a k-bridge layout always has a larger additive sum + than its (k-1)-bridge subset *even when the extra bridge is excellent*. + Additive is therefore fine for ranking **within** a single stratum (fixed + size) but must **never** be used to compare across strata. +* ``product_score`` — a multiplicative fidelity proxy, + ``prod(1 - readout_err) * prod(1 - gate_err)`` over the same qubits and + edges. Adding a bridge multiplies the score by that bridge's fidelity + factor ``(1 - r)(1 - e1)(1 - e2) <= 1``, so product is directly comparable + both within and across strata. **product_score is the ranking key.** + +Caveats +------- +* The VF2 cap (``mapping_cap``, default 2000) can truncate the embedding set + on large heavy-hex backends. When that happens ``vf2_truncated`` is True in + the result and callers should surface it (the sweep may not have seen every + possible layout). +* Like the underlying lightweight scorer, this is a first-order relative + heuristic (independent-error assumption, one gate per edge, no crosstalk), + suitable for ranking, not absolute fidelity prediction. +""" + +import itertools +import logging + +import numpy as np + +from .auto_lucj import ( + _collect_vf2_mappings, + _get_two_q_gate_name, + _make_backend_cmap_pygraph, + _MAX_RAW_VF2_MAPPINGS, + create_lucj_zigzag_layout, +) + +_log = logging.getLogger(__name__) + +# NaN / uncalibrated penalty, matching lightweight_layout_error_scoring. +# For the additive sum this adds 1.0 (max error); for the product it makes +# the fidelity factor (1 - 1.0) = 0, i.e. the candidate is effectively +# excluded from the top ranks. +_UNCALIBRATED_PENALTY = 1.0 + + +def _safe_readout(props, qubit): + """Readout error for `qubit`, NaN/None -> penalty (mirrors lightweight).""" + try: + val = props.readout_error(qubit) + except Exception: + return _UNCALIBRATED_PENALTY + if val is None or (isinstance(val, float) and np.isnan(val)): + return _UNCALIBRATED_PENALTY + return float(val) + + +def _safe_gate_error(props, gate_name, u, v): + """2Q gate error for edge (u, v) with reverse fallback, NaN -> penalty.""" + for a, b in ((u, v), (v, u)): + try: + val = props.gate_error(gate_name, (a, b)) + except Exception: + continue + if val is None or (isinstance(val, float) and np.isnan(val)): + continue + return float(val) + return _UNCALIBRATED_PENALTY + + +def sweep_ancilla_layouts(norb, backend, props, *, + min_bridges=None, top_n=3, + mapping_cap=None) -> dict: + """One-shot ancilla sweep: VF2 at the geometric max bridge count, + then derive every lower-k variant by bridge subtraction, score, and + return the top_n candidates per ancilla count. + + Args: + norb: Number of spatial orbitals (alpha chain length). + backend: IBM Qiskit BackendV2-like object (needs ``coupling_map`` and + a discoverable 2Q gate; see ``auto_lucj._get_two_q_gate_name``). + props: BackendProperties-like object exposing ``readout_error(q)`` and + ``gate_error(name, (u, v))``. No API calls are made here. + min_bridges: Floor of the sweep (inclusive). Defaults to + ``min(3, k_max_effective)``. Must satisfy + ``1 <= min_bridges <= k_max_effective`` or ValueError is raised. + top_n: Max candidates returned per ancilla count. + mapping_cap: Override the VF2 mapping cap (default + ``auto_lucj._MAX_RAW_VF2_MAPPINGS``). Mainly for tests. + + Returns { + 'strata': {k: [entry, ...]}, # k descending; len<=top_n each + 'k_max_effective': int, # what actually fit on the chip + 'min_bridges': int, # floor actually used + 'vf2_truncated': bool, # 2000-cap hit (surface in UI!) + 'n_raw_embeddings': int, # complete VF2 mappings used + 'n_candidates_scored': int, # total variants scored (pre-dedupe) + } + entry = { + 'layout': [...], # chain qubits (alpha+beta) + 'alpha': [...], 'beta': [...], + 'ancillas': [...], # physical bridge qubits kept + 'bridge_slots': (...), # orbital slots kept, e.g. (0, 8, 12) + 'product_score': float, # multiplicative, THE ranking key + 'additive_score': float, # legacy lightweight, informational + 'rank_in_stratum': int, # 1-based, by product_score desc + 'source': 'vf2' | 'derived', # intact k_max vs subtraction variant + } + """ + # ---- 1. Build the backend graph and the k_max template ---------------- + backend_graph = _make_backend_cmap_pygraph(backend=backend) + + k_max = (norb + 3) // 4 # ceil(norb / 4): the geometric bridge ceiling + template, k_max_effective = create_lucj_zigzag_layout( + num_orbitals=norb, + backend_coupling_graph=backend_graph, + requested_bridges=k_max, + ) + if k_max_effective < 1: + raise RuntimeError( + f"No ancilla bridges fit for norb={norb} on this backend " + f"(k_max_effective={k_max_effective}); an ancilla sweep needs " + f"at least one bridge." + ) + + # ---- 2. Resolve and validate min_bridges ------------------------------ + if min_bridges is None: + min_bridges = min(3, k_max_effective) + if not (1 <= min_bridges <= k_max_effective): + raise ValueError( + f"min_bridges={min_bridges} out of range; must satisfy " + f"1 <= min_bridges <= k_max_effective ({k_max_effective})." + ) + + # ---- 3. Collect VF2 embeddings, detect truncation --------------------- + cap = mapping_cap if mapping_cap is not None else _MAX_RAW_VF2_MAPPINGS + mappings = _collect_vf2_mappings(backend_graph, template, cap=cap) + # The helper only *logs* truncation; detect it by the cap being reached. + vf2_truncated = len(mappings) >= cap + if vf2_truncated: + _log.debug("Ancilla sweep: VF2 truncated at cap=%d", cap) + + # ---- 4. Materialize complete layouts (mirror get_all_zigzag_layouts) -- + expected_size = 2 * norb + k_max_effective + layouts = [] + for mapping in mappings: + layout = [None] * expected_size + for key, value in mapping.items(): + layout[value] = key + if any(v is None for v in layout): + _log.debug("Ancilla sweep: skipping incomplete VF2 mapping") + continue + layouts.append(layout) + n_raw_embeddings = len(layouts) + if not layouts: + raise RuntimeError( + f"No complete zigzag embedding found for norb={norb} on this " + f"backend." + ) + + # ---- 5. Precompute props once (hoist all API-shaped lookups) ---------- + gate_name = _get_two_q_gate_name(backend) + if gate_name is None: + raise RuntimeError("Could not determine the backend 2Q gate name.") + + node_indices = list(backend_graph.node_indices()) + max_id = max(node_indices) + # readout array indexed by physical qubit id; penalty for anything absent. + readout = np.full(max_id + 1, _UNCALIBRATED_PENALTY, dtype=float) + for q in node_indices: + readout[q] = _safe_readout(props, q) + # physical-edge -> gate error, keyed by frozenset so direction is moot. + edge_err = {} + for u, v in backend_graph.edge_list(): + edge_err[frozenset((u, v))] = _safe_gate_error(props, gate_name, u, v) + + def _edge_e(a, b): + return edge_err.get(frozenset((a, b)), + _safe_gate_error(props, gate_name, a, b)) + + # ---- 6. Enumerate + score every variant, grouped by stratum ---------- + # strata_pool[k] : dict keyed by (frozenset(chain), frozenset(ancilla)) + # -> entry, giving per-stratum dedupe for free. + strata_pool = {k: {} for k in range(k_max_effective, min_bridges - 1, -1)} + n_candidates_scored = 0 + + for layout in layouts: + alpha = layout[:norb] + beta = layout[norb:2 * norb] + chain = layout[:2 * norb] + chain_fs = frozenset(chain) + + # Chain aggregates are constant across every variant of this + # embedding, so compute them once. + chain_qubits = np.array(chain, dtype=int) + chain_readout_sum = float(readout[chain_qubits].sum()) + chain_readout_prod = float(np.prod(np.clip(1.0 - readout[chain_qubits], + 0.0, 1.0))) + chain_edges = ([(alpha[j], alpha[j + 1]) for j in range(norb - 1)] + + [(beta[j], beta[j + 1]) for j in range(norb - 1)]) + chain_gate_errs = np.array([_edge_e(a, b) for a, b in chain_edges], + dtype=float) + chain_gate_sum = float(chain_gate_errs.sum()) + chain_gate_prod = float(np.prod(np.clip(1.0 - chain_gate_errs, + 0.0, 1.0))) + + # Per-bridge contributions for this embedding. + bridges = [] + for i in range(k_max_effective): + bphys = layout[2 * norb + i] + e1 = _edge_e(alpha[4 * i], bphys) + e2 = _edge_e(bphys, beta[4 * i]) + r = float(readout[bphys]) + add_i = r + e1 + e2 + prod_i = (max(0.0, 1.0 - r) * max(0.0, 1.0 - e1) + * max(0.0, 1.0 - e2)) + bridges.append({ + 'phys': bphys, + 'slot': 4 * i, + 'add': add_i, + 'prod': prod_i, + }) + + # Alpha/beta swap normalization (mirror _deduplicate_layouts): the + # representative alpha is the chain with the smaller first element. + if alpha and beta and alpha[0] > beta[0]: + norm_alpha, norm_beta = list(beta), list(alpha) + else: + norm_alpha, norm_beta = list(alpha), list(beta) + norm_chain = norm_alpha + norm_beta + + for k in range(k_max_effective, min_bridges - 1, -1): + for kept in itertools.combinations(range(k_max_effective), k): + n_candidates_scored += 1 + ancillas = [bridges[i]['phys'] for i in kept] + ancilla_fs = frozenset(ancillas) + key = (chain_fs, ancilla_fs) + if key in strata_pool[k]: + # Duplicate (e.g. alpha/beta swap): identical qubits and + # edges -> identical score, so keep the first. + continue + additive = (chain_readout_sum + chain_gate_sum + + sum(bridges[i]['add'] for i in kept)) + product = chain_readout_prod * chain_gate_prod + for i in kept: + product *= bridges[i]['prod'] + strata_pool[k][key] = { + 'layout': list(norm_chain), + 'alpha': list(norm_alpha), + 'beta': list(norm_beta), + 'ancillas': ancillas, + 'bridge_slots': tuple(bridges[i]['slot'] for i in kept), + 'product_score': product, + 'additive_score': additive, + 'rank_in_stratum': 0, # filled after sort + 'source': 'vf2' if k == k_max_effective else 'derived', + } + + # ---- 7. Rank each stratum by product_score desc, slice top_n --------- + strata = {} + for k in range(k_max_effective, min_bridges - 1, -1): + entries = sorted(strata_pool[k].values(), + key=lambda e: e['product_score'], reverse=True) + entries = entries[:top_n] + for rank, entry in enumerate(entries, start=1): + entry['rank_in_stratum'] = rank + strata[k] = entries + _log.debug("Ancilla sweep stratum k=%d: %d candidates (top_n=%d)", + k, len(entries), top_n) + + return { + 'strata': strata, + 'k_max_effective': k_max_effective, + 'min_bridges': min_bridges, + 'vf2_truncated': vf2_truncated, + 'n_raw_embeddings': n_raw_embeddings, + 'n_candidates_scored': n_candidates_scored, + } diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py new file mode 100644 index 0000000..4be1beb --- /dev/null +++ b/tests/test_ancilla_sweep.py @@ -0,0 +1,265 @@ +"""Tests for qpu_mapper.ancilla_sweep — the one-shot bridge-subtraction sweep. + +Deterministic and fully offline (no qiskit, no network). A synthetic backend +is built from two disconnected width-8 heavy-hex-like "ladder" blocks: + + top chain t0 - t1 - ... - t7 (8 qubits) + bridges | r0 | r1 | r7 (one bridge qubit per column) + bottom chain b0 - b1 - ... - b7 (8 qubits) + +Each bridge qubit rj connects tj and bj (a 3-node path tj-rj-bj), exactly the +shape auto_lucj's zigzag template expects. Two such blocks are built: + + * GOOD block — physical qubit ids 0..23, low error everywhere. + * BAD block — physical qubit ids 24..47, high error everywhere. + +For norb=8 the geometric ceiling is k_max = ceil(8/4) = 2 bridges (orbital +slots 0 and 4), so k_max_effective == 2 and a min_bridges=1 sweep produces two +strata (k=2 intact VF2 layouts, k=1 subtraction variants). +""" + +import time + +import pytest +import rustworkx + +from types import SimpleNamespace + +from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts + +GOOD_QUBITS = set(range(24)) # ids 0..23 are the low-error "good region" + + +# ── synthetic backend / props ────────────────────────────────────────────── + +def _build_block(base, edges): + """Append a width-8 ladder block based at physical id `base`. + + Ids: top base..base+7, bottom base+8..base+15, bridges base+16..base+23. + """ + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges.append((top[j], top[j + 1])) + edges.append((bot[j], bot[j + 1])) + for j in range(8): + edges.append((top[j], brg[j])) + edges.append((brg[j], bot[j])) + + +def make_backend(): + """SimpleNamespace exposing exactly what _make_backend_cmap_pygraph and + _get_two_q_gate_name read: a directed rustworkx coupling graph and the + backend operation names (with a 2Q 'cz').""" + edges = [] + _build_block(0, edges) # GOOD block → ids 0..23 + _build_block(24, edges) # BAD block → ids 24..47 + graph = rustworkx.PyDiGraph() + for i in range(48): + graph.add_node(i) + for u, v in edges: + graph.add_edge(u, v, None) + coupling_map = SimpleNamespace(graph=graph) + return SimpleNamespace(coupling_map=coupling_map, + operation_names=['cz', 'sx', 'rz', 'x']) + + +# Error parameters. GOOD block uses these small, IDENTICAL-per-role values so +# that the across-strata per-ancilla factor is exact and unambiguous. +R_CHAIN_GOOD, R_BRIDGE_GOOD = 0.001, 0.003 +E_CHAIN_GOOD, E_BRIDGE_GOOD = 0.002, 0.004 +R_CHAIN_BAD, R_BRIDGE_BAD = 0.05, 0.06 +E_CHAIN_BAD, E_BRIDGE_BAD = 0.05, 0.07 + + +class FakeProps: + """BackendProperties stand-in: readout_error(q) and gate_error(name, (u,v)) + are all the sweep and its scoring read. Fully calibrated (no NaN).""" + + def readout_error(self, q): + good = q in GOOD_QUBITS + is_bridge = (q % 24) >= 16 + if is_bridge: + return R_BRIDGE_GOOD if good else R_BRIDGE_BAD + return R_CHAIN_GOOD if good else R_CHAIN_BAD + + def gate_error(self, name, edge): + u, v = edge + good = u in GOOD_QUBITS and v in GOOD_QUBITS + is_bridge = (u % 24) >= 16 or (v % 24) >= 16 + if is_bridge: + return E_BRIDGE_GOOD if good else E_BRIDGE_BAD + return E_CHAIN_GOOD if good else E_CHAIN_BAD + + +ENTRY_FIELDS = { + 'layout', 'alpha', 'beta', 'ancillas', 'bridge_slots', + 'product_score', 'additive_score', 'rank_in_stratum', 'source', +} + + +def _dedupe_key(entry): + return (frozenset(entry['alpha']) | frozenset(entry['beta']), + frozenset(entry['ancillas'])) + + +@pytest.fixture +def backend(): + return make_backend() + + +@pytest.fixture +def props(): + return FakeProps() + + +# ── t1: shape ────────────────────────────────────────────────────────────── + +def test_shape(backend, props): + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) + assert res['k_max_effective'] == 2 + assert res['min_bridges'] == 1 + + # strata keys run k_max_effective..min_bridges, descending. + assert list(res['strata'].keys()) == [2, 1] + + for k, entries in res['strata'].items(): + assert len(entries) <= 3 # top_n cap + assert entries, f"stratum k={k} unexpectedly empty" + for e in entries: + assert set(e) == ENTRY_FIELDS # all documented fields + assert len(e['ancillas']) == k # ancilla count == k + assert len(e['bridge_slots']) == k + assert e['layout'] == list(e['alpha']) + list(e['beta']) + assert len(e['alpha']) == 8 and len(e['beta']) == 8 + # rank_in_stratum is 1-based and dense. + assert [e['rank_in_stratum'] for e in entries] == list( + range(1, len(entries) + 1)) + + +# ── t2: regression — the good-region k-1 layout is derived for free ───────── + +def test_kminus1_variant_present(backend, props): + """The user's observation: an independent per-k search misses the k-1 + layout that lives inside the best k-max embedding. With subtraction it is + always in the k-1 pool on the same chain qubits.""" + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + top = res['strata'][2][0] # best intact k=2 layout + assert top['source'] == 'vf2' + chain = frozenset(top['alpha']) | frozenset(top['beta']) + + same_chain = [e for e in res['strata'][1] + if (frozenset(e['alpha']) | frozenset(e['beta'])) == chain] + assert same_chain, "k-1 derived variant on the top chain is missing" + # Everything in the k-1 stratum is a subtraction variant. + assert all(e['source'] == 'derived' for e in same_chain) + # The top layout's OWN k-1 variant (a strict subset of its two bridges) + # must be present. Other same-chain entries may come from the reversed + # embedding, which shares the chain qubits but keeps different bridges — + # those are not subsets of top's ancillas, which is exactly why an + # independent per-k search starting from the rigid template can miss the + # good one that subtraction recovers here. + top_ancillas = set(top['ancillas']) + assert any(set(e['ancillas']) < top_ancillas for e in same_chain), ( + "the top layout's own k-1 subtraction variant is absent") + + +# ── t3: good region wins every stratum ────────────────────────────────────── + +def test_good_region_wins(backend, props): + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) + for k, entries in res['strata'].items(): + best = entries[0] + used = set(best['alpha']) | set(best['beta']) | set(best['ancillas']) + assert used <= GOOD_QUBITS, ( + f"stratum k={k} winner {sorted(used)} leaks outside good region") + + +# ── t4: size-bias guard (within-stratum agreement, across-stratum factor) ─── + +def test_size_bias_product_vs_additive(backend, props): + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + + # Within a stratum (fixed size), the product ranking agrees with the + # additive ranking: entries are ordered by product desc, and in the + # small-error regime prod(1-x) ~ 1 - sum(x), so additive is non-decreasing + # down the list. + for k, entries in res['strata'].items(): + prods = [e['product_score'] for e in entries] + adds = [e['additive_score'] for e in entries] + assert prods == sorted(prods, reverse=True) + assert adds == sorted(adds), ( + f"stratum k={k}: additive not non-decreasing along product order") + + # ACROSS strata, additive is size-biased and must NOT rank: the k=1 best + # has a SMALLER additive sum than the k=2 best (fewer terms) even though + # both live in the same good region — proving additive can't compare sizes. + k2, k1 = res['strata'][2][0], res['strata'][1][0] + assert k1['additive_score'] < k2['additive_score'] + + # product_score IS comparable across strata: adding the second bridge + # multiplies the k=1 fidelity by exactly that bridge's factor + # (1-r)(1-e1)(1-e2). Both good-region bridges are identical, so the ratio + # is exact. Tolerance 1e-9 (float round-off only). + per_ancilla = (1 - R_BRIDGE_GOOD) * (1 - E_BRIDGE_GOOD) ** 2 + ratio = k1['product_score'] / k2['product_score'] + assert ratio == pytest.approx(1.0 / per_ancilla, abs=1e-9) + + +# ── t5: dedupe ────────────────────────────────────────────────────────────── + +def test_dedupe(backend, props): + """Alpha/beta-swap embeddings collapse to a single entry per stratum.""" + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + + for k, entries in res['strata'].items(): + keys = [_dedupe_key(e) for e in entries] + assert len(keys) == len(set(keys)), ( + f"stratum k={k} has duplicate (chain, ancilla) keys") + + # A real collapse happened: VF2 found more raw embeddings than the k=2 + # stratum keeps, because each layout and its alpha/beta swap merge. + assert res['n_raw_embeddings'] > len(res['strata'][2]) + + +# ── t6: validation ────────────────────────────────────────────────────────── + +def test_validation(backend, props): + with pytest.raises(ValueError): + sweep_ancilla_layouts(8, backend, props, min_bridges=0) + with pytest.raises(ValueError): + sweep_ancilla_layouts(8, backend, props, min_bridges=99) + + # min_bridges == k_max_effective → exactly one stratum, all intact 'vf2'. + res = sweep_ancilla_layouts(8, backend, props, min_bridges=2, top_n=1000) + assert list(res['strata'].keys()) == [2] + assert all(e['source'] == 'vf2' for e in res['strata'][2]) + + +# ── t7: truncation ────────────────────────────────────────────────────────── + +def test_truncation(backend, props): + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, mapping_cap=1) + assert res['vf2_truncated'] is True + assert res['n_raw_embeddings'] == 1 + # Still well-formed strata from the single embedding. + assert list(res['strata'].keys()) == [2, 1] + for k, entries in res['strata'].items(): + assert entries + for e in entries: + assert set(e) == ENTRY_FIELDS + assert len(e['ancillas']) == k + + +# ── performance smoke (reported wall time) ────────────────────────────────── + +def test_perf_smoke(backend, props): + """Not a hard threshold — exercises the full sweep so pytest --durations + reports its wall time. The vectorized precompute keeps this well under a + second on the synthetic graph.""" + t0 = time.perf_counter() + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + elapsed = time.perf_counter() - t0 + assert res['strata'] + assert elapsed < 5.0, f"sweep too slow: {elapsed:.3f}s" From 348b4e7e76c0608c29aa4bbc6e12f339f3ae5978 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 15:33:27 -0400 Subject: [PATCH 02/66] Wire ancilla sweep into Auto tab: stratified dropdown with LQS labels, truncation banner --- qpu_mapper/ui/builder.py | 25 +++- qpu_mapper/ui/lucj_panel.py | 249 ++++++++++++++++++++++++++---------- tests/test_sweep_ui.py | 182 ++++++++++++++++++++++++++ 3 files changed, 382 insertions(+), 74 deletions(-) create mode 100644 tests/test_sweep_ui.py diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index da07e31..295bfa4 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -298,8 +298,10 @@ def _run_pipeline(self): _lucj_ctx = _NS( state=state, out=self.out, W=W, lucj_norb_slider=self.lucj_norb_slider, lucj_ancilla_dd=self.lucj_ancilla_dd, + lucj_min_ancilla=self.lucj_min_ancilla, lucj_chk_score=self.lucj_chk_score, btn_lucj_run=self.btn_lucj_run, - lbl_lucj_status=self.lbl_lucj_status, dd_lucj_layout=self.dd_lucj_layout, + lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, + dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, lucj_multi_ancillas=self.lucj_multi_ancillas, @@ -1178,12 +1180,25 @@ def _build_auto_lucj_widgets(self, W): description='Num Orbitals:', layout=Layout(width='220px'), style={'description_width': '110px'}) + # 'Auto' runs the stratified ancilla sweep (default). Picking an + # explicit 0..5 runs the legacy single-count search unchanged. self.lucj_ancilla_dd = Dropdown( - options=[('Auto (max ancillas)', -1), ('0 (no ancillas)', 0), + options=[('Auto (sweep all counts)', -1), ('0 (no ancillas)', 0), ('1 ancilla', 1), ('2 ancillas', 2), ('3 ancillas', 3), ('4 ancillas', 4), ('5 ancillas', 5)], value=-1, description='Ancilla:', layout=W, - style={'description_width': 'initial'}) + style={'description_width': 'initial'}, + tooltip='Fix the ancilla count (legacy single search); ' + 'Auto runs the stratified sweep') + # Sweep-only floor. 0 = auto → engine default min(3, k_max). Only + # consulted when the Ancilla dropdown is on 'Auto'. + self.lucj_min_ancilla = BoundedIntText( + value=0, min=0, max=20, + description='Min ancillas:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='Sweep all counts from max down to this floor ' + '(0 = auto)') self.lucj_chk_score = Checkbox( value=True, description='Score layouts (pick lowest error)', @@ -1192,6 +1207,8 @@ def _build_auto_lucj_widgets(self, W): description='🤖 Generate LUCJ Layout', button_style='success', layout=W) self.lbl_lucj_status = HTML("") + # Sweep truncation banner (VF2 cap hit); empty/hidden otherwise. + self.lbl_lucj_trunc = HTML("") # ── Inspect Layouts cluster ────────────────────────────── self.dd_lucj_layout = Dropdown( @@ -1586,8 +1603,10 @@ def _build_auto_lucj_view(self): "🔬 Single Circuit"), self.lucj_norb_slider, self.lucj_ancilla_dd, + self.lucj_min_ancilla, self.lucj_chk_score, self.btn_lucj_run, + self.lbl_lucj_trunc, self.lbl_lucj_status, HTML("
" "📋 Inspect Layouts
"), diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index ce36a3a..e2fa542 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -24,9 +24,11 @@ def setup_lucj_callbacks(ctx): lucj_norb_slider = ctx.lucj_norb_slider lucj_ancilla_dd = ctx.lucj_ancilla_dd + lucj_min_ancilla = ctx.lucj_min_ancilla lucj_chk_score = ctx.lucj_chk_score btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status + lbl_lucj_trunc = ctx.lbl_lucj_trunc dd_lucj_layout = ctx.dd_lucj_layout lbl_lucj_detail = ctx.lbl_lucj_detail @@ -102,6 +104,18 @@ def _apply_lucj_layout(entry): for q in d['beta']: d['styles'][q] = {'fill': beta_fill, 'line': _line, 'width': _width, 'text_color': _text} + # Sweep candidates carry their kept bridges in entry['ancillas']; + # place them as the ancilla role (green) so a derived k no ancillas placed + # (unchanged behaviour). + anc_color = d['defaults']['fill_anc'] + anc_fill = 'none' if line_only else hex_to_rgba(anc_color, 1.0) + d['ancilla'] = [str(q) for q in entry.get('ancillas', []) + if str(q) in state.qubit_ids] + for q in d['ancilla']: + d['styles'][q] = {'fill': anc_fill, + 'line': _line, 'width': _width, 'text_color': _text} _refresh() _get_export() @@ -112,16 +126,166 @@ def _on_lucj_layout_select(change): return entry = _lucj_all_layouts[idx] _apply_lucj_layout(entry) - sc = f"{entry['score']:.4f}" if entry['score'] is not None else "N/A" - lbl_lucj_detail.value = ( - f"
" - f"#{entry['rank']} (err={sc})
" - f"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in entry['beta'])}
" - ) + if 'product_score' in entry: + # Sweep candidate: multiplicative LQS is the headline; the + # additive sum (size-biased across k) goes in the detail only. + k = len(entry['ancillas']) + lqs = entry['product_score'] * 100.0 + header = (f"k={k} · #{entry['rank_in_stratum']} " + f"· LQS {lqs:.1f}% " + f"(add {entry['additive_score']:.4f}, " + f"{esc(str(entry.get('source', '')))})") + anc = ', '.join(str(q) for q in entry['ancillas']) + lbl_lucj_detail.value = ( + f"
" + f"{header}
" + f"α: {', '.join(str(q) for q in entry['alpha'])}
" + f"β: {', '.join(str(q) for q in entry['beta'])}
" + f"ancillas: {anc}
" + ) + else: + sc = f"{entry['score']:.4f}" if entry['score'] is not None else "N/A" + lbl_lucj_detail.value = ( + f"
" + f"#{entry['rank']} (err={sc})
" + f"α: {', '.join(str(q) for q in entry['alpha'])}
" + f"β: {', '.join(str(q) for q in entry['beta'])}
" + ) dd_lucj_layout.observe(_on_lucj_layout_select, names='value') + # ── Dropdown re-seed helper (observer-safe) ────────────────── + def _seed_layout_dropdown(entries, dd_opts): + """Store `entries` as the flat candidate list and re-seed + dd_lucj_layout without firing the select observer, then apply the + first entry. Shared by the legacy and sweep paths.""" + _lucj_all_layouts.clear() + _lucj_all_layouts.extend(entries) + # Suppress observer firing while re-seeding: otherwise setting + # value=0 fires _on_lucj_layout_select → apply, then we apply again + # below — double push_undo + redundant refresh. Same unobserve → + # set → observe dance as _reoptimize_downstream. + dd_lucj_layout.unobserve(_on_lucj_layout_select, names='value') + dd_lucj_layout.options = dd_opts + dd_lucj_layout.value = 0 if dd_opts else None + dd_lucj_layout.disabled = not dd_opts + dd_lucj_layout.observe(_on_lucj_layout_select, names='value') + if entries: + _apply_lucj_layout(entries[0]) + + # ── Legacy single-count search ─────────────────────────────── + def _generate_legacy(norb, requested_ancillas): + from ..auto_lucj import get_all_zigzag_layouts + + all_layouts, num_ab = get_all_zigzag_layouts( + num_orbitals=norb, + backend=state.active_backend, + score=lucj_chk_score.value, + props=state.initial_props, + requested_bridges=requested_ancillas, + ) + + # Surface the geometric-cap clamp: auto_lucj logs a stderr + # warning when the requested bridges exceed ceil(norb/4), but + # Jupyter hides stderr — without this the user saw + # "ancillas=1" with no hint that their "5" was clamped. + ancilla_note = "" + if (requested_ancillas is not None + and requested_ancillas >= 0 + and requested_ancillas != num_ab): + ancilla_note = ( + f"
⚠️ You requested {requested_ancillas} " + f"ancilla(s) but the zigzag geometry only allows " + f"{num_ab} for norb={norb} (max one bridge " + f"every 4 orbitals)." + ) + + dd_opts = [] + for entry in all_layouts: + sc = f"err={entry['score']:.4f}" if entry['score'] is not None else "?" + dd_opts.append(( + f"#{entry['rank']} ({sc}) α:[{entry['alpha'][0]}..{entry['alpha'][-1]}]", + entry['rank'] - 1, + )) + _seed_layout_dropdown(all_layouts, dd_opts) + + best = all_layouts[0] + if best['score'] is None and lucj_chk_score.value: + lbl_lucj_status.value = ( + f"
" + f"⚠️ Scoring unavailable (no calibration data). " + f"{len(all_layouts)} layouts found (unsorted). " + f"ancillas={num_ab}{ancilla_note}
") + else: + sc = f"{best['score']:.4f}" if best['score'] is not None else "N/A" + lbl_lucj_status.value = ( + f"
" + f"✅ {len(all_layouts)} layouts found (norb={norb}, " + f"ancillas={num_ab}). Best: err={sc}{ancilla_note}
") + + # ── Stratified ancilla sweep (new default) ─────────────────── + def _generate_sweep(norb): + from ..ancilla_sweep import sweep_ancilla_layouts + + # 0 (or blank) → engine default min(3, k_max); else the user floor. + min_val = lucj_min_ancilla.value + min_bridges = None if (min_val is None or min_val <= 0) else min_val + + res = sweep_ancilla_layouts( + norb, state.active_backend, state.initial_props, + min_bridges=min_bridges) + + strata = res['strata'] + # Flatten k descending, entries in stratum order; the dropdown value + # is the flat index. Label format is fixed: "k=4 · #1 · LQS 25.3%". + flat = [] + dd_opts = [] + for k in sorted(strata.keys(), reverse=True): + for entry in strata[k]: + lqs = entry['product_score'] * 100.0 + dd_opts.append(( + f"k={k} · #{entry['rank_in_stratum']} · LQS {lqs:.1f}%", + len(flat), + )) + flat.append(entry) + + _seed_layout_dropdown(flat, dd_opts) + + # Truncation banner (U5): visible only when the VF2 cap was hit. + if res['vf2_truncated']: + lbl_lucj_trunc.value = ( + f"
⚠️ Enumeration capped at " + f"{esc(str(res['n_raw_embeddings']))} mappings — ranking may " + f"be non-exhaustive.
") + else: + lbl_lucj_trunc.value = "" + + # One-line summary (U6). product_score is comparable across strata, + # so the global best is a plain max over the flat list. + best = max(flat, key=lambda e: e['product_score']) if flat else None + if best is not None: + best_lqs = f"{best['product_score'] * 100.0:.1f}%" + best_k = len(best['ancillas']) + k_range = f"{res['k_max_effective']}..{res['min_bridges']}" + emb = f"{res['n_raw_embeddings']:,}" + cand = f"{res['n_candidates_scored']:,}" + lbl_lucj_status.value = ( + f"
✅ Sweep: k={esc(k_range)} · " + f"{esc(emb)} embeddings · {esc(cand)} candidates · " + f"best LQS {esc(best_lqs)} (k={esc(str(best_k))})
") + else: + lbl_lucj_status.value = ( + f"
⚠️ Sweep produced no candidates.
") + # ── Single circuit LUCJ generate ───────────────────────────── def _on_lucj_generate(b): if state.active_backend is None: @@ -137,72 +301,15 @@ def _on_lucj_generate(b): btn_lucj_run.disabled = True btn_lucj_run.description = '⏳ Generating...' lbl_lucj_status.value = "" + lbl_lucj_trunc.value = "" try: - from ..auto_lucj import get_all_zigzag_layouts - requested_ancillas = lucj_ancilla_dd.value - all_layouts, num_ab = get_all_zigzag_layouts( - num_orbitals=norb, - backend=state.active_backend, - score=lucj_chk_score.value, - props=state.initial_props, - requested_bridges=requested_ancillas, - ) - - # Surface the geometric-cap clamp: auto_lucj logs a stderr - # warning when the requested bridges exceed ceil(norb/4), but - # Jupyter hides stderr — without this the user saw - # "ancillas=1" with no hint that their "5" was clamped. - ancilla_note = "" - if (requested_ancillas is not None - and requested_ancillas >= 0 - and requested_ancillas != num_ab): - ancilla_note = ( - f"
⚠️ You requested {requested_ancillas} " - f"ancilla(s) but the zigzag geometry only allows " - f"{num_ab} for norb={norb} (max one bridge " - f"every 4 orbitals)." - ) - - _lucj_all_layouts.clear() - _lucj_all_layouts.extend(all_layouts) - - # Populate dropdown - dd_opts = [] - for entry in all_layouts: - sc = f"err={entry['score']:.4f}" if entry['score'] is not None else "?" - dd_opts.append(( - f"#{entry['rank']} ({sc}) α:[{entry['alpha'][0]}..{entry['alpha'][-1]}]", - entry['rank'] - 1, - )) - # Suppress observer firing while re-seeding: otherwise - # setting value=0 fires _on_lucj_layout_select → apply, then - # we apply again below — double push_undo + redundant refresh. - # Same unobserve → set → observe dance as _reoptimize_downstream. - dd_lucj_layout.unobserve(_on_lucj_layout_select, names='value') - dd_lucj_layout.options = dd_opts - dd_lucj_layout.value = 0 - dd_lucj_layout.disabled = False - dd_lucj_layout.observe(_on_lucj_layout_select, names='value') - - best = all_layouts[0] - _apply_lucj_layout(best) - - if best['score'] is None and lucj_chk_score.value: - lbl_lucj_status.value = ( - f"
" - f"⚠️ Scoring unavailable (no calibration data). " - f"{len(all_layouts)} layouts found (unsorted). " - f"ancillas={num_ab}{ancilla_note}
") + # Exact count picked (>= 0) → legacy single-count search, + # unchanged. 'Auto' (-1) → stratified sweep (new default). + if requested_ancillas is not None and requested_ancillas >= 0: + _generate_legacy(norb, requested_ancillas) else: - sc = f"{best['score']:.4f}" if best['score'] is not None else "N/A" - lbl_lucj_status.value = ( - f"
" - f"✅ {len(all_layouts)} layouts found (norb={norb}, " - f"ancillas={num_ab}). Best: err={sc}{ancilla_note}
") - + _generate_sweep(norb) except Exception as e: lbl_lucj_status.value = ( f"") else: lbl_lucj_status.value = ( f"
" + + " · ".join(chips) + "
") if chips else "") + + def _on_scan_progress(name, status, detail=''): + # Called from the WORKER thread — NEVER touch widgets here. Marshal + # the widget mutation onto the main loop. + def _apply(): + if name not in _scan['progress']: + _scan['order'].append(name) + _scan['progress'][name] = (status, detail) + _render_progress_line() + scan_marshal(_apply) + + def _entry_label(entry): + k = len(entry['ancillas']) + return (f"k={k} · #{entry['rank_in_stratum']} · " + f"LQS {entry['product_score'] * 100.0:.1f}%") + + def _render_targets(targets): + rows = [] + for t in targets: + if t['eligible']: + rows.append(f"" + f"{esc(str(t['name']))} ✓") + else: + rows.append(f"{esc(str(t['name']))} " + f"— {esc(str(t['reason']))}") + scan_results_box.children = [HTML( + "
Targets:
" + + "
".join(rows) + "
")] + + def _stage_handoff(backend_name, candidate): + hook = inter_qpu_handoff[0] if inter_qpu_handoff else None + if hook is None: + lbl_scan_progress.value = ( + "
Inter-QPU panel " + "unavailable — cannot open a remote candidate.
") + return + # A handoff must never break the scan UI. + with contextlib.suppress(Exception): + hook(backend_name, candidate) + + def _render_results(scan_result): + results = scan_result['results'] + head = ("" + "" + "" + "" + "" + "" + "") + body = [] + for r in results: + name = esc(str(r['name'])) + fam = esc(str(r['family'] or '?')) + if r['error']: + body.append( + f"" + f"" + f"" + f"") + elif r['best_lqs'] is None: + body.append( + f"" + f"" + f"" + f"") + else: + lqs = esc(f"{r['best_lqs'] * 100.0:.1f}%") + ncand = sum(len(v) for v in r['sweep']['strata'].values()) + body.append( + f"" + f"" + f"" + f"" + f"") + children = [HTML(head + "".join(body) + "
QPUfamilybest LQSkcands
{name}{fam}✗ " + f"{esc(str(r['error']))}
{name}{fam}no candidates" + f"
{name}{fam}{lqs}" + f"{esc(str(r['best_k']))}" + f"{esc(str(ncand))}
")] + + # Per-QPU stratified dropdowns (same label format as single-circuit). + for r in results: + sweep = r.get('sweep') + if not sweep: + continue + strata = sweep['strata'] + flat, dd_opts = [], [] + for k in sorted(strata.keys(), reverse=True): + for entry in strata[k]: + dd_opts.append((_entry_label(entry), len(flat))) + flat.append(entry) + if not dd_opts: + continue + children.append(HTML( + f"
" + f"{esc(str(r['name']))} — {_format_best_per_k(strata)}
")) + dd = Dropdown(options=dd_opts, value=None, description='Layout:', + layout=W, style={'description_width': '50px'}) + det = HTML("") + + def _make_cb(qpu_name, flatlist, detail_lbl): + def _cb(change): + idx = change['new'] + if idx is None or idx >= len(flatlist): + return + entry = flatlist[idx] + detail_lbl.value = ( + f"
" + f"α: {esc(', '.join(str(q) for q in entry['alpha']))}
" + f"β: {esc(', '.join(str(q) for q in entry['beta']))}
" + f"ancillas: " + f"{esc(', '.join(str(q) for q in entry['ancillas']))}" + f"
") + # Drive the inter-QPU panel — NEVER touch C1 / current layout. + _stage_handoff(qpu_name, entry) + return _cb + dd.observe(_make_cb(r['name'], flat, det), names='value') + children.extend([dd, det]) + + scan_results_box.children = children + + def _on_scan_done(scan_result): + _render_results(scan_result) + btn_scan_qpus.disabled = False + btn_scan_qpus.description = '🌐 Scan all QPUs' + + def _on_scan_error(err): + lbl_scan_progress.value = ( + f"
❌ Scan failed: " + f"{esc(str(err))}
") + btn_scan_qpus.disabled = False + btn_scan_qpus.description = '🌐 Scan all QPUs' + + def _on_scan_click(b): + if state.active_backend is None or state.active_service is None: + lbl_scan_progress.value = ( + "❌ Connect a " + "backend first.") + return + from ..qpu_scan import list_scan_targets, scan_qpus, _detect_family + from ..props_shim import make_scan_get_props + + norb = lucj_norb_slider.value + min_val = lucj_min_ancilla.value + min_bridges = None if (min_val is None or min_val <= 0) else min_val + try: + family = _detect_family(state.active_backend) + except Exception: + family = None + + targets = list_scan_targets( + state, norb, same_family_as=family, + include_other_families=chk_scan_other_families.value) + _render_targets(targets) # immediate feedback + + eligible = [t for t in targets if t['eligible']] + if not eligible: + lbl_scan_progress.value = ( + "
No eligible " + "backends for this norb / family scope.
") + return + + _scan['progress'].clear() + _scan['order'].clear() + btn_scan_qpus.disabled = True + btn_scan_qpus.description = '⏳ Scanning...' + get_backend = state.active_service.backend + get_props = make_scan_get_props(state) + + def _work(): + return scan_qpus(eligible, norb, get_backend, get_props, + min_bridges=min_bridges, top_n=3, + progress_cb=_on_scan_progress) + scan_spawn_bg(_work, on_done=_on_scan_done, on_error=_on_scan_error) + + btn_scan_qpus.on_click(_on_scan_click) + # ── Multi-circuit LUCJ generate ────────────────────────────── def _on_lucj_multi(b): if state.active_backend is None: diff --git a/tests/test_props_shim.py b/tests/test_props_shim.py new file mode 100644 index 0000000..42aac5b --- /dev/null +++ b/tests/test_props_shim.py @@ -0,0 +1,108 @@ +"""Tests for qpu_mapper.props_shim — the cache-aware props adapter. + +t1 (the crux): CachedPropsShim built from B0.a-shaped dicts answers +readout_error(q) and gate_error(name, pair) for both edge orders, and +raises a clear KeyError on any missing lookup. Plus a factory cache-hit +reconstruction test with fakes (offline, no qiskit, no network). +""" +from types import SimpleNamespace + +import numpy as np +import pytest + +from qpu_mapper.props_shim import CachedPropsShim, make_scan_get_props + + +def _fixtures(): + # Mirrors data.get_props_for_datetime's shapes: per-qubit arrays and + # per-edge arrays parallel to `edges`. + edges = [(0, 1), (1, 2), (2, 3)] + qubit_props = { + 'readout_error': np.array([0.010, 0.020, 0.030, 0.040]), + 't1': np.array([100.0, 110.0, 120.0, 130.0]), + } + gate_props = { + 'cz_error': np.array([0.001, 0.002, 0.003]), + 'gate_length': np.array([200.0, 210.0, 220.0]), + } + return qubit_props, gate_props, edges + + +# ── t1: the crux ──────────────────────────────────────────────────────────── + +def test_readout_error_by_qubit(): + qp, gp, edges = _fixtures() + shim = CachedPropsShim(qp, gp, edges) + assert shim.readout_error(0) == pytest.approx(0.010) + assert shim.readout_error(3) == pytest.approx(0.040) + assert isinstance(shim.readout_error(1), float) + + +def test_gate_error_both_pair_orders(): + qp, gp, edges = _fixtures() + shim = CachedPropsShim(qp, gp, edges) + # (1,2) is index 1 → 0.002; reverse must give the same value. + assert shim.gate_error('cz', (1, 2)) == pytest.approx(0.002) + assert shim.gate_error('cz', (2, 1)) == pytest.approx(0.002) + assert shim.gate_error('cz', (0, 1)) == pytest.approx(0.001) + assert shim.gate_error('cz', (3, 2)) == pytest.approx(0.003) + # gate_name is informational — a different name still resolves by edge. + assert shim.gate_error('ecr', (0, 1)) == pytest.approx(0.001) + + +def test_missing_qubit_raises_keyerror(): + qp, gp, edges = _fixtures() + shim = CachedPropsShim(qp, gp, edges) + with pytest.raises(KeyError): + shim.readout_error(999) + + +def test_missing_edge_raises_keyerror(): + qp, gp, edges = _fixtures() + shim = CachedPropsShim(qp, gp, edges) + with pytest.raises(KeyError): + shim.gate_error('cz', (0, 3)) # not an edge in the map + + +def test_missing_prop_key_raises_on_construction(): + qp, gp, edges = _fixtures() + with pytest.raises(KeyError): + CachedPropsShim({'t1': qp['t1']}, gp, edges) # no readout_error + with pytest.raises(KeyError): + CachedPropsShim(qp, {'gate_length': gp['gate_length']}, edges) # no cz_error + + +def test_custom_gate_key(): + qp = {'readout_error': [0.01, 0.02]} + gp = {'ecr_error': [0.005]} + shim = CachedPropsShim(qp, gp, [(0, 1)], gate_key='ecr_error') + assert shim.gate_error('ecr', (0, 1)) == pytest.approx(0.005) + + +# ── factory: cache-hit reconstruction (no live fetch) ─────────────────────── + +def test_factory_cache_hit(monkeypatch): + qp, gp, edges = _fixtures() + + # Fake backend: coupling map + num_qubits + a 2Q gate + a name. + backend = SimpleNamespace( + name='ibm_fake', + num_qubits=4, + coupling_map=SimpleNamespace(get_edges=lambda: list(edges)), + operation_names=['cz', 'sx', 'rz', 'x'], + ) + + from qpu_mapper import data + monkeypatch.setattr(data, 'list_known_calibrations', + lambda name, day: [{'last_update': '2026-07-12 09:00:00'}]) + monkeypatch.setattr(data, '_load_calibration', lambda name, ts: (qp, gp)) + # properties() must NOT be called on a cache hit. + backend.properties = lambda: (_ for _ in ()).throw( + AssertionError("live fetch on cache hit")) + + state = SimpleNamespace(active_backend_name='current') + get_props = make_scan_get_props(state, now='2026-07-12') + props = get_props(backend) + + assert props.readout_error(2) == pytest.approx(0.030) + assert props.gate_error('cz', (2, 1)) == pytest.approx(0.002) diff --git a/tests/test_qpu_scan.py b/tests/test_qpu_scan.py new file mode 100644 index 0000000..430a4c8 --- /dev/null +++ b/tests/test_qpu_scan.py @@ -0,0 +1,186 @@ +"""Tests for qpu_mapper.qpu_scan — the multi-QPU scan engine. + +Offline, deterministic, no qiskit, no network. Fake backends are +SimpleNamespaces exposing exactly what family/size detection reads +(``name`` / ``num_qubits`` / ``processor_type``); the ancilla sweep is +monkeypatched with canned dicts (real VF2 has its own tests). +""" +from types import SimpleNamespace + +import pytest + +from qpu_mapper.qpu_scan import list_scan_targets, scan_qpus + + +def _mk_backend(name, family, n_qubits): + proc = {'family': family, 'revision': '1'} if family else None + return SimpleNamespace(name=name, processor_type=proc, num_qubits=n_qubits) + + +def _canned_sweep(strata, **meta): + base = { + 'strata': strata, + 'k_max_effective': max(strata) if strata else 0, + 'min_bridges': min(strata) if strata else 0, + 'vf2_truncated': False, + 'n_raw_embeddings': 1, + 'n_candidates_scored': 1, + } + base.update(meta) + return base + + +def _entry(prod, k): + """One sweep candidate with `k` ancillas and the given product_score.""" + return { + 'layout': [0, 1], 'alpha': [0], 'beta': [1], + 'ancillas': list(range(2, 2 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 1.0, + 'rank_in_stratum': 1, 'source': 'vf2', + } + + +# ── t1: list_scan_targets — flags and reasons ─────────────────────────────── + +def test_list_scan_targets_flags_and_reasons(): + service = SimpleNamespace(backends=lambda: [ + _mk_backend('ibm_a', 'Heron', 156), # same family, OK + _mk_backend('ibm_b', 'Heron', 156), # same family, OK + _mk_backend('ibm_c', 'Nighthawk', 120), # other family + _mk_backend('ibm_d', 'Heron', 6), # same family, too small + _mk_backend('ibm_e', None, 200), # unknown family + ]) + # norb=4 → floor = 2*4+1 = 9 qubits. + targets = list_scan_targets(service, 4, same_family_as='Heron r3') + by = {t['name']: t for t in targets} + + assert by['ibm_a']['eligible'] and by['ibm_a']['reason'] is None + assert by['ibm_b']['eligible'] + assert by['ibm_a']['family'] == 'Heron' + + assert not by['ibm_c']['eligible'] + assert by['ibm_c']['reason'] == 'different family (Nighthawk)' + + assert not by['ibm_d']['eligible'] + assert by['ibm_d']['reason'] == 'needs >= 9 qubits, has 6' + + assert not by['ibm_e']['eligible'] + assert by['ibm_e']['reason'] == 'family unknown' + + # include_other_families flips the family-filtered one to eligible, + # keeping its label; the too-small one stays ineligible (size gate). + widened = {t['name']: t for t in list_scan_targets( + service, 4, same_family_as='Heron r3', include_other_families=True)} + assert widened['ibm_c']['eligible'] + assert widened['ibm_c']['family'] == 'Nighthawk' + assert widened['ibm_e']['eligible'] # unknown family now included + assert not widened['ibm_d']['eligible'] # still too small + + +# ── t2: scan happy path — ranking + progress order ────────────────────────── + +def test_scan_happy_path_sorted_and_progress(monkeypatch): + scores = {'ibm_a': 0.30, 'ibm_b': 0.50} + + def fake_sweep(norb, backend, props, **kw): + return _canned_sweep({2: [_entry(scores[backend.name], 2)]}) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", fake_sweep) + + backends = {'ibm_a': _mk_backend('ibm_a', 'Heron', 156), + 'ibm_b': _mk_backend('ibm_b', 'Heron', 156)} + targets = [{'name': 'ibm_a', 'family': 'Heron', 'eligible': True}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True}] + + events = [] + out = scan_qpus( + targets, 4, + get_backend=lambda n: backends[n], + get_props=lambda b: object(), + progress_cb=lambda name, status, detail='': events.append((name, status))) + + # Sorted by best_lqs desc → ibm_b (0.50) before ibm_a (0.30). + assert [r['name'] for r in out['results']] == ['ibm_b', 'ibm_a'] + assert out['n_scanned'] == 2 and out['n_failed'] == 0 and out['n_skipped'] == 0 + # progress: start→ok per backend, in INPUT order (not sorted). + assert events == [ + ('ibm_a', 'start'), ('ibm_a', 'ok'), + ('ibm_b', 'start'), ('ibm_b', 'ok'), + ] + + +# ── t3: isolation — one backend failing doesn't kill the scan ─────────────── + +def test_scan_isolation_on_props_failure(monkeypatch): + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, backend, props, **kw: _canned_sweep({2: [_entry(0.4, 2)]})) + + backends = {'ibm_a': _mk_backend('ibm_a', 'Heron', 156), + 'ibm_b': _mk_backend('ibm_b', 'Heron', 156)} + + def get_props(backend): + if backend.name == 'ibm_a': + raise RuntimeError('calibration fetch boom') + return object() + + targets = [{'name': 'ibm_a', 'family': 'Heron', 'eligible': True}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True}] + + out = scan_qpus(targets, 4, get_backend=lambda n: backends[n], + get_props=get_props) + + assert out['n_failed'] == 1 and out['n_scanned'] == 1 + by = {r['name']: r for r in out['results']} + assert by['ibm_a']['error'] and 'boom' in by['ibm_a']['error'] + assert by['ibm_a']['sweep'] is None + assert by['ibm_b']['error'] is None and by['ibm_b']['best_lqs'] == 0.4 + # Failed backend sorts to the end. + assert out['results'][-1]['name'] == 'ibm_a' + + +# ── t4: best_lqs / best_k extraction ──────────────────────────────────────── + +def test_best_lqs_extraction(monkeypatch): + # Max product_score is the k=1 entry (0.90); k=3 top is 0.20. + strata = { + 3: [_entry(0.20, 3)], + 2: [_entry(0.55, 2)], + 1: [_entry(0.90, 1)], + } + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, backend, props, **kw: _canned_sweep(strata)) + + out = scan_qpus( + [{'name': 'ibm_a', 'family': 'Heron', 'eligible': True}], 4, + get_backend=lambda n: _mk_backend(n, 'Heron', 156), + get_props=lambda b: object()) + + r = out['results'][0] + assert r['best_lqs'] == 0.90 + assert r['best_k'] == 1 + + +# ── t5: empty eligible set ────────────────────────────────────────────────── + +def test_scan_empty_targets(): + out = scan_qpus([], 4, get_backend=lambda n: None, get_props=lambda b: None) + assert out['results'] == [] + assert out['n_scanned'] == 0 and out['n_failed'] == 0 and out['n_skipped'] == 0 + + +def test_scan_skips_ineligible_targets(monkeypatch): + """Ineligible targets are skipped (never swept), counted in n_skipped.""" + called = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: called.append(1) or _canned_sweep({2: [_entry(0.4, 2)]})) + + targets = [{'name': 'ibm_x', 'family': 'Nighthawk', 'eligible': False, + 'reason': 'different family (Nighthawk)'}] + out = scan_qpus(targets, 4, get_backend=lambda n: None, get_props=lambda b: None) + + assert called == [] # sweep never invoked + assert out['n_skipped'] == 1 and out['n_scanned'] == 0 + assert out['results'][0]['sweep'] is None diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py new file mode 100644 index 0000000..bcc347c --- /dev/null +++ b/tests/test_scan_ui.py @@ -0,0 +1,216 @@ +"""Headless tests for the multi-QPU scan UI (Component 3b) + M1/M2. + +Offline: the data layer is stubbed, and qpu_scan.scan_qpus / list_scan_targets +are monkeypatched with canned results (no VF2, no network). The background +spawn and the progress marshal primitive are injected synchronously so the +handler runs deterministically. +""" +from types import SimpleNamespace + +import numpy as np +import pytest + +from qpu_mapper.ui.lucj_panel import _format_sweep_status + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover - defensive + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _sweep(prod_hi, prod_lo): + def entry(prod, k): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(range(4, 4 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 1.0, + 'rank_in_stratum': 1, 'source': 'vf2'} + return {'strata': {2: [entry(prod_lo, 2)], 1: [entry(prod_hi, 1)]}, + 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 10, 'n_candidates_scored': 20} + + +def _fake_scan_result(error='fetch failed'): + return { + 'results': [ + {'name': 'ibm_b', 'family': 'Heron', 'sweep': _sweep(0.60, 0.50), + 'best_lqs': 0.60, 'best_k': 1, 'error': None}, + {'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(0.40, 0.30), + 'best_lqs': 0.40, 'best_k': 1, 'error': None}, + {'name': 'ibm_c', 'family': 'Nighthawk', 'sweep': None, + 'best_lqs': None, 'best_k': None, 'error': error}, + ], + 'n_scanned': 2, 'n_failed': 1, 'n_skipped': 0, + } + + +def _targets(): + return [ + {'name': 'ibm_b', 'family': 'Heron', 'n_qubits': 156, + 'eligible': True, 'reason': None}, + {'name': 'ibm_a', 'family': 'Heron', 'n_qubits': 156, + 'eligible': True, 'reason': None}, + {'name': 'ibm_c', 'family': 'Nighthawk', 'n_qubits': 120, + 'eligible': True, 'reason': None}, + ] + + +def _build(monkeypatch, spawn=_sync_spawn, marshal=None): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + if marshal is not None: + monkeypatch.setattr(au, 'marshal_to_main', marshal) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: object()) + state.available_backends = ["ibm_a", "ibm_b", "ibm_c"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + + b = MapperUIBuilder(state) + b.build() + return b + + +def _patch_scan(monkeypatch, result=None, capture_progress=False): + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: _targets()) + res = result if result is not None else _fake_scan_result() + + def fake_scan(targets, norb, get_backend, get_props, **kw): + cb = kw.get('progress_cb') + if capture_progress and cb: + for r in res['results']: + cb(r['name'], 'start', '') + cb(r['name'], 'ok' if r['error'] is None else 'error', + r['error'] or '') + return res + monkeypatch.setattr(qs, 'scan_qpus', fake_scan) + + +def _dropdowns(children): + from ipywidgets import Dropdown + return [c for c in children if isinstance(c, Dropdown)] + + +# ── t2: scan happy path — table sorted, dropdowns, button re-enabled ──────── + +def test_scan_happy_path(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch) + b.btn_scan_qpus.click() + + children = b.scan_results_box.children + table_html = children[0].value + assert table_html.index('ibm_b') < table_html.index('ibm_a') # sorted + assert '60.0%' in table_html and '40.0%' in table_html + # One stratified dropdown per successful QPU. + assert len(_dropdowns(children)) == 2 + # Button re-enabled after completion. + assert b.btn_scan_qpus.disabled is False + + +# ── t3: progress marshaling — no direct-from-thread widget writes ─────────── + +def test_scan_progress_marshaled(monkeypatch): + captured = [] + b = _build(monkeypatch, marshal=lambda cb: captured.append(cb)) + _patch_scan(monkeypatch, capture_progress=True) + + b.btn_scan_qpus.click() + # Progress callbacks were marshaled, NOT applied directly: the progress + # label is still empty even though progress_cb fired during the scan. + assert b.lbl_scan_progress.value == "" + assert captured, "progress updates should have been marshaled" + + # Draining the marshaled callbacks updates the label on the main loop. + for cb in captured: + cb() + assert 'ibm_b' in b.lbl_scan_progress.value + assert '✓' in b.lbl_scan_progress.value + + +# ── t4: failed-backend row greyed with esc()'d error ──────────────────────── + +def test_scan_failed_row_escaped(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch, result=_fake_scan_result(error='boom ')) + b.btn_scan_qpus.click() + + table_html = b.scan_results_box.children[0].value + assert 'color:#999' in table_html # greyed + assert 'boom <x>' in table_html # esc()'d error, not raw '' + assert '' not in table_html + + +# ── t7: handoff — selecting a remote candidate stages it ──────────────────── + +def test_scan_handoff_on_select(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch) + + staged = [] + b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) + + b.btn_scan_qpus.click() + dds = _dropdowns(b.scan_results_box.children) + dds[0].value = 0 # pick ibm_b's top candidate + + assert len(staged) == 1 + name, cand = staged[0] + assert name == 'ibm_b' + # flat index 0 = top stratum (k descending) = the k=2 entry. + assert cand['ancillas'] == [4, 5] + + +# ── t5: M1 — sweep mode greys out the score checkbox ──────────────────────── + +def test_m1_score_checkbox_toggle(monkeypatch): + b = _build(monkeypatch) + # Default: Ancilla='Auto' (-1) → sweep mode → score checkbox disabled. + assert b.lucj_ancilla_dd.value == -1 + assert b.lucj_chk_score.disabled is True + + b.lucj_ancilla_dd.value = 2 # exact count → legacy mode + assert b.lucj_chk_score.disabled is False + + b.lucj_ancilla_dd.value = -1 # back to sweep + assert b.lucj_chk_score.disabled is True + + +# ── t6: M2 — per-stratum status line format ───────────────────────────────── + +def test_m2_status_line_format(): + res = _sweep(0.40, 0.30) # strata 2→30%, 1→40% + res['k_max_effective'] = 2 + res['min_bridges'] = 1 + res['n_raw_embeddings'] = 214 + line = _format_sweep_status(res) + assert line == "Sweep: k=2..1 · 214 embeddings · best per k: 2→30.0% · 1→40.0%" From 26642ac8d40a591d93647f336f0266bf93e0842a Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 19:38:23 -0400 Subject: [PATCH 04/66] Add stability-filtered search: chip-wide volatility, hard filter with auto-relax valve --- qpu_mapper/ancilla_sweep.py | 42 ++++++-- qpu_mapper/stability_filter.py | 167 ++++++++++++++++++++++++++++++++ tests/test_stability_filter.py | 169 +++++++++++++++++++++++++++++++++ 3 files changed, 371 insertions(+), 7 deletions(-) create mode 100644 qpu_mapper/stability_filter.py create mode 100644 tests/test_stability_filter.py diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index 2717e0b..b8e6d50 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -78,6 +78,7 @@ _get_two_q_gate_name, _make_backend_cmap_pygraph, _MAX_RAW_VF2_MAPPINGS, + _remove_nodes_from_graph, create_lucj_zigzag_layout, ) @@ -116,7 +117,7 @@ def _safe_gate_error(props, gate_name, u, v): def sweep_ancilla_layouts(norb, backend, props, *, min_bridges=None, top_n=3, - mapping_cap=None) -> dict: + mapping_cap=None, exclude_qubits=None) -> dict: """One-shot ancilla sweep: VF2 at the geometric max bridge count, then derive every lower-k variant by bridge subtraction, score, and return the top_n candidates per ancilla count. @@ -133,6 +134,10 @@ def sweep_ancilla_layouts(norb, backend, props, *, top_n: Max candidates returned per ancilla count. mapping_cap: Override the VF2 mapping cap (default ``auto_lucj._MAX_RAW_VF2_MAPPINGS``). Mainly for tests. + exclude_qubits: optional set of physical qubit ids to remove from the + coupling graph BEFORE template creation (a hard search-space + filter, e.g. volatile qubits from stability analysis). ``None`` or + empty → byte-for-byte identical to the unfiltered sweep. Returns { 'strata': {k: [entry, ...]}, # k descending; len<=top_n each @@ -141,6 +146,8 @@ def sweep_ancilla_layouts(norb, backend, props, *, 'vf2_truncated': bool, # 2000-cap hit (surface in UI!) 'n_raw_embeddings': int, # complete VF2 mappings used 'n_candidates_scored': int, # total variants scored (pre-dedupe) + 'excluded_qubits': [...], # sorted list actually pruned (empty + # when exclude_qubits is None) } entry = { 'layout': [...], # chain qubits (alpha+beta) @@ -154,12 +161,29 @@ def sweep_ancilla_layouts(norb, backend, props, *, } """ # ---- 1. Build the backend graph and the k_max template ---------------- - backend_graph = _make_backend_cmap_pygraph(backend=backend) + # `full_graph` keeps physical-qubit ids as node INDICES (props precompute + # relies on that). When excluding, we prune a SEPARATE `search_graph`: + # _remove_nodes_from_graph reindexes, so we tag physical ids into node + # data first and recover them via `_key_to_phys` when reading VF2 keys. + full_graph = _make_backend_cmap_pygraph(backend=backend) + excluded_sorted = sorted(int(q) for q in exclude_qubits) if exclude_qubits else [] + if excluded_sorted: + for i in full_graph.node_indices(): + full_graph[i] = i + search_graph = _remove_nodes_from_graph(full_graph, set(excluded_sorted)) + + def _key_to_phys(k): + return search_graph[k] + else: + search_graph = full_graph + + def _key_to_phys(k): + return k k_max = (norb + 3) // 4 # ceil(norb / 4): the geometric bridge ceiling template, k_max_effective = create_lucj_zigzag_layout( num_orbitals=norb, - backend_coupling_graph=backend_graph, + backend_coupling_graph=search_graph, requested_bridges=k_max, ) if k_max_effective < 1: @@ -180,7 +204,7 @@ def sweep_ancilla_layouts(norb, backend, props, *, # ---- 3. Collect VF2 embeddings, detect truncation --------------------- cap = mapping_cap if mapping_cap is not None else _MAX_RAW_VF2_MAPPINGS - mappings = _collect_vf2_mappings(backend_graph, template, cap=cap) + mappings = _collect_vf2_mappings(search_graph, template, cap=cap) # The helper only *logs* truncation; detect it by the cap being reached. vf2_truncated = len(mappings) >= cap if vf2_truncated: @@ -192,7 +216,7 @@ def sweep_ancilla_layouts(norb, backend, props, *, for mapping in mappings: layout = [None] * expected_size for key, value in mapping.items(): - layout[value] = key + layout[value] = _key_to_phys(key) if any(v is None for v in layout): _log.debug("Ancilla sweep: skipping incomplete VF2 mapping") continue @@ -209,7 +233,10 @@ def sweep_ancilla_layouts(norb, backend, props, *, if gate_name is None: raise RuntimeError("Could not determine the backend 2Q gate name.") - node_indices = list(backend_graph.node_indices()) + # Precompute over the FULL graph (indices == physical ids). Excluded + # qubits/edges may be present here but never appear in any layout, so + # their entries are harmless. + node_indices = list(full_graph.node_indices()) max_id = max(node_indices) # readout array indexed by physical qubit id; penalty for anything absent. readout = np.full(max_id + 1, _UNCALIBRATED_PENALTY, dtype=float) @@ -217,7 +244,7 @@ def sweep_ancilla_layouts(norb, backend, props, *, readout[q] = _safe_readout(props, q) # physical-edge -> gate error, keyed by frozenset so direction is moot. edge_err = {} - for u, v in backend_graph.edge_list(): + for u, v in full_graph.edge_list(): edge_err[frozenset((u, v))] = _safe_gate_error(props, gate_name, u, v) def _edge_e(a, b): @@ -321,4 +348,5 @@ def _edge_e(a, b): 'vf2_truncated': vf2_truncated, 'n_raw_embeddings': n_raw_embeddings, 'n_candidates_scored': n_candidates_scored, + 'excluded_qubits': excluded_sorted, } diff --git a/qpu_mapper/stability_filter.py b/qpu_mapper/stability_filter.py new file mode 100644 index 0000000..95a263b --- /dev/null +++ b/qpu_mapper/stability_filter.py @@ -0,0 +1,167 @@ +""" +stability_filter.py — Stability-aware ancilla sweep (pure, synchronous). + +Given cached calibration history, score every qubit's volatility, exclude the +volatile ones from the sweep's search space (a hard filter), and run +``ancilla_sweep.sweep_ancilla_layouts`` on the pruned chip — with an automatic +RELAX VALVE that re-admits the least-volatile excluded qubits when the filter +is too strict for ``norb`` to fit. + +All functions are pure and offline: history in, dict out. The volatility math +is NOT reimplemented here — it reuses ``stability.analyze_property_stability`` +(the same per-series detector the Stability Check panel uses), so the two views +can never diverge. Only the plumbing (assembling a per-qubit series across the +windowed history) lives here. + +Cap-pressure note: pruning shrinks the host graph, which usually DECREASES the +number of VF2 embeddings per template — but on a tight fit it can push VF2 +toward truncation. ``vf2_truncated`` propagates untouched from the sweep. +""" + +import logging + +from .ancilla_sweep import sweep_ancilla_layouts +from .stability import analyze_property_stability + +_log = logging.getLogger(__name__) + +# Volatility = analyze_property_stability's 'error' score = max/median - 1. +# The default threshold flags a qubit whose worst windowed day exceeded ~1.5× +# its own median readout error (score > 0.5) — a clear, repeated instability, +# not day-to-day noise. +_DEFAULT_THRESHOLD = 0.5 + +# Fraction of the initial excluded set re-admitted per relax step. +_RELAX_BATCH_FRAC = 0.20 + +_READOUT_KEY = 'readout_error' + + +def _windowed_dates(history, window_days, today): + dates = sorted(history.keys()) + if today is not None: + dates = [d for d in dates if d <= today] + if window_days and window_days > 0: + dates = dates[-window_days:] + return dates + + +def compute_qubit_volatility(history, window_days, *, today=None): + """Chip-wide per-qubit volatility from cached history (pure). + + Args: + history: ``{date_str: {'qubit_props': {'readout_error': array}, ...}}`` + — the shape of ``state.cal_history``. + window_days: use the most recent this-many dates. + today: optional upper bound date string; dates after it are ignored. + + Returns ``{qubit_id: volatility_score}`` — higher = more volatile. Reuses + ``stability.analyze_property_stability(series, 'error')['score']`` per + qubit (readout_error series). Qubits with fewer than the detector's + minimum valid samples score 0.0 (not enough data to judge). Empty history + → ``{}``. + """ + if not history: + return {} + dates = _windowed_dates(history, window_days, today) + if not dates: + return {} + + n_qubits = 0 + for d in dates: + arr = history[d].get('qubit_props', {}).get(_READOUT_KEY) + if arr is not None: + n_qubits = max(n_qubits, len(arr)) + + volatility = {} + for q in range(n_qubits): + series = [] + for d in dates: + arr = history[d].get('qubit_props', {}).get(_READOUT_KEY) + if arr is not None and q < len(arr): + series.append(arr[q]) + else: + series.append(float('nan')) + analysis = analyze_property_stability(series, kind='error') + volatility[q] = analysis['score'] + return volatility + + +def select_excluded(volatility, *, threshold): + """Qubit ids with volatility strictly over ``threshold``, sorted MOST + volatile first (so the relax valve re-admits from the least-volatile + tail).""" + over = [(q, v) for q, v in volatility.items() if v > threshold] + over.sort(key=lambda qv: qv[1], reverse=True) + return [q for q, _ in over] + + +def sweep_with_stability(norb, backend, props, history, *, + window_days=14, threshold=_DEFAULT_THRESHOLD, + min_bridges=None, top_n=3, mapping_cap=None): + """Stability-filtered ancilla sweep with an automatic relax valve. + + 1. Score volatility over the windowed history and build the excluded set. + 2. Run the sweep excluding those qubits. + 3. If the pruned graph cannot host ``norb`` (the sweep raises — zero + embeddings, no bridges fit, or template creation fails), re-admit the + LEAST-volatile excluded qubits in batches (``_RELAX_BATCH_FRAC`` of the + initial set per step, at least 1) and retry, until it fits or nothing + is left excluded. + 4. Return the sweep dict EXTENDED with a ``stability`` block. + + No / empty history → run the plain sweep and set + ``stability={'available': False}`` (never raises for lack of history). + """ + def _plain(): + res = sweep_ancilla_layouts( + norb, backend, props, min_bridges=min_bridges, + top_n=top_n, mapping_cap=mapping_cap) + res['stability'] = {'available': False} + return res + + if not history: + return _plain() + + volatility = compute_qubit_volatility(history, window_days) + if not volatility: + return _plain() + + excluded = select_excluded(volatility, threshold=threshold) # most→least + n_excluded_initial = len(excluded) + batch = max(1, int(n_excluded_initial * _RELAX_BATCH_FRAC)) + + current = list(excluded) + n_readmitted = 0 + relaxed = False + while True: + try: + res = sweep_ancilla_layouts( + norb, backend, props, min_bridges=min_bridges, + top_n=top_n, mapping_cap=mapping_cap, + exclude_qubits=set(current) or None) + break + except Exception as exc: + if not current: + # Even the unfiltered chip can't host norb — a real failure, + # not a filter-too-strict one. Propagate. + raise + relaxed = True + # Re-admit the least-volatile tail (current is most→least). + readmit = current[-batch:] + current = current[:-batch] + n_readmitted += len(readmit) + _log.info("Stability sweep: norb=%d didn't fit with %d excluded " + "(%s); re-admitted %d least-volatile, retrying", + norb, len(current) + len(readmit), exc, len(readmit)) + + res['stability'] = { + 'available': True, + 'window_days': window_days, + 'threshold': threshold, + 'n_excluded_initial': n_excluded_initial, + 'n_readmitted': n_readmitted, + 'excluded_final': sorted(current), + 'relaxed': relaxed, + } + return res diff --git a/tests/test_stability_filter.py b/tests/test_stability_filter.py new file mode 100644 index 0000000..85ab35c --- /dev/null +++ b/tests/test_stability_filter.py @@ -0,0 +1,169 @@ +"""Tests for qpu_mapper.stability_filter — the stability-aware sweep. + +Offline, deterministic. Two disconnected width-8 heavy-hex-like blocks +(the norb=8 host from the sweep tests): block A = ids 0..23, block B = +ids 24..47. Synthetic calibration history is crafted so specific qubits +spike (volatile). Real VF2 runs — the graphs are tiny — but there is no +qiskit dependency and no network. +""" +from types import SimpleNamespace + +import rustworkx + +from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts +from qpu_mapper.stability_filter import ( + compute_qubit_volatility, select_excluded, sweep_with_stability, +) + + +# ── synthetic backend / props (mirrors the ancilla-sweep test host) ───────── + +def _build_block(base, edges): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges.append((top[j], top[j + 1])) + edges.append((bot[j], bot[j + 1])) + for j in range(8): + edges.append((top[j], brg[j])) + edges.append((brg[j], bot[j])) + + +def _make_backend(): + edges = [] + _build_block(0, edges) # block A → ids 0..23 + _build_block(24, edges) # block B → ids 24..47 + g = rustworkx.PyDiGraph() + for i in range(48): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _Props: + def readout_error(self, q): + return 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def _history(spikes, n_dates=6, n_qubits=48): + """History where every qubit is flat 0.01 except `spikes` {qid: value}, + which get a single high sample on the last date → a high volatility score.""" + dates = [f"2026-07-{i + 1:02d}" for i in range(n_dates)] + hist = {} + for di, d in enumerate(dates): + arr = [0.01] * n_qubits + if di == n_dates - 1: + for q, val in spikes.items(): + arr[q] = val + hist[d] = {'qubit_props': {'readout_error': arr}, 'gate_props': {}} + return hist + + +def _all_qubits(res): + used = set() + for entries in res['strata'].values(): + for e in entries: + used.update(e['alpha']) + used.update(e['beta']) + used.update(e['ancillas']) + return used + + +# ── t1: volatility scoring ────────────────────────────────────────────────── + +def test_volatility_orders_volatile_above_stable(): + # q3 spikes hard, q10 mildly, q5 flat. + hist = _history({3: 0.06, 10: 0.02}) + vol = compute_qubit_volatility(hist, window_days=14) + assert vol[3] > vol[10] > vol[5] + assert vol[5] == 0.0 # flat series → no volatility + + +# ── t2: select_excluded ───────────────────────────────────────────────────── + +def test_select_excluded_threshold_and_order(): + vol = {3: 5.0, 2: 4.5, 10: 2.0, 5: 0.0, 7: 0.8} + excluded = select_excluded(vol, threshold=1.0) + assert excluded == [3, 2, 10] # >1.0, most-volatile first + assert 5 not in excluded and 7 not in excluded + + +# ── t3: filtered sweep never uses excluded qubits (A1 correctness) ────────── + +def test_filtered_sweep_excludes_qubits(): + backend, props = _make_backend(), _Props() + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, + exclude_qubits={4, 5}) + assert res['excluded_qubits'] == [4, 5] + used = _all_qubits(res) + assert 4 not in used and 5 not in used + assert res['strata'] # still found layouts (block B) + + +# ── t4: RELAX VALVE (the crux) ────────────────────────────────────────────── + +def test_relax_valve_readmits_least_volatile(): + backend, props = _make_backend(), _Props() + # Block A top row (0..3) + block B top row (24, 25) all volatile. Excluding + # ALL breaks BOTH blocks; re-admitting the least-volatile (25 then 24) + # restores block B while the most-volatile (3, block A) stays excluded. + hist = _history({3: 0.06, 2: 0.055, 1: 0.05, 0: 0.045, 24: 0.03, 25: 0.025}) + res = sweep_with_stability(8, backend, props, hist, + window_days=14, threshold=1.0, min_bridges=1) + + st = res['stability'] + assert st['available'] is True + assert st['relaxed'] is True + assert st['n_readmitted'] > 0 + assert st['n_excluded_initial'] == 6 + assert 3 in st['excluded_final'] # most-volatile survived + assert st['excluded_final'] == sorted(st['excluded_final']) + assert res['strata'] # sweep succeeded after relaxing + # The pruned-out qubits never appear in a returned candidate. + used = _all_qubits(res) + assert used.isdisjoint(set(st['excluded_final'])) + + +# ── t5: no history → plain sweep, stability unavailable ───────────────────── + +def test_no_history_runs_plain_sweep(): + backend, props = _make_backend(), _Props() + for empty in (None, {}): + res = sweep_with_stability(8, backend, props, empty, min_bridges=1) + assert res['stability'] == {'available': False} + assert res['strata'] + + +# ── t6: A1 non-regression — exclude_qubits=None path ──────────────────────── + +def test_a1_default_is_unfiltered(): + backend, props = _make_backend(), _Props() + base = sweep_ancilla_layouts(8, backend, props, min_bridges=1) + explicit_none = sweep_ancilla_layouts(8, backend, props, min_bridges=1, + exclude_qubits=None) + assert base['excluded_qubits'] == [] + assert explicit_none['excluded_qubits'] == [] + # Same strata shape (k range) with and without the (empty) exclusion. + assert list(base['strata'].keys()) == list(explicit_none['strata'].keys()) + + +# ── t7: metadata — sorted excluded_final, vf2_truncated propagated ────────── + +def test_metadata_and_truncation_propagation(): + backend, props = _make_backend(), _Props() + # A couple of volatile block-B bridge qubits (not chain-critical), plus a + # cap of 1 so VF2 truncates — the flag must survive the orchestrator. + hist = _history({40: 0.06, 41: 0.05}) + res = sweep_with_stability(8, backend, props, hist, window_days=14, + threshold=1.0, min_bridges=1, mapping_cap=1) + assert res['vf2_truncated'] is True # propagated untouched + st = res['stability'] + assert st['available'] is True + assert st['excluded_final'] == sorted(st['excluded_final']) + assert res['excluded_qubits'] == sorted(res['excluded_qubits']) From adf9a7bc7c18547ace35a42808874a2d04cb9447 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 19:53:24 -0400 Subject: [PATCH 05/66] Add stability filter UI: opt-in filtered sweep with relax banner, cached-only scan filtering --- qpu_mapper/ui/builder.py | 60 ++++++++++- qpu_mapper/ui/lucj_panel.py | 179 +++++++++++++++++++++++++++++++-- tests/test_stability_ui.py | 194 ++++++++++++++++++++++++++++++++++++ 3 files changed, 425 insertions(+), 8 deletions(-) create mode 100644 tests/test_stability_ui.py diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index e25733c..7e7bdeb 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -16,7 +16,8 @@ import numpy as np from ipywidgets import ( Output, VBox, HBox, RadioButtons, Label, ColorPicker, - IntSlider, FloatSlider, BoundedIntText, Button, Layout, Checkbox, Tab, HTML, Dropdown, + IntSlider, FloatSlider, BoundedIntText, BoundedFloatText, Button, Layout, + Checkbox, Tab, HTML, Dropdown, Textarea, Text, ToggleButtons, Accordion, DatePicker, FileUpload, IntProgress, ) @@ -328,8 +329,16 @@ def _run_pipeline(self): scan_spawn_bg=default_spawn_bg, scan_marshal=marshal_to_main, inter_qpu_handoff=self._inter_qpu_handoff, + # Stability filter (V1/V2/V3). + chk_stability_filter=self.chk_stability_filter, + rb_stability_window=self.rb_stability_window_auto, + ft_stability_threshold=self.ft_stability_threshold, + stability_ctrl_box=self.stability_ctrl_box, + lbl_lucj_stability=self.lbl_lucj_stability, + chk_scan_stability=self.chk_scan_stability, ) setup_lucj_callbacks(_lucj_ctx) + self._refresh_stability_filter_availability() # ── PNG save popup ─────────────────────────────────────────── # ui.png_export builds the popup + sliders + checkbox and wires @@ -1224,6 +1233,34 @@ def _build_auto_lucj_widgets(self, W): # Sweep truncation banner (VF2 cap hit); empty/hidden otherwise. self.lbl_lucj_trunc = HTML("") + # ── Stability filter (opt-in) ──────────────────────────── + self.chk_stability_filter = Checkbox( + value=False, description='🛡 Stability filter', layout=W, + tooltip='Exclude volatile qubits (from calibration history) ' + 'before the sweep') + self.rb_stability_window_auto = RadioButtons( + options=[('7 days', 7), ('14 days', 14), ('30 days', 30)], + value=14, description='Window:', layout=W, + style={'description_width': '70px'}) + self.ft_stability_threshold = BoundedFloatText( + value=0.5, min=0.0, max=100.0, step=0.1, + description='Threshold:', layout=Layout(width='230px'), + style={'description_width': '90px'}, + tooltip='Volatility score = max/median − 1; higher threshold = ' + 'more tolerant (fewer qubits excluded)') + # Window + threshold row, revealed only when the filter is on. + self.stability_ctrl_box = VBox( + [self.rb_stability_window_auto, self.ft_stability_threshold]) + self.stability_ctrl_box.layout.display = 'none' + self.lbl_lucj_stability = HTML("") + # Scan sub-option: filter each scanned backend with CACHED history only. + self.chk_scan_stability = Checkbox( + value=False, + description='apply stability filter (cached history only)', + layout=W, + tooltip='Filter each scanned backend using its CACHED history ' + 'only — no remote history fetch in this version') + # ── Multi-QPU scan cluster ─────────────────────────────── self.btn_scan_qpus = Button( description='🌐 Scan all QPUs', button_style='info', layout=W, @@ -1608,6 +1645,22 @@ def _build_auto_view(self): self.btn_load_style, ]) + def _refresh_stability_filter_availability(self): + """Enable the 🛡 Stability filter only when calibration history is + loaded; otherwise disable it with a hint. Re-evaluated each time the + Auto view is (re)built, so it flips on after history is fetched.""" + state = self.state + available = bool(getattr(state, 'cal_history', None) + and getattr(state, 'cal_history_dates', None)) + self.chk_stability_filter.disabled = not available + if available: + self.chk_stability_filter.tooltip = ( + 'Exclude volatile qubits (from calibration history) before ' + 'the sweep') + else: + self.chk_stability_filter.tooltip = ( + 'Fetch calibration history first (Stability Check / Multi-day)') + def _build_auto_lucj_view(self): """Build the 'Auto' nav tab view (LUCJ chemistry mode). @@ -1621,6 +1674,7 @@ def _build_auto_lucj_view(self): ``lucj_multi_ancillas`` to override it per sub-circuit (blank falls back to the dropdown). """ + self._refresh_stability_filter_availability() return VBox([ HTML("
" "🤖 Auto-LUCJ Layout Engine
"), @@ -1631,6 +1685,9 @@ def _build_auto_lucj_view(self): self.lucj_ancilla_dd, self.lucj_min_ancilla, self.lucj_chk_score, + self.chk_stability_filter, + self.stability_ctrl_box, + self.lbl_lucj_stability, self.btn_lucj_run, self.lbl_lucj_trunc, self.lbl_lucj_status, @@ -1639,6 +1696,7 @@ def _build_auto_lucj_view(self): "🌐 Scan All QPUs"), self.btn_scan_qpus, self.chk_scan_other_families, + self.chk_scan_stability, self.lbl_scan_progress, self.scan_results_box, HTML("
" diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 26a78f7..46cd675 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -257,9 +257,25 @@ def _generate_sweep(norb): min_val = lucj_min_ancilla.value min_bridges = None if (min_val is None or min_val <= 0) else min_val - res = sweep_ancilla_layouts( - norb, state.active_backend, state.initial_props, - min_bridges=min_bridges) + # V2: opt-in stability filter (drop-in superset of the plain sweep). + history = getattr(state, 'cal_history', None) + if _stability_filter_active() and history: + from ..stability_filter import sweep_with_stability + res = sweep_with_stability( + norb, state.active_backend, state.initial_props, history, + window_days=rb_stability_window.value, + threshold=ft_stability_threshold.value, + min_bridges=min_bridges) + _render_stability_banner(res.get('stability'), norb) + else: + res = sweep_ancilla_layouts( + norb, state.active_backend, state.initial_props, + min_bridges=min_bridges) + if _stability_filter_active(): + # Checkbox on but no history dict → skipped note. + _render_stability_banner(None, norb) + else: + lbl_lucj_stability.value = "" strata = res['strata'] # Flatten k descending, entries in stratum order; the dropdown value @@ -357,6 +373,144 @@ def _on_ancilla_mode_change(change=None): scan_marshal = ctx.scan_marshal inter_qpu_handoff = ctx.inter_qpu_handoff # shared cell → stage hook + # ── Stability filter (V1/V2/V3) ────────────────────────────── + chk_stability_filter = ctx.chk_stability_filter + rb_stability_window = ctx.rb_stability_window + ft_stability_threshold = ctx.ft_stability_threshold + stability_ctrl_box = ctx.stability_ctrl_box + lbl_lucj_stability = ctx.lbl_lucj_stability + chk_scan_stability = ctx.chk_scan_stability + + def _on_stability_toggle(change=None): + # Reveal the window/threshold row only when the filter is on. + stability_ctrl_box.layout.display = ( + 'block' if chk_stability_filter.value else 'none') + if not chk_stability_filter.value: + lbl_lucj_stability.value = "" + chk_stability_filter.observe(_on_stability_toggle, names='value') + _on_stability_toggle() + + def _stability_filter_active(): + return bool(chk_stability_filter.value + and not chk_stability_filter.disabled) + + def _render_stability_banner(stab, norb): + """Render res['stability'] (V2): filtered / relaxed / unavailable.""" + if stab is None or not stab.get('available', False): + lbl_lucj_stability.value = ( + "
" + "🛡 no history in range — filter skipped
") + return + if stab.get('relaxed'): + lbl_lucj_stability.value = ( + f"
🛡 filter too strict for norb=" + f"{esc(str(norb))} — re-admitted " + f"{esc(str(stab.get('n_readmitted')))} of " + f"{esc(str(stab.get('n_excluded_initial')))} " + f"(most-volatile still excluded)
") + else: + n = len(stab.get('excluded_final', [])) + lbl_lucj_stability.value = ( + f"
🛡 filtered {esc(str(n))} volatile qubits " + f"(window {esc(str(stab.get('window_days')))}d)
") + + def _cached_history_for(backend_name): + """Assemble a per-backend history dict from the DISK CACHE ONLY (no + remote fetch). Empty when the backend has no cached snapshots.""" + from .. import data + try: + known = data.list_known_calibrations(backend_name) + except Exception: + return {} + hist = {} + for entry in known or []: + ts = entry.get('last_update') + if not ts: + continue + cached = data._load_calibration(backend_name, ts) + if cached: + hist[ts] = {'qubit_props': cached[0], 'gate_props': cached[1]} + return hist + + def _stability_badge(r): + stab = r.get('stability') + if not stab: + return "" + if not stab.get('available', False): + return ("stability: n/a " + "(no cached history)") + n = len(stab.get('excluded_final', [])) + extra = " (relaxed)" if stab.get('relaxed') else "" + return (f"🛡 −{esc(str(n))} " + f"qubits{extra}") + + def _scan_filtered(eligible, norb, get_backend, get_props, min_bridges): + """Handler-side per-target scan with cached-history stability filter. + + qpu_scan.scan_qpus hardcodes the unfiltered sweep and exposes no + exclusion/sweep-fn hook, so the filtered scan can't route through it + without editing the frozen engine. This mirrors its contract + (per-backend isolation, progress_cb, best_lqs sort) and adds a + per-result 'stability' block. Cached history ONLY — no remote fetch. + """ + from ..ancilla_sweep import sweep_ancilla_layouts + from ..stability_filter import sweep_with_stability + window = rb_stability_window.value + threshold = ft_stability_threshold.value + results = [] + n_scanned = n_failed = n_skipped = 0 + for t in eligible: + name = t.get('name') if isinstance(t, dict) else t + family = t.get('family') if isinstance(t, dict) else None + _on_scan_progress(name, 'start', '') + try: + backend = get_backend(name) + props = get_props(backend) + hist = _cached_history_for(name) + if hist: + res = sweep_with_stability( + norb, backend, props, hist, window_days=window, + threshold=threshold, min_bridges=min_bridges, top_n=3) + stab = res.get('stability', {'available': False}) + else: + res = sweep_ancilla_layouts( + norb, backend, props, min_bridges=min_bridges, top_n=3) + stab = {'available': False, 'reason': 'no cached history'} + except Exception as exc: + n_failed += 1 + results.append({'name': name, 'family': family, 'sweep': None, + 'best_lqs': None, 'best_k': None, + 'error': str(exc), + 'stability': {'available': False}}) + _on_scan_progress(name, 'error', str(exc)) + continue + best_lqs, best_k = None, None + for k, entries in res['strata'].items(): + for e in entries: + if best_lqs is None or e['product_score'] > best_lqs: + best_lqs, best_k = e['product_score'], k + if best_lqs is None: + n_skipped += 1 + results.append({'name': name, 'family': family, 'sweep': res, + 'best_lqs': None, 'best_k': None, + 'error': None, 'stability': stab}) + _on_scan_progress(name, 'skipped', 'no candidates') + continue + n_scanned += 1 + results.append({'name': name, 'family': family, 'sweep': res, + 'best_lqs': best_lqs, 'best_k': best_k, + 'error': None, 'stability': stab}) + _on_scan_progress(name, 'ok', f'best LQS {best_lqs * 100:.1f}%') + ranked = [r for r in results if r['best_lqs'] is not None] + rest = [r for r in results if r['best_lqs'] is None] + ranked.sort(key=lambda r: r['best_lqs'], reverse=True) + return {'results': ranked + rest, 'n_scanned': n_scanned, + 'n_failed': n_failed, 'n_skipped': n_skipped} + _scan = {'progress': {}, 'order': []} _STATUS_ICON = {'start': '⏳', 'ok': '✓', 'skipped': '·', 'error': '✗'} @@ -419,17 +573,19 @@ def _render_results(scan_result): "family" "best LQS" "k" - "cands") + "cands" + "stability") body = [] for r in results: name = esc(str(r['name'])) fam = esc(str(r['family'] or '?')) + badge = _stability_badge(r) if r['error']: body.append( f"" f"{name}" f"{fam}" - f"✗ " + f"✗ " f"{esc(str(r['error']))}") elif r['best_lqs'] is None: body.append( @@ -437,7 +593,9 @@ def _render_results(scan_result): f"{name}" f"{fam}" f"no candidates" - f"") + f"" + f"" + f"{badge}") else: lqs = esc(f"{r['best_lqs'] * 100.0:.1f}%") ncand = sum(len(v) for v in r['sweep']['strata'].values()) @@ -448,7 +606,9 @@ def _render_results(scan_result): f"" f"{esc(str(r['best_k']))}" f"" - f"{esc(str(ncand))}") + f"{esc(str(ncand))}" + f"" + f"{badge}") children = [HTML(head + "".join(body) + "")] # Per-QPU stratified dropdowns (same label format as single-circuit). @@ -540,8 +700,13 @@ def _on_scan_click(b): btn_scan_qpus.description = '⏳ Scanning...' get_backend = state.active_service.backend get_props = make_scan_get_props(state) + use_scan_filter = (_stability_filter_active() + and chk_scan_stability.value) def _work(): + if use_scan_filter: + return _scan_filtered(eligible, norb, get_backend, get_props, + min_bridges) return scan_qpus(eligible, norb, get_backend, get_props, min_bridges=min_bridges, top_n=3, progress_cb=_on_scan_progress) diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py new file mode 100644 index 0000000..d5c0ae0 --- /dev/null +++ b/tests/test_stability_ui.py @@ -0,0 +1,194 @@ +"""Headless tests for the stability-filter UI (Component 4b). + +Offline: the data layer is stubbed and the stability/sweep engines are +monkeypatched with canned dicts. The background spawn + progress marshal +are injected synchronously. +""" +from types import SimpleNamespace + +import numpy as np +import pytest + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _entry(prod=0.4, k=1): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(range(4, 4 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 0.5, + 'rank_in_stratum': 1, 'source': 'derived'} + + +def _canned_res(stability): + return {'strata': {1: [_entry()]}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 5, + 'n_candidates_scored': 5, 'excluded_qubits': [1, 2, 3], + 'stability': stability} + + +def _build(monkeypatch, *, history=False, spawn=_sync_spawn, + marshal=lambda cb: cb()): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr(au, 'marshal_to_main', marshal) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: object()) + state.available_backends = ["ibm_a", "ibm_b"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + if history: + state.cal_history_dates = ['2026-07-01', '2026-07-02'] + state.cal_history = { + d: {'qubit_props': {'readout_error': [0.01] * 8}, 'gate_props': {}} + for d in state.cal_history_dates} + else: + state.cal_history_dates = ["_seed_"] # skip bg auto-load; no dict + state.cal_history = {} + + b = MapperUIBuilder(state) + b.build() + return b + + +# ── t1: availability gating ───────────────────────────────────────────────── + +def test_checkbox_disabled_without_history(monkeypatch): + b = _build(monkeypatch, history=False) + assert b.chk_stability_filter.disabled is True + assert 'Fetch calibration history' in b.chk_stability_filter.tooltip + + +def test_checkbox_enabled_with_history(monkeypatch): + b = _build(monkeypatch, history=True) + assert b.chk_stability_filter.disabled is False + assert b.chk_stability_filter.tooltip # non-empty + + +# ── t2: filter ON routes to sweep_with_stability with the controls' args ──── + +def test_filter_on_calls_sweep_with_stability(monkeypatch): + b = _build(monkeypatch, history=True) + + calls = {} + def fake_sws(norb, backend, props, hist, **kw): + calls['kw'] = kw + return _canned_res({'available': True, 'relaxed': False, + 'excluded_final': [1, 2, 3], + 'window_days': kw.get('window_days')}) + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", fake_sws) + plain = [] + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: plain.append(1) or _canned_res(None)) + + b.chk_stability_filter.value = True + b.rb_stability_window_auto.value = 7 + b.ft_stability_threshold.value = 1.5 + b.btn_lucj_run.click() + + assert calls['kw']['window_days'] == 7 + assert calls['kw']['threshold'] == 1.5 + assert plain == [] # plain NOT called + + +# ── t3: the three banner states ───────────────────────────────────────────── + +def test_banner_states(monkeypatch): + b = _build(monkeypatch, history=True) + holder = {} + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: _canned_res(holder['stab'])) + b.chk_stability_filter.value = True + + holder['stab'] = {'available': True, 'relaxed': False, + 'excluded_final': [1, 2, 3, 4], 'window_days': 14} + b.btn_lucj_run.click() + assert 'filtered 4 volatile qubits' in b.lbl_lucj_stability.value + assert 'window 14d' in b.lbl_lucj_stability.value + + holder['stab'] = {'available': True, 'relaxed': True, + 'n_readmitted': 2, 'n_excluded_initial': 6} + b.btn_lucj_run.click() + assert 'too strict' in b.lbl_lucj_stability.value + assert 're-admitted 2 of 6' in b.lbl_lucj_stability.value + + holder['stab'] = {'available': False} + b.btn_lucj_run.click() + assert 'filter skipped' in b.lbl_lucj_stability.value + + +# ── t4: scan rows carry stability badges ──────────────────────────────────── + +def test_scan_stability_badges(monkeypatch): + b = _build(monkeypatch, history=True) + + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) + + def fake_scan(*a, **k): + return {'results': [ + {'name': 'ibm_a', 'family': 'Heron', 'sweep': _canned_res(None), + 'best_lqs': 0.5, 'best_k': 1, 'error': None, + 'stability': {'available': True, 'relaxed': False, + 'excluded_final': [3, 4], 'window_days': 14}}, + {'name': 'ibm_b', 'family': 'Heron', 'sweep': _canned_res(None), + 'best_lqs': 0.4, 'best_k': 1, 'error': None, + 'stability': {'available': False, 'reason': 'no cached history'}}, + ], 'n_scanned': 2, 'n_failed': 0, 'n_skipped': 0} + monkeypatch.setattr(qs, 'scan_qpus', fake_scan) + + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert '🛡 −2 qubits' in table # cached → filtered + assert 'n/a (no cached history)' in table # fresh → n/a + + +# ── t5: filter OFF keeps the plain sweep path ─────────────────────────────── + +def test_filter_off_uses_plain_sweep(monkeypatch): + b = _build(monkeypatch, history=True) + + plain = [] + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: plain.append(1) or _canned_res(None)) + sws = [] + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: sws.append(1) or _canned_res({'available': True})) + + assert b.chk_stability_filter.value is False # default OFF + b.btn_lucj_run.click() + assert plain == [1] # plain sweep used + assert sws == [] # filter engine untouched + assert b.lbl_lucj_stability.value == "" # no banner From 778c2439b880aaa10f9cf5e642ee356700378013 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 20:15:46 -0400 Subject: [PATCH 06/66] Route scan warnings into UI: per-row k-capped notes, scoped notice capture --- qpu_mapper/ui/lucj_panel.py | 103 +++++++++++++++++++-- tests/test_scan_notices.py | 179 ++++++++++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+), 9 deletions(-) create mode 100644 tests/test_scan_notices.py diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 46cd675..72c6b12 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -37,6 +37,33 @@ def _format_sweep_status(res): f"best per k: {esc(per_k)}") +def _k_cap_phrase(norb, k_effective): + """(N1) 'k capped at E (requested R)' when the geometric request + ceil(norb/4) exceeds what actually fit; '' otherwise. Pure metadata — + replaces the operator's need to read the repeated stderr warning.""" + request = (norb + 3) // 4 + if k_effective is not None and k_effective < request: + return f"k capped at {k_effective} (requested {request})" + return "" + + +class _ScanNoticeCapture(logging.Handler): + """(N2) Captures WARNING+ records off the 'qpu_mapper' logger during a + scan, tagging each with the current backend context. emit() never raises + out — a logging hiccup must not break the scan.""" + + def __init__(self, context_getter): + super().__init__(level=logging.WARNING) + self._context_getter = context_getter + self.records = [] # list of (backend_context, message) + + def emit(self, record): + try: + self.records.append((self._context_getter(), record.getMessage())) + except Exception: + pass + + def setup_lucj_callbacks(ctx): """Wire all LUCJ-related callbacks. Called from ui.py after widget creation.""" @@ -307,10 +334,12 @@ def _generate_sweep(norb): # One-line summary (M2): per-stratum LQS gradient, NOT a single # size-biased "best LQS" (product_score always favours fewer bridges). if flat: + cap = _k_cap_phrase(norb, res.get('k_max_effective')) + cap_txt = f" · {esc(cap)}" if cap else "" lbl_lucj_status.value = ( f"
✅ {_format_sweep_status(res)}
") + f"margin:3px 0;'>✅ {_format_sweep_status(res)}{cap_txt}
") else: lbl_lucj_status.value = ( f"
{esc(cap)}" + if cap else "") body.append( f"{name}" f"{fam}" @@ -608,7 +645,7 @@ def _render_results(scan_result): f"" f"{esc(str(ncand))}" f"" - f"{badge}") + f"{badge}{cap_html}") children = [HTML(head + "".join(body) + "")] # Per-QPU stratified dropdowns (same label format as single-circuit). @@ -653,8 +690,34 @@ def _cb(change): scan_results_box.children = children - def _on_scan_done(scan_result): + def _append_notices(notices): + # (N2) Collapsible "⚠ notices (N)" under the results table: + # deduplicated messages (message → ×count), grouped by backend + # context. Hidden when empty. + if not notices: + return + from collections import OrderedDict + groups = OrderedDict() + for ctx, msg in notices: + groups.setdefault(ctx, OrderedDict()) + groups[ctx][msg] = groups[ctx].get(msg, 0) + 1 + parts = [] + for ctx, msgs in groups.items(): + parts.append(f"{esc(str(ctx))}") + for msg, cnt in msgs.items(): + suffix = f" ×{cnt}" if cnt > 1 else "" + parts.append(f"  {esc(msg)}{esc(suffix)}") + html = ( + f"
" + f"⚠ notices ({len(notices)})" + f"
" + "
".join(parts) + "
" + f"
") + scan_results_box.children = list(scan_results_box.children) + [HTML(html)] + + def _on_scan_done(payload): + scan_result, notices = payload _render_results(scan_result) + _append_notices(notices) btn_scan_qpus.disabled = False btn_scan_qpus.description = '🌐 Scan all QPUs' @@ -696,6 +759,8 @@ def _on_scan_click(b): _scan['progress'].clear() _scan['order'].clear() + _scan['current'] = None + _scan['norb'] = norb btn_scan_qpus.disabled = True btn_scan_qpus.description = '⏳ Scanning...' get_backend = state.active_service.backend @@ -704,12 +769,32 @@ def _on_scan_click(b): and chk_scan_stability.value) def _work(): - if use_scan_filter: - return _scan_filtered(eligible, norb, get_backend, get_props, - min_bridges) - return scan_qpus(eligible, norb, get_backend, get_props, - min_bridges=min_bridges, top_n=3, - progress_cb=_on_scan_progress) + # (N2/N3) Capture WARNING+ off 'qpu_mapper' for the scan's + # duration and stop them leaking under the cell (propagate=False). + # Attach in try, restore BOTH in finally (done + error paths). + logger = logging.getLogger('qpu_mapper') + orig_propagate = logger.propagate + handler = _ScanNoticeCapture(lambda: _scan.get('current') or 'general') + try: + logger.addHandler(handler) + logger.propagate = False + except Exception: + pass + try: + if use_scan_filter: + result = _scan_filtered(eligible, norb, get_backend, + get_props, min_bridges) + else: + result = scan_qpus(eligible, norb, get_backend, get_props, + min_bridges=min_bridges, top_n=3, + progress_cb=_on_scan_progress) + return (result, list(handler.records)) + finally: + try: + logger.removeHandler(handler) + logger.propagate = orig_propagate + except Exception: + pass scan_spawn_bg(_work, on_done=_on_scan_done, on_error=_on_scan_error) btn_scan_qpus.on_click(_on_scan_click) diff --git a/tests/test_scan_notices.py b/tests/test_scan_notices.py new file mode 100644 index 0000000..a4950e8 --- /dev/null +++ b/tests/test_scan_notices.py @@ -0,0 +1,179 @@ +"""Headless tests for in-UI scan notices (N1 cap note, N2 capture, N3 no-leak). + +Offline: data layer stubbed, scan monkeypatched, spawn+marshal synchronous. +""" +import logging +from types import SimpleNamespace + +import numpy as np + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _sweep(k_max_effective=1): + entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.4, + 'additive_score': 0.5, 'rank_in_stratum': 1, 'source': 'vf2'} + return {'strata': {1: [entry]}, 'k_max_effective': k_max_effective, + 'min_bridges': 1, 'vf2_truncated': False, 'n_raw_embeddings': 5, + 'n_candidates_scored': 5} + + +def _build(monkeypatch): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: object()) + state.available_backends = ["ibm_a"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b + + +def _patch_targets(monkeypatch, names=('ibm_a',)): + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in names]) + + +def _all_html(box): + from ipywidgets import HTML + return " ".join(c.value for c in box.children if isinstance(c, HTML)) + + +# ── t1: k-capped row note from metadata ───────────────────────────────────── + +def test_k_capped_row_note(monkeypatch): + b = _build(monkeypatch) + _patch_targets(monkeypatch) + import qpu_mapper.qpu_scan as qs + + def scan_capped(*a, **k): + return {'results': [{'name': 'ibm_a', 'family': 'Heron', + 'sweep': _sweep(k_max_effective=2), + 'best_lqs': 0.5, 'best_k': 2, 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} + monkeypatch.setattr(qs, 'scan_qpus', scan_capped) + + b.lucj_norb_slider.value = 12 # request = ceil(12/4) = 3 + b.btn_scan_qpus.click() + assert 'k capped at 2 (requested 3)' in _all_html(b.scan_results_box) + + +def test_k_not_capped_no_note(monkeypatch): + b = _build(monkeypatch) + _patch_targets(monkeypatch) + import qpu_mapper.qpu_scan as qs + + def scan_ok(*a, **k): + return {'results': [{'name': 'ibm_a', 'family': 'Heron', + 'sweep': _sweep(k_max_effective=3), + 'best_lqs': 0.5, 'best_k': 3, 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} + monkeypatch.setattr(qs, 'scan_qpus', scan_ok) + + b.lucj_norb_slider.value = 12 # request = 3, k_eff = 3 → equal + b.btn_scan_qpus.click() + assert 'k capped' not in _all_html(b.scan_results_box) + + +# ── t2: warning capture → grouped, deduplicated notices ───────────────────── + +def test_notices_capture_and_dedup(monkeypatch): + b = _build(monkeypatch) + _patch_targets(monkeypatch) + import qpu_mapper.qpu_scan as qs + lg = logging.getLogger('qpu_mapper') + + def scan_warns(targets, norb, gb, gp, **kw): + cb = kw['progress_cb'] + cb('ibm_a', 'start', '') + lg.warning("stale cache housekeeping") + lg.warning("stale cache housekeeping") + lg.warning("other notice") + cb('ibm_a', 'ok', '') + return {'results': [{'name': 'ibm_a', 'family': 'Heron', + 'sweep': _sweep(), 'best_lqs': 0.5, 'best_k': 1, + 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} + monkeypatch.setattr(qs, 'scan_qpus', scan_warns) + + b.btn_scan_qpus.click() + html = _all_html(b.scan_results_box) + assert '⚠ notices (3)' in html # 3 total records + assert 'stale cache housekeeping ×2' in html # deduped with count + assert 'other notice' in html # the singleton (no ×) + assert 'other notice ×' not in html + assert 'ibm_a' in html # grouped under the backend + + +# ── t3: finally-restoration (done AND error paths) ────────────────────────── + +def test_logger_restored_after_scan(monkeypatch): + b = _build(monkeypatch) + _patch_targets(monkeypatch) + import qpu_mapper.qpu_scan as qs + lg = logging.getLogger('qpu_mapper') + h0, p0 = list(lg.handlers), lg.propagate + + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { + 'results': [{'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(), + 'best_lqs': 0.5, 'best_k': 1, 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) + b.btn_scan_qpus.click() + assert list(lg.handlers) == h0 + assert lg.propagate == p0 + + def boom(*a, **k): + raise RuntimeError("scan blew up") + monkeypatch.setattr(qs, 'scan_qpus', boom) + b.btn_scan_qpus.click() # error path + assert list(lg.handlers) == h0 # still restored + assert lg.propagate == p0 + + +# ── t4: empty notices → no section ────────────────────────────────────────── + +def test_no_notices_section_when_empty(monkeypatch): + b = _build(monkeypatch) + _patch_targets(monkeypatch) + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { + 'results': [{'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(), + 'best_lqs': 0.5, 'best_k': 1, 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) + b.btn_scan_qpus.click() + assert '⚠ notices' not in _all_html(b.scan_results_box) From cd9087788a67e35f58d7520e340771c87aa21242 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 20:20:42 -0400 Subject: [PATCH 07/66] Fix derived candidates to prefix bridge subsets (LUCJ contract) --- qpu_mapper/ancilla_sweep.py | 82 ++++++++++++++++++++++--------------- tests/test_ancilla_sweep.py | 43 ++++++++++++++++++- 2 files changed, 92 insertions(+), 33 deletions(-) diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index b8e6d50..112e978 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -34,12 +34,24 @@ * The k_max template is the *most constrained* subgraph, so the VF2 cap removes the fewest useful embeddings there. -* Every k_max embedding yields all of its lower-`k` variants for free — - including the "good-region k-1 layout" that an independent k-1 search, - starting from the rigid every-4th-orbital template, never generates. -* Subtraction also unlocks *non-standard* bridge-position sets (e.g. keeping - orbital slots ``{0, 8, 12}`` out of ``{0, 4, 8, 12}``) that the fixed - template cannot express at all. +* Every k_max embedding yields its lower-`k` variants for free — including the + "good-region k-1 layout" that an independent k-1 search, starting from the + rigid every-4th-orbital template, never generates. + +LUCJ PREFIX CONTRACT (do not break) +----------------------------------- +A derived k' candidate keeps the bridges at the **first k' standard slots** +``(0, 4, ..., 4*(k'-1))`` and drops the tail — exactly ONE variant per k' per +embedding, byte-for-byte indistinguishable from a legacy exact-k' layout. + +We deliberately do NOT enumerate all ``C(k_max, k')`` bridge subsets. A +scattered set like ``{0, 8, 12}`` is a *valid subgraph* with a *valid score* +but a **semantically invalid ansatz layout**: the LUCJ construction places +bridges at consecutive standard slots, and a downstream consumer (rendering, +codegen, exact-k' equivalence) assumes that. Keeping only the prefix restores +the contract — and, as a bonus, does strictly less work (one variant per k', +not a combinatorial fan-out). ``bridge_slots`` is retained precisely to +*certify* this: it is always ``tuple(range(0, 4*k', 4))``. Scoring: product vs additive ----------------------------- @@ -68,7 +80,6 @@ suitable for ranking, not absolute fidelity prediction. """ -import itertools import logging import numpy as np @@ -303,31 +314,38 @@ def _edge_e(a, b): norm_chain = norm_alpha + norm_beta for k in range(k_max_effective, min_bridges - 1, -1): - for kept in itertools.combinations(range(k_max_effective), k): - n_candidates_scored += 1 - ancillas = [bridges[i]['phys'] for i in kept] - ancilla_fs = frozenset(ancillas) - key = (chain_fs, ancilla_fs) - if key in strata_pool[k]: - # Duplicate (e.g. alpha/beta swap): identical qubits and - # edges -> identical score, so keep the first. - continue - additive = (chain_readout_sum + chain_gate_sum - + sum(bridges[i]['add'] for i in kept)) - product = chain_readout_prod * chain_gate_prod - for i in kept: - product *= bridges[i]['prod'] - strata_pool[k][key] = { - 'layout': list(norm_chain), - 'alpha': list(norm_alpha), - 'beta': list(norm_beta), - 'ancillas': ancillas, - 'bridge_slots': tuple(bridges[i]['slot'] for i in kept), - 'product_score': product, - 'additive_score': additive, - 'rank_in_stratum': 0, # filled after sort - 'source': 'vf2' if k == k_max_effective else 'derived', - } + # LUCJ PREFIX CONTRACT: a derived k' candidate keeps the bridges + # at the FIRST k' standard slots (0, 4, ..., 4*(k'-1)) and drops + # the tail — exactly one variant per k', indistinguishable from a + # legacy exact-k' layout. NOT all C(k_max, k') subsets: scattered + # slots ({0, 8, 12}) are semantically invalid ansatz layouts. + kept = range(k) + n_candidates_scored += 1 + ancillas = [bridges[i]['phys'] for i in kept] + ancilla_fs = frozenset(ancillas) + key = (chain_fs, ancilla_fs) + if key in strata_pool[k]: + # Duplicate (e.g. alpha/beta swap): identical qubits and + # edges -> identical score, so keep the first. + continue + additive = (chain_readout_sum + chain_gate_sum + + sum(bridges[i]['add'] for i in kept)) + product = chain_readout_prod * chain_gate_prod + for i in kept: + product *= bridges[i]['prod'] + strata_pool[k][key] = { + 'layout': list(norm_chain), + 'alpha': list(norm_alpha), + 'beta': list(norm_beta), + 'ancillas': ancillas, + # Always the first-k' standard slots — this field now + # certifies the prefix contract: tuple(range(0, 4*k, 4)). + 'bridge_slots': tuple(bridges[i]['slot'] for i in kept), + 'product_score': product, + 'additive_score': additive, + 'rank_in_stratum': 0, # filled after sort + 'source': 'vf2' if k == k_max_effective else 'derived', + } # ---- 7. Rank each stratum by product_score desc, slice top_n --------- strata = {} diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index 4be1beb..1890954 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -15,7 +15,12 @@ For norb=8 the geometric ceiling is k_max = ceil(8/4) = 2 bridges (orbital slots 0 and 4), so k_max_effective == 2 and a min_bridges=1 sweep produces two -strata (k=2 intact VF2 layouts, k=1 subtraction variants). +strata (k=2 intact VF2 layouts, k=1 PREFIX variants — one per embedding, +keeping only the bridge at slot 0). + +LUCJ PREFIX CONTRACT: a derived k' candidate keeps the bridges at the first k' +standard slots (0, 4, ..., 4*(k'-1)), never a scattered subset. Enforced by +test_bridge_slots_are_prefix and test_prefix_legacy_equivalence below. """ import time @@ -165,6 +170,42 @@ def test_kminus1_variant_present(backend, props): "the top layout's own k-1 subtraction variant is absent") +# ── F2c: bridge_slots are the first-k' standard slots — no holes, ever ────── + +def test_bridge_slots_are_prefix(backend, props): + """The regression born from the scattered-ancilla bug: EVERY entry in + EVERY stratum must keep bridges at the first k' standard slots, so + bridge_slots == (0, 4, ..., 4*(k'-1)) with no offsets and no gaps.""" + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + for k, entries in res['strata'].items(): + for e in entries: + k_prime = len(e['ancillas']) + assert e['bridge_slots'] == tuple(range(0, 4 * k_prime, 4)), ( + f"k={k} entry has non-prefix slots {e['bridge_slots']}") + assert len(e['bridge_slots']) == k_prime == k + + +# ── F2d: a derived k' entry == its parent embedding's first-k' bridges ────── + +def test_prefix_legacy_equivalence(backend, props): + """A derived k' candidate must be indistinguishable from the original + code computing exactly-k' on the same embedding: its kept ancilla + physical qubits equal the first k' ancillas of a k_max parent on the + same chain (ancillas are stored in bridge-slot order).""" + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + kmax = res['k_max_effective'] + parents = res['strata'][kmax] # full-ancilla vf2 entries + for k, entries in res['strata'].items(): + for e in entries: + chain = frozenset(e['alpha']) | frozenset(e['beta']) + assert any( + (frozenset(p['alpha']) | frozenset(p['beta'])) == chain + and list(p['ancillas'][:k]) == list(e['ancillas']) + for p in parents), ( + f"k={k} ancillas {e['ancillas']} are not the first-{k} " + f"bridges of any parent embedding") + + # ── t3: good region wins every stratum ────────────────────────────────────── def test_good_region_wins(backend, props): From b221aedeeffa45128a477d09de24ee7166e6f8a4 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 20:46:40 -0400 Subject: [PATCH 08/66] UI cleanup: separate local results from scan, clear-results control, staged banner, score label disambiguation --- qpu_mapper/ui/builder.py | 31 ++++-- qpu_mapper/ui/inter_qpu.py | 18 +++- qpu_mapper/ui/lucj_panel.py | 29 +++++- tests/test_ui_cleanup.py | 200 ++++++++++++++++++++++++++++++++++++ 4 files changed, 263 insertions(+), 15 deletions(-) create mode 100644 tests/test_ui_cleanup.py diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index 7e7bdeb..aac29f8 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -324,6 +324,7 @@ def _run_pipeline(self): # Multi-QPU scan (B2/B3/B4). btn_scan_qpus=self.btn_scan_qpus, chk_scan_other_families=self.chk_scan_other_families, + btn_scan_clear=self.btn_scan_clear, lbl_scan_progress=self.lbl_scan_progress, scan_results_box=self.scan_results_box, scan_spawn_bg=default_spawn_bg, @@ -1260,6 +1261,10 @@ def _build_auto_lucj_widgets(self, W): layout=W, tooltip='Filter each scanned backend using its CACHED history ' 'only — no remote history fetch in this version') + self.btn_scan_clear = Button( + description='✕ Clear results', button_style='', + layout=Layout(width='130px'), + tooltip='Dismiss the scan results table, dropdowns and notices') # ── Multi-QPU scan cluster ─────────────────────────────── self.btn_scan_qpus = Button( @@ -1675,6 +1680,8 @@ def _build_auto_lucj_view(self): falls back to the dropdown). """ self._refresh_stability_filter_availability() + name = esc(str(getattr(self.state, 'active_backend_name', '') + or 'current backend')) return VBox([ HTML("
" "🤖 Auto-LUCJ Layout Engine
"), @@ -1691,18 +1698,30 @@ def _build_auto_lucj_view(self): self.btn_lucj_run, self.lbl_lucj_trunc, self.lbl_lucj_status, + # ── Local (current backend) results — ABOVE the scan block ── + HTML("
"), + HTML(f"
📍 This backend ({name})
"), + HTML("
" + "Per-layout LQS is template fidelity (single-pass " + "edges); the Estimated Layout-Quality box " + "(Analysis) is the circuit-level score. Two different " + "scales.
"), + self.dd_lucj_layout, + self.lbl_lucj_detail, + # ── Remote scan block — its own header + Clear control ────── HTML("
"), - HTML("
" - "🌐 Scan All QPUs
"), + HBox([ + HTML("
🌐 Scan All " + "QPUs (other backends)
"), + self.btn_scan_clear, + ], layout=Layout(align_items='center')), self.btn_scan_qpus, self.chk_scan_other_families, self.chk_scan_stability, self.lbl_scan_progress, self.scan_results_box, - HTML("
" - "📋 Inspect Layouts
"), - self.dd_lucj_layout, - self.lbl_lucj_detail, HTML("
"), HTML("
" "🔗 Multi-Circuit (Multi-Programming)
"), diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index 6b871bc..c926cb4 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -283,10 +283,20 @@ def stage_remote_candidate(backend_name, candidate): with contextlib.suppress(Exception): dd_backend_qpu2.value = backend_name _pending_handoff[0] = (backend_name, candidate) - lbl_qpu2_status.value = ( - f"Staged " - f"{esc(str(backend_name))} — click Connect QPU 2 " - f"to view this candidate on its chip.") + # (C3) Prominent one-liner explaining the half-open state until the + # user clicks Connect. Replaced by the connect status once connected. + staged_html = ( + f"
📡 {esc(str(backend_name))} " + f"staged — click Connect QPU 2 to load the device and " + f"paint the candidate.
") + lbl_qpu2_status.value = staged_html + # Also surface it inside the revealed QPU-2 sidebar slot, so the + # prompt is visible wherever the user is looking. + if _qpu2_content_box[0] is not None: + with contextlib.suppress(Exception): + _qpu2_content_box[0].children = [HTML(staged_html)] if handoff_cell is not None: handoff_cell[0] = stage_remote_candidate diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 72c6b12..c76b890 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -183,8 +183,10 @@ def _on_lucj_layout_select(change): lqs = entry['product_score'] * 100.0 header = (f"k={k} · #{entry['rank_in_stratum']} " f"· LQS {lqs:.1f}% " - f"(add {entry['additive_score']:.4f}, " - f"{esc(str(entry.get('source', '')))})") + f"template fidelity " + f"(single-pass edges); internal ranking sum " + f"{entry['additive_score']:.4f}, " + f"{esc(str(entry.get('source', '')))}") anc = ', '.join(str(q) for q in entry['ancillas']) lbl_lucj_detail.value = ( f"
" f"β: {', '.join(str(q) for q in entry['beta'])}
" ) + # (C4) Disambiguate the LQS number: it's template fidelity, not the + # circuit-level Estimated Layout-Quality box in the Analysis panel. + with contextlib.suppress(Exception): + dd_lucj_layout.tooltip = ('LQS = template fidelity (single-pass ' + 'edges), not the circuit-level Estimated ' + 'Layout-Quality') dd_lucj_layout.observe(_on_lucj_layout_select, names='value') # ── Dropdown re-seed helper (observer-safe) ────────────────── @@ -396,6 +404,7 @@ def _on_ancilla_mode_change(change=None): # ── B2/B3/B4: Multi-QPU scan ───────────────────────────────── btn_scan_qpus = ctx.btn_scan_qpus chk_scan_other_families = ctx.chk_scan_other_families + btn_scan_clear = ctx.btn_scan_clear lbl_scan_progress = ctx.lbl_scan_progress scan_results_box = ctx.scan_results_box scan_spawn_bg = ctx.scan_spawn_bg @@ -543,6 +552,18 @@ def _scan_filtered(eligible, norb, get_backend, get_props, min_bridges): _scan = {'progress': {}, 'order': []} _STATUS_ICON = {'start': '⏳', 'ok': '✓', 'skipped': '·', 'error': '✗'} + def _clear_scan_results(): + # (C2) Full reset — table, per-QPU dropdowns, notices, progress line, + # and the scan button. No ghost dropdown state survives. + scan_results_box.children = [] + lbl_scan_progress.value = "" + _scan['progress'].clear() + _scan['order'].clear() + _scan['current'] = None + btn_scan_qpus.disabled = False + btn_scan_qpus.description = '🌐 Scan all QPUs' + btn_scan_clear.on_click(lambda b: _clear_scan_results()) + def _render_progress_line(): chips = [] for name in _scan['order']: @@ -745,6 +766,7 @@ def _on_scan_click(b): except Exception: family = None + _clear_scan_results() # (C2) drop any stale results targets = list_scan_targets( state, norb, same_family_as=family, include_other_families=chk_scan_other_families.value) @@ -757,9 +779,6 @@ def _on_scan_click(b): "backends for this norb / family scope.
") return - _scan['progress'].clear() - _scan['order'].clear() - _scan['current'] = None _scan['norb'] = norb btn_scan_qpus.disabled = True btn_scan_qpus.description = '⏳ Scanning...' diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py new file mode 100644 index 0000000..80eeca8 --- /dev/null +++ b/tests/test_ui_cleanup.py @@ -0,0 +1,200 @@ +"""Headless tests for the scan/sweep UI cleanup (C1 separation, C2 dismissal, +C3 staged banner, C4 labels).""" +from types import SimpleNamespace + +import numpy as np +import pytest + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _entry(prod, k): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(range(4, 4 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 0.4162, + 'rank_in_stratum': 1, 'source': 'derived'} + + +def _canned(): + return {'strata': {2: [_entry(0.30, 2)], 1: [_entry(0.40, 1)]}, + 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 5, 'n_candidates_scored': 5, + 'excluded_qubits': []} + + +def _build(monkeypatch): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: object()) + state.available_backends = ["ibm_here", "ibm_other"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b + + +# ── t1: local block renders ABOVE the scan block ──────────────────────────── + +def test_local_block_above_scan(monkeypatch): + b = _build(monkeypatch) + view = b._build_auto_lucj_view() + children = list(view.children) + # The local sweep dropdown must precede the scan results container. + assert children.index(b.dd_lucj_layout) < children.index(b.scan_results_box) + # And the "This backend ()" header exists, with the active name. + from ipywidgets import HTML + headers = [c.value for c in children if isinstance(c, HTML)] + assert any('📍 This backend (ibm_here)' in h for h in headers) + + +# ── t2: clear resets everything and re-arms the button ────────────────────── + +def test_clear_scan_results(monkeypatch): + b = _build(monkeypatch) + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, + 'reason': None}]) + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { + 'results': [{'name': 'ibm_other', 'family': 'Heron', + 'sweep': _canned(), 'best_lqs': 0.4, 'best_k': 1, + 'error': None}], + 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) + + b.btn_scan_qpus.click() + assert b.scan_results_box.children # populated + assert b.btn_scan_qpus.disabled is False # re-enabled on done + + b.btn_scan_clear.click() + assert b.scan_results_box.children == () # table + dropdowns gone + assert b.lbl_scan_progress.value == "" # progress cleared + assert b.btn_scan_qpus.disabled is False # button armed + + +def test_new_scan_auto_clears(monkeypatch): + b = _build(monkeypatch) + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, + 'reason': None}]) + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { + 'results': [{'name': 'ibm_other', 'family': 'Heron', + 'sweep': _canned(), 'best_lqs': 0.4, 'best_k': 1, + 'error': None}], 'n_scanned': 1, 'n_failed': 0, + 'n_skipped': 0}) + b.btn_scan_qpus.click() + first = list(b.scan_results_box.children) + b.btn_scan_qpus.click() # a second scan + # Fresh render, not appended onto the stale one. + assert list(b.scan_results_box.children) != first + first + + +# ── t3: staged banner appears on stage, cleared on connect ────────────────── + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._handlers = [] + + def observe(self, fn, names=None): + self._handlers.append(fn) + + def on_click(self, fn): + self._click = fn + + def fire(self, new): + for fn in self._handlers: + fn({'new': new}) + + +def _inter_ctx(): + from ipywidgets import VBox + state = SimpleNamespace( + available_backends=[], active_backend_name='ibm_here', + active_service=SimpleNamespace( + backend=lambda n: (_ for _ in ()).throw(RuntimeError('stub')))) + ctx = SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_Stub(value=''), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), + full_ui=_Stub(children=[]), + handoff_cell=[None], + ) + return ctx, state + + +def test_staged_banner_then_cleared_on_connect(): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + ctx, state = _inter_ctx() + setup_inter_qpu(ctx) + stage = ctx.handoff_cell[0] + assert stage is not None + + stage('ibm_remote', {'alpha': [0], 'beta': [1], 'ancillas': [2]}) + assert 'ibm_remote' in ctx.lbl_qpu2_status.value + assert 'staged' in ctx.lbl_qpu2_status.value + assert 'Connect QPU 2' in ctx.lbl_qpu2_status.value + + # Invoking the (stubbed) connect replaces the staged banner. + ctx.btn_connect_qpu2._click(None) + assert 'staged' not in ctx.lbl_qpu2_status.value + + +# ── t4: label disambiguation in the detail + dropdown ─────────────────────── + +def test_label_disambiguation(monkeypatch): + b = _build(monkeypatch) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned()) + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() + + # Dropdown labels keep the short "LQS" token. + assert any('LQS' in opt[0] for opt in b.dd_lucj_layout.options) + + # Selecting an entry renders the disambiguated detail wording. + b.dd_lucj_layout.value = 1 # fire select + detail = b.lbl_lucj_detail.value + assert 'template fidelity (single-pass edges)' in detail + assert 'internal ranking sum 0.4162' in detail + assert '(add ' not in detail # old wording gone From 8e53579069dd182c12da4f7e0d0e62a54b42c652 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Sun, 12 Jul 2026 21:21:35 -0400 Subject: [PATCH 09/66] One scorer everywhere: extract estimate_fidelity_core, per-backend circuit LQS in scan --- qpu_mapper/ancilla_sweep.py | 27 +++++- qpu_mapper/export/scoring.py | 136 ++++++++++++++++++------------ qpu_mapper/props_shim.py | 21 +++++ qpu_mapper/ui/builder.py | 5 -- qpu_mapper/ui/lucj_panel.py | 155 ++++++++++++++++++++++++++++++----- tests/test_ancilla_sweep.py | 50 +++++++++++ tests/test_scan_ui.py | 27 ++++++ tests/test_scoring_core.py | 86 +++++++++++++++++++ tests/test_sweep_ui.py | 22 +++++ 9 files changed, 448 insertions(+), 81 deletions(-) create mode 100644 tests/test_scoring_core.py diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index 112e978..f77561b 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -128,7 +128,8 @@ def _safe_gate_error(props, gate_name, u, v): def sweep_ancilla_layouts(norb, backend, props, *, min_bridges=None, top_n=3, - mapping_cap=None, exclude_qubits=None) -> dict: + mapping_cap=None, exclude_qubits=None, + circuit_score_fn=None) -> dict: """One-shot ancilla sweep: VF2 at the geometric max bridge count, then derive every lower-k variant by bridge subtraction, score, and return the top_n candidates per ancilla count. @@ -149,6 +150,17 @@ def sweep_ancilla_layouts(norb, backend, props, *, coupling graph BEFORE template creation (a hard search-space filter, e.g. volatile qubits from stability analysis). ``None`` or empty → byte-for-byte identical to the unfiltered sweep. + circuit_score_fn: optional ``callable(entry) -> float`` computing a + CIRCUIT-LEVEL fidelity for a candidate, using the SAME code path + as the UI's Estimated Layout-Quality box + (``export.scoring.estimate_circuit_fidelity``). It is state-bound + (needs the app's dict-shaped props), so the UI injects it rather + than the engine calling it directly. When provided, it is called + ONLY on the top_n sliced entries per stratum (cheap) and its + result is stored on ``entry['lqs_circuit']``; a scoring failure + leaves ``lqs_circuit=None`` and never aborts the sweep. When + ``None`` (default) the returned dict is byte-compatible with the + pre-A2 shape — no ``lqs_circuit`` key is added. Returns { 'strata': {k: [entry, ...]}, # k descending; len<=top_n each @@ -348,6 +360,10 @@ def _edge_e(a, b): } # ---- 7. Rank each stratum by product_score desc, slice top_n --------- + # product_score is the internal PRE-RANK (cross-stratum-comparable, cheap). + # Circuit-level scoring (A2) runs ONLY on the sliced survivors — top_n per + # stratum — so the expensive state-bound scorer is called O(top_n * strata) + # times, not per raw candidate. strata = {} for k in range(k_max_effective, min_bridges - 1, -1): entries = sorted(strata_pool[k].values(), @@ -355,6 +371,15 @@ def _edge_e(a, b): entries = entries[:top_n] for rank, entry in enumerate(entries, start=1): entry['rank_in_stratum'] = rank + if circuit_score_fn is not None: + for entry in entries: + try: + entry['lqs_circuit'] = circuit_score_fn(entry) + except Exception as exc: + # A scoring error must never abort the sweep. + _log.warning("Circuit scoring failed for a candidate " + "(k=%d): %s", k, exc) + entry['lqs_circuit'] = None strata[k] = entries _log.debug("Ancilla sweep stratum k=%d: %d candidates (top_n=%d)", k, len(entries), top_n) diff --git a/qpu_mapper/export/scoring.py b/qpu_mapper/export/scoring.py index 47a3e94..88a996d 100644 --- a/qpu_mapper/export/scoring.py +++ b/qpu_mapper/export/scoring.py @@ -42,6 +42,77 @@ def compute_error_delta(qp_a, gp_a, qp_b, gp_b): # ESTIMATED FIDELITY # ═══════════════════════════════════════════════════════════════════════ +def estimate_fidelity_core(layout_qubit_ids, readout_by_id, gate_edges, + all_readout=None): + """Pure product-form fidelity — the math of :func:`estimate_circuit_fidelity` + with all state reads lifted out, so the SAME scorer serves the local C1 + box (state-backed wrapper below) and the multi-QPU scan (per-backend + arrays from ``props_shim.CachedPropsShim``). + + Args: + layout_qubit_ids: ordered iterable of qubit ids in the layout. + readout_by_id: ``{qubit_id: readout_error}`` for (at least) the layout + ids. NaN allowed (skipped). Missing ids are skipped. + gate_edges: iterable of ``(id_u, id_v, cz_error)`` — the device + couplings; those with BOTH endpoints in the layout set contribute. + all_readout: optional full readout array for device-mean outlier + detection; ``None`` → no outliers. + + Returns the same dict shape as :func:`estimate_circuit_fidelity`. + """ + qubit_set = set(layout_qubit_ids) + + readout_f = 1.0 + worst_q = (None, 0) + n_q = 0 + for qid in layout_qubit_ids: + err = readout_by_id.get(qid) + if err is None: + continue + if not np.isnan(err): + readout_f *= (1 - err) + n_q += 1 + if err > worst_q[1]: + worst_q = (qid, float(err)) + + gate_f = 1.0 + worst_g = (None, 0) + n_g = 0 + for u_id, v_id, err in gate_edges: + if u_id in qubit_set and v_id in qubit_set: + if err is not None and not np.isnan(err): + gate_f *= (1 - err) + n_g += 1 + if err > worst_g[1]: + worst_g = ((u_id, v_id), float(err)) + + total_f = readout_f * gate_f + + outliers = [] + if all_readout is not None: + arr = np.asarray(all_readout, dtype=float) + if len(arr) > OUTLIER_MIN_SAMPLES: + valid = arr[~np.isnan(arr)] + if len(valid) > 0: + mean, std = np.mean(valid), np.std(valid) + threshold = mean + OUTLIER_SIGMA * std + for qid in layout_qubit_ids: + err = readout_by_id.get(qid) + if err is not None and not np.isnan(err) and err > threshold: + outliers.append((qid, float(err))) + + return { + 'fidelity': float(total_f), + 'readout_fidelity': float(readout_f), + 'gate_fidelity': float(gate_f), + 'n_qubits': n_q, + 'n_gates': n_g, + 'worst_qubit': worst_q, + 'worst_gate': worst_g, + 'outliers': outliers, + } + + def estimate_circuit_fidelity(state, circuit_idx, mode='lucj'): """Estimate a product-form fidelity upper bound from calibration data. @@ -113,66 +184,25 @@ def estimate_circuit_fidelity(state, circuit_idx, mode='lucj'): if not qubit_ids or not state.qubit_props_data: return None + # ── State reads → plain arrays/dicts, then delegate to the pure core ── q_id_map = {q: i for i, q in enumerate(state.qubit_ids)} if state.qubit_ids else {} - # Readout fidelity re_arr = state.qubit_props_data.get('readout_error', np.array([])) - readout_f = 1.0 - worst_q = (None, 0) - n_q = 0 + readout_by_id = {} for qid in qubit_ids: idx = q_id_map.get(qid) if idx is not None and idx < len(re_arr): - err = re_arr[idx] - if not np.isnan(err): - readout_f *= (1 - err) - n_q += 1 - if err > worst_q[1]: - worst_q = (qid, float(err)) - - # Gate fidelity (CZ gates between layout qubits) + readout_by_id[qid] = re_arr[idx] + cz_arr = state.gate_props_data.get('cz_error', np.array([])) - qubit_set = set(qubit_ids) - gate_f = 1.0 - worst_g = (None, 0) - n_g = 0 + gate_edges = [] for i, edge in enumerate(state.edges_list or []): + # Access u_id/v_id for every edge (same pattern as before), but only + # feed the core edges whose cz value is present — the both-endpoints- + # in-layout filter and NaN skip live in estimate_fidelity_core. u_id, v_id = state.qubit_ids[edge[0]], state.qubit_ids[edge[1]] - if u_id in qubit_set and v_id in qubit_set: - if i < len(cz_arr): - err = cz_arr[i] - if not np.isnan(err): - # Multiplicative fidelity accumulation, same form as - # readout_f above: each valid gate contributes a - # (1 - err) factor to the product. - gate_f *= (1 - err) - n_g += 1 - if err > worst_g[1]: - worst_g = ((u_id, v_id), float(err)) - - total_f = readout_f * gate_f + if i < len(cz_arr): + gate_edges.append((u_id, v_id, cz_arr[i])) - # Outlier detection: flag qubits whose readout error sits more than - # OUTLIER_SIGMA standard deviations above the device mean. - outliers = [] - if len(re_arr) > OUTLIER_MIN_SAMPLES: - valid = re_arr[~np.isnan(re_arr)] - if len(valid) > 0: - mean, std = np.mean(valid), np.std(valid) - threshold = mean + OUTLIER_SIGMA * std - for qid in qubit_ids: - idx = q_id_map.get(qid) - if idx is not None and idx < len(re_arr): - if not np.isnan(re_arr[idx]) and re_arr[idx] > threshold: - outliers.append((qid, float(re_arr[idx]))) - - return { - 'fidelity': float(total_f), - 'readout_fidelity': float(readout_f), - 'gate_fidelity': float(gate_f), - 'n_qubits': n_q, - 'n_gates': n_g, - 'worst_qubit': worst_q, - 'worst_gate': worst_g, - 'outliers': outliers, - } + return estimate_fidelity_core(qubit_ids, readout_by_id, gate_edges, + all_readout=re_arr) diff --git a/qpu_mapper/props_shim.py b/qpu_mapper/props_shim.py index 9f90ee4..cb7cb21 100644 --- a/qpu_mapper/props_shim.py +++ b/qpu_mapper/props_shim.py @@ -85,6 +85,27 @@ def gate_error(self, gate_name, pair): raise KeyError( f"no gate_error for edge {(u, v)!r}") from exc + def score_layout(self, layout_qubit_ids): + """Circuit-level fidelity for a layout on THIS backend, via the shared + ``export.scoring.estimate_fidelity_core`` — so a scan candidate lands + on the SAME scale as the local Estimated Layout-Quality box. Returns + the core dict (``None`` only if the layout is empty).""" + from .export.scoring import estimate_fidelity_core + ids = list(layout_qubit_ids) + if not ids: + return None + readout_by_id = {} + for q in ids: + try: + readout_by_id[q] = self._readout[q] + except (IndexError, KeyError, TypeError): + pass + gate_edges = [(u, v, err) + for key, err in self._gate.items() + for (u, v) in (tuple(key),)] + return estimate_fidelity_core(ids, readout_by_id, gate_edges, + all_readout=self._readout) + def _backend_edges(backend): """Deterministic edge list for a backend, matching data._generate_ibm.""" diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index aac29f8..092663c 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -1702,11 +1702,6 @@ def _build_auto_lucj_view(self): HTML("
"), HTML(f"
📍 This backend ({name})
"), - HTML("
" - "Per-layout LQS is template fidelity (single-pass " - "edges); the Estimated Layout-Quality box " - "(Analysis) is the circuit-level score. Two different " - "scales.
"), self.dd_lucj_layout, self.lbl_lucj_detail, # ── Remote scan block — its own header + Clear control ────── diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index c76b890..be1195a 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -15,15 +15,32 @@ _log = logging.getLogger(__name__) +def _entry_lqs(entry): + """(lqs_value, is_template): the circuit-level LQS (``entry['lqs_circuit']``, + same scale as the Estimated Layout-Quality box) when available, else the + internal template heuristic ``product_score`` with the template flag set.""" + val = entry.get('lqs_circuit') + if val is not None: + return val, False + return entry['product_score'], True + + +def _entry_lqs_pct(entry): + """('25.3%', is_template) for display.""" + val, is_tmpl = _entry_lqs(entry) + return f"{val * 100.0:.1f}%", is_tmpl + + def _format_best_per_k(strata): """"6→24.1% · 5→24.6% · 4→25.0% · 3→25.3%" — the LQS gradient across - strata (best product_score per k, k descending). Shows the trade-off - instead of a single size-biased "winner".""" + strata (best entry per k, k descending). Uses circuit-level LQS when + present. Shows the trade-off instead of a single size-biased "winner".""" parts = [] for k in sorted(strata.keys(), reverse=True): entries = strata[k] if entries: - parts.append(f"{k}→{entries[0]['product_score'] * 100.0:.1f}%") + val, _ = _entry_lqs(entries[0]) + parts.append(f"{k}→{val * 100.0:.1f}%") return ' · '.join(parts) @@ -177,15 +194,17 @@ def _on_lucj_layout_select(change): entry = _lucj_all_layouts[idx] _apply_lucj_layout(entry) if 'product_score' in entry: - # Sweep candidate: multiplicative LQS is the headline; the - # additive sum (size-biased across k) goes in the detail only. + # Sweep candidate: circuit-level LQS (matches the Estimated + # Layout-Quality box) is the headline; the internal ranking sum + # (size-biased across k) goes in the detail only. k = len(entry['ancillas']) - lqs = entry['product_score'] * 100.0 + pct, is_tmpl = _entry_lqs_pct(entry) + scale = ('template fidelity (single-pass edges)' if is_tmpl + else 'circuit-level (matches Estimated Layout-Quality)') header = (f"k={k} · #{entry['rank_in_stratum']} " - f"· LQS {lqs:.1f}% " - f"template fidelity " - f"(single-pass edges); internal ranking sum " - f"{entry['additive_score']:.4f}, " + f"· LQS {pct} " + f"{scale}; internal ranking " + f"sum {entry['additive_score']:.4f}, " f"{esc(str(entry.get('source', '')))}") anc = ', '.join(str(q) for q in entry['ancillas']) lbl_lucj_detail.value = ( @@ -205,12 +224,15 @@ def _on_lucj_layout_select(change): f"α: {', '.join(str(q) for q in entry['alpha'])}
" f"β: {', '.join(str(q) for q in entry['beta'])}" ) - # (C4) Disambiguate the LQS number: it's template fidelity, not the - # circuit-level Estimated Layout-Quality box in the Analysis panel. + # (A2) The LQS shown here is the circuit-level score — the same number + # the Estimated Layout-Quality box reports. '(template)' flags the + # internal heuristic used only when circuit scoring is unavailable. with contextlib.suppress(Exception): - dd_lucj_layout.tooltip = ('LQS = template fidelity (single-pass ' - 'edges), not the circuit-level Estimated ' - 'Layout-Quality') + dd_lucj_layout.tooltip = ('LQS = circuit-level fidelity, the same ' + 'number as the Estimated Layout-Quality ' + 'box. "(template)" = internal heuristic ' + 'fallback when circuit scoring is ' + 'unavailable.') dd_lucj_layout.observe(_on_lucj_layout_select, names='value') # ── Dropdown re-seed helper (observer-safe) ────────────────── @@ -232,6 +254,41 @@ def _seed_layout_dropdown(entries, dd_opts): if entries: _apply_lucj_layout(entries[0]) + # ── A2: circuit-level LQS for a sweep candidate ────────────── + def _circuit_score(entry): + """Score a sweep candidate with the SAME path as the Estimated + Layout-Quality box: build a scratch layout from the candidate and + run export.scoring.estimate_circuit_fidelity against the current + backend's props. Returns a fidelity in [0, 1] or None.""" + from types import SimpleNamespace + from ..export.scoring import estimate_circuit_fidelity + layout = { + 'alpha': [str(q) for q in entry['alpha']], + 'beta': [str(q) for q in entry['beta']], + 'other': [], + 'ancilla': [str(q) for q in entry['ancillas']], + } + fake = SimpleNamespace( + layouts_data={0: layout}, + qubit_props_data=getattr(state, 'qubit_props_data', {}) or {}, + gate_props_data=getattr(state, 'gate_props_data', {}) or {}, + qubit_ids=state.qubit_ids, + edges_list=state.edges_list, + ) + res = estimate_circuit_fidelity(fake, 0, 'lucj') + return res['fidelity'] if res else None + + def _annotate_circuit_lqs(res): + """Fill entry['lqs_circuit'] for any strata entry that lacks it (the + stability-filter path can't pass circuit_score_fn to the engine).""" + for entries in res.get('strata', {}).values(): + for e in entries: + if 'lqs_circuit' not in e: + try: + e['lqs_circuit'] = _circuit_score(e) + except Exception: + e['lqs_circuit'] = None + # ── Legacy single-count search ─────────────────────────────── def _generate_legacy(norb, requested_ancillas): from ..auto_lucj import get_all_zigzag_layouts @@ -302,10 +359,14 @@ def _generate_sweep(norb): threshold=ft_stability_threshold.value, min_bridges=min_bridges) _render_stability_banner(res.get('stability'), norb) + # The frozen stability engine can't take circuit_score_fn — fill + # circuit-level LQS on its survivors here (A2). + _annotate_circuit_lqs(res) else: res = sweep_ancilla_layouts( norb, state.active_backend, state.initial_props, - min_bridges=min_bridges) + min_bridges=min_bridges, + circuit_score_fn=_circuit_score) # A2: aligned circuit LQS if _stability_filter_active(): # Checkbox on but no history dict → skipped note. _render_stability_banner(None, norb) @@ -314,14 +375,16 @@ def _generate_sweep(norb): strata = res['strata'] # Flatten k descending, entries in stratum order; the dropdown value - # is the flat index. Label format is fixed: "k=4 · #1 · LQS 25.3%". + # is the flat index. Label: "k=4 · #1 · LQS 25.3%" (circuit-level; + # "(template)" suffix when circuit scoring was unavailable). flat = [] dd_opts = [] for k in sorted(strata.keys(), reverse=True): for entry in strata[k]: - lqs = entry['product_score'] * 100.0 + pct, is_tmpl = _entry_lqs_pct(entry) + suffix = " (template)" if is_tmpl else "" dd_opts.append(( - f"k={k} · #{entry['rank_in_stratum']} · LQS {lqs:.1f}%", + f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}", len(flat), )) flat.append(entry) @@ -486,6 +549,41 @@ def _stability_badge(r): return (f"🛡 −{esc(str(n))} " f"qubits{extra}") + def _scan_circuit_score(props): + """Per-backend circuit-level scorer: uses the shim's own arrays via + the shared core, so every scan entry lands on the SAME scale as the + local C1 box. Returns None when the shim can't score.""" + def _fn(entry): + qubits = (list(entry['alpha']) + list(entry['beta']) + + list(entry['ancillas'])) + if not hasattr(props, 'score_layout'): + return None + res = props.score_layout(qubits) + return res['fidelity'] if res else None + return _fn + + def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): + """(A3/S2) Fill each scan entry's lqs_circuit with THAT backend's + circuit-level fidelity, so the scan table/dropdowns display the same + scale as the local sweep. Runs on the worker thread (props are + cache-first). A per-backend failure leaves lqs_circuit as-is (None → + the '(template)' fallback still applies to genuine failures only).""" + for r in scan_result.get('results', []): + sweep = r.get('sweep') + if not sweep: + continue + try: + scorer = _scan_circuit_score(get_props(get_backend(r['name']))) + except Exception: + continue + for entries in sweep.get('strata', {}).values(): + for e in entries: + if e.get('lqs_circuit') is None: + try: + e['lqs_circuit'] = scorer(e) + except Exception: + e['lqs_circuit'] = None + def _scan_filtered(eligible, norb, get_backend, get_props, min_bridges): """Handler-side per-target scan with cached-history stability filter. @@ -592,8 +690,9 @@ def _apply(): def _entry_label(entry): k = len(entry['ancillas']) - return (f"k={k} · #{entry['rank_in_stratum']} · " - f"LQS {entry['product_score'] * 100.0:.1f}%") + pct, is_tmpl = _entry_lqs_pct(entry) + suffix = " (template)" if is_tmpl else "" + return f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" def _render_targets(targets): rows = [] @@ -651,7 +750,17 @@ def _render_results(scan_result): f"" f"{badge}") else: - lqs = esc(f"{r['best_lqs'] * 100.0:.1f}%") + # Scan sweeps aren't circuit-scored (remote backend props are + # not the current state's) → template heuristic, flagged. + best_entry = None + for _entries in r['sweep']['strata'].values(): + if _entries: + best_entry = _entries[0] + break + if best_entry is not None and best_entry.get('lqs_circuit') is not None: + lqs = esc(f"{best_entry['lqs_circuit'] * 100.0:.1f}%") + else: + lqs = esc(f"{r['best_lqs'] * 100.0:.1f}% (template)") ncand = sum(len(v) for v in r['sweep']['strata'].values()) cap = _k_cap_phrase(_scan.get('norb', 0), r['sweep'].get('k_max_effective')) @@ -807,6 +916,8 @@ def _work(): result = scan_qpus(eligible, norb, get_backend, get_props, min_bridges=min_bridges, top_n=3, progress_cb=_on_scan_progress) + # (A3/S2) Circuit-level LQS per backend — one scale everywhere. + _annotate_scan_circuit_lqs(result, get_backend, get_props) return (result, list(handler.records)) finally: try: diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index 1890954..a3b97f3 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -206,6 +206,56 @@ def test_prefix_legacy_equivalence(backend, props): f"bridges of any parent embedding") +# ── A2: circuit_score_fn on the sliced survivors only ────────────────────── + +def test_circuit_score_fn_on_sliced_only(backend, props): + """(A2) The injected scorer runs ONCE per sliced entry (top_n per + stratum), and its value lands on entry['lqs_circuit'].""" + calls = [] + + def scorer(entry): + calls.append(entry) + return 0.5 + + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3, + circuit_score_fn=scorer) + total = sum(len(v) for v in res['strata'].values()) + assert len(calls) == total # exactly once per survivor + assert total <= 3 * len(res['strata']) # cheap-slice property + for entries in res['strata'].values(): + for e in entries: + assert e['lqs_circuit'] == 0.5 + + +def test_circuit_score_error_keeps_entry_none(backend, props): + """(A2) A scorer that raises on one candidate leaves it lqs_circuit=None; + the sweep still completes and other entries are scored.""" + calls = [] + + def scorer(entry): + calls.append(1) + if len(calls) == 1: + raise ValueError("boom") + return 0.5 + + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3, + circuit_score_fn=scorer) + vals = [e['lqs_circuit'] for entries in res['strata'].values() + for e in entries] + assert vals.count(None) == 1 # the failed one + assert 0.5 in vals # the rest scored + assert res['strata'] # sweep completed + + +def test_no_circuit_score_fn_is_byte_compatible(backend, props): + """(A2 default guarantee) Without the scorer, no lqs_circuit key appears — + the dict shape is unchanged from pre-A2.""" + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) + for entries in res['strata'].values(): + for e in entries: + assert 'lqs_circuit' not in e + + # ── t3: good region wins every stratum ────────────────────────────────────── def test_good_region_wins(backend, props): diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index bcc347c..f191db5 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -214,3 +214,30 @@ def test_m2_status_line_format(): res['n_raw_embeddings'] = 214 line = _format_sweep_status(res) assert line == "Sweep: k=2..1 · 214 embeddings · best per k: 2→30.0% · 1→40.0%" + + +# ── A3 t4: scan circuit-LQS annotation (success → number, failure → template) + +def test_scan_circuit_lqs_annotated(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch) # canned entries, no lqs_circuit + # A working per-backend shim → annotation fills circuit LQS on every entry. + from qpu_mapper.props_shim import CachedPropsShim + qp = {'readout_error': np.array([0.01] * 8)} + gp = {'cz_error': np.array([0.001] * 7)} + shim = CachedPropsShim(qp, gp, [(i, i + 1) for i in range(7)]) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: shim)) + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert '(template)' not in table # circuit-scored, not fallback + + +def test_scan_template_suffix_only_on_failure(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch) + # Default get_backend returns a bare object() → the real get_props raises + # (no coupling_map) → annotation skips → lqs_circuit stays None → template. + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert '(template)' in table diff --git a/tests/test_scoring_core.py b/tests/test_scoring_core.py new file mode 100644 index 0000000..7982c6a --- /dev/null +++ b/tests/test_scoring_core.py @@ -0,0 +1,86 @@ +"""A3 tests — one scorer everywhere (estimate_fidelity_core). + +Pure/offline. Pins C1 behaviour across the extract, checks the shim's +per-backend scorer, and proves scan == local on identical calibration. +""" +from types import SimpleNamespace + +import numpy as np +import pytest + +from qpu_mapper.export.scoring import ( + estimate_circuit_fidelity, estimate_fidelity_core, +) +from qpu_mapper.props_shim import CachedPropsShim + + +# ── t1: C1 pin — behaviour unchanged across the refactor-extract ──────────── + +def test_c1_pin_unchanged(): + qubit_ids = ['0', '1', '2', '3'] + readout = np.array([0.01, 0.02, 0.03, 0.04]) + cz = np.array([0.001, 0.002, 0.003]) + edges = [(0, 1), (1, 2), (2, 3)] + state = SimpleNamespace( + layouts_data={0: {'alpha': ['0', '1'], 'beta': ['2', '3'], + 'other': [], 'ancilla': []}}, + qubit_props_data={'readout_error': readout}, + gate_props_data={'cz_error': cz}, + qubit_ids=qubit_ids, edges_list=edges) + + res = estimate_circuit_fidelity(state, 0, 'lucj') + # Expected computed from the fixture with the documented formula — no + # magic constant. All 4 qubits + all 3 edges are inside the layout. + readout_f = float(np.prod(1 - readout)) + gate_f = float(np.prod(1 - cz)) + assert res['fidelity'] == pytest.approx(readout_f * gate_f) + assert res['readout_fidelity'] == pytest.approx(readout_f) + assert res['gate_fidelity'] == pytest.approx(gate_f) + assert res['n_qubits'] == 4 and res['n_gates'] == 3 + + # The pure core, called with the same lifted inputs, agrees exactly. + readout_by_id = {q: readout[i] for i, q in enumerate(qubit_ids)} + gate_edges = [(qubit_ids[u], qubit_ids[v], cz[i]) + for i, (u, v) in enumerate(edges)] + core = estimate_fidelity_core(['0', '1', '2', '3'], readout_by_id, + gate_edges, all_readout=readout) + assert core == res + + +# ── t2: per-backend shim scorer == hand-computed product ──────────────────── + +def test_shim_score_hand_computed(): + qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04])} + gp = {'cz_error': np.array([0.001, 0.002, 0.003])} + edges = [(0, 1), (1, 2), (2, 3)] + shim = CachedPropsShim(qp, gp, edges) + + res = shim.score_layout([0, 1, 2, 3]) + readout_f = float(np.prod(1 - qp['readout_error'])) + gate_f = float(np.prod(1 - gp['cz_error'])) + assert res['fidelity'] == pytest.approx(readout_f * gate_f) + assert res['n_qubits'] == 4 and res['n_gates'] == 3 + assert shim.score_layout([]) is None # empty → None + + +# ── t3: scan row == local number on the SAME calibration (the screenshot) ── + +def test_scan_equals_local_same_backend(): + qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06])} + gp = {'cz_error': np.array([0.001, 0.002, 0.003, 0.004, 0.005])} + edges = [(0, 1), (1, 2), (2, 3), (0, 4), (1, 5)] + + # Local (C1) via the state wrapper: candidate alpha=[0,1] beta=[2,3] anc=[4]. + qubit_ids = ['0', '1', '2', '3', '4', '5'] + state = SimpleNamespace( + layouts_data={0: {'alpha': ['0', '1'], 'beta': ['2', '3'], + 'other': [], 'ancilla': ['4']}}, + qubit_props_data=qp, gate_props_data=gp, + qubit_ids=qubit_ids, edges_list=edges) + local = estimate_circuit_fidelity(state, 0, 'lucj')['fidelity'] + + # Scan (per-backend shim) on the SAME arrays, same candidate (physical ids). + shim = CachedPropsShim(qp, gp, edges) + scan = shim.score_layout([0, 1, 2, 3, 4])['fidelity'] + + assert scan == pytest.approx(local) # one scale, same number diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index be5fdea..2cddd95 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -59,6 +59,9 @@ def entry(anc, prod, add, src): 'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], 'ancillas': anc, 'bridge_slots': tuple(range(0, 4 * len(anc), 4)), 'product_score': prod, 'additive_score': add, + # A2: engine now attaches circuit-level LQS; equal to product here + # so the rendered percentage is unchanged in these UI assertions. + 'lqs_circuit': prod, 'rank_in_stratum': 1, 'source': src, } return { @@ -73,6 +76,25 @@ def entry(anc, prod, add, src): } +# ── A2 t2: label/status formatters prefer circuit-level LQS ───────────────── + +def test_formatters_use_lqs_circuit(): + from qpu_mapper.ui.lucj_panel import _entry_lqs_pct, _format_best_per_k + + circ = {'product_score': 0.30, 'lqs_circuit': 0.42, 'ancillas': [4]} + pct, is_tmpl = _entry_lqs_pct(circ) + assert pct == '42.0%' and is_tmpl is False # circuit LQS, no flag + + tmpl = {'product_score': 0.30, 'ancillas': [4]} # no lqs_circuit + pct2, is_tmpl2 = _entry_lqs_pct(tmpl) + assert pct2 == '30.0%' and is_tmpl2 is True # falls back, flagged + + strata = {2: [{'product_score': 0.3, 'lqs_circuit': 0.5}], + 1: [{'product_score': 0.4, 'lqs_circuit': 0.6}]} + assert _format_best_per_k(strata) == '2→50.0% · 1→60.0%' + assert _format_best_per_k({1: [{'product_score': 0.4}]}) == '1→40.0%' + + # ── t1: sweep mode default → stratified dropdown, exact label format ──────── def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): From a8c02c81d1e400acaf3bb97723fd1b2357f8ef43 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 00:05:52 -0400 Subject: [PATCH 10/66] Hybrid sweep, scan/local parity, live-only scan scoring, directed edge surface fixes --- qpu_mapper/ancilla_sweep.py | 158 +++++++++++------ qpu_mapper/props_shim.py | 165 +++++++++++------ qpu_mapper/ui/builder.py | 10 +- qpu_mapper/ui/lucj_panel.py | 187 ++++++++++++++------ tests/test_ancilla_sweep.py | 120 ++++++++++++- tests/test_props_shim.py | 206 ++++++++++++++++++++-- tests/test_scan_notices.py | 63 +++---- tests/test_scan_ui.py | 343 ++++++++++++++++++++++++++++-------- tests/test_stability_ui.py | 33 ++-- tests/test_sweep_ui.py | 30 ++++ 10 files changed, 1002 insertions(+), 313 deletions(-) diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index f77561b..1c928eb 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -129,7 +129,7 @@ def _safe_gate_error(props, gate_name, u, v): def sweep_ancilla_layouts(norb, backend, props, *, min_bridges=None, top_n=3, mapping_cap=None, exclude_qubits=None, - circuit_score_fn=None) -> dict: + circuit_score_fn=None, hybrid=True) -> dict: """One-shot ancilla sweep: VF2 at the geometric max bridge count, then derive every lower-k variant by bridge subtraction, score, and return the top_n candidates per ancilla count. @@ -161,6 +161,14 @@ def sweep_ancilla_layouts(norb, backend, props, *, leaves ``lqs_circuit=None`` and never aborts the sweep. When ``None`` (default) the returned dict is byte-compatible with the pre-A2 shape — no ``lqs_circuit`` key is added. + hybrid: when True (default), each stratum k' < k_max_effective is the + UNION of (a) the derived prefix candidates AND (b) a DIRECT VF2 at + the k' template on the same (possibly pruned) graph. Derivation + alone chains every low-k stratum to k_max's embeddings, so a clean + chain that only the smaller k' template can reach is invisible to + it; the direct pass recovers exactly those. One extra VF2 per + stratum (the cost the old per-k flow already paid). hybrid=False → + derivation-only, byte-compatible with the pre-hybrid sweep. Returns { 'strata': {k: [entry, ...]}, # k descending; len<=top_n each @@ -171,6 +179,9 @@ def sweep_ancilla_layouts(norb, backend, props, *, 'n_candidates_scored': int, # total variants scored (pre-dedupe) 'excluded_qubits': [...], # sorted list actually pruned (empty # when exclude_qubits is None) + 'per_stratum': {k: {'n_direct', 'n_derived', 'truncated'}}, + # per-k provenance; vf2_truncated is + # any(per-stratum truncated) } entry = { 'layout': [...], # chain qubits (alpha+beta) @@ -278,86 +289,122 @@ def _edge_e(a, b): # strata_pool[k] : dict keyed by (frozenset(chain), frozenset(ancilla)) # -> entry, giving per-stratum dedupe for free. strata_pool = {k: {} for k in range(k_max_effective, min_bridges - 1, -1)} + per_stratum = {k: {'n_direct': 0, 'n_derived': 0, 'truncated': False} + for k in range(k_max_effective, min_bridges - 1, -1)} n_candidates_scored = 0 - for layout in layouts: + def _embedding_data(layout, n_bridges): + """Per-embedding precompute: chain aggregates + per-bridge factors. + Constant across every k' derived from this embedding.""" alpha = layout[:norb] beta = layout[norb:2 * norb] chain = layout[:2 * norb] - chain_fs = frozenset(chain) - - # Chain aggregates are constant across every variant of this - # embedding, so compute them once. chain_qubits = np.array(chain, dtype=int) - chain_readout_sum = float(readout[chain_qubits].sum()) - chain_readout_prod = float(np.prod(np.clip(1.0 - readout[chain_qubits], - 0.0, 1.0))) chain_edges = ([(alpha[j], alpha[j + 1]) for j in range(norb - 1)] + [(beta[j], beta[j + 1]) for j in range(norb - 1)]) chain_gate_errs = np.array([_edge_e(a, b) for a, b in chain_edges], dtype=float) - chain_gate_sum = float(chain_gate_errs.sum()) - chain_gate_prod = float(np.prod(np.clip(1.0 - chain_gate_errs, - 0.0, 1.0))) - - # Per-bridge contributions for this embedding. bridges = [] - for i in range(k_max_effective): + for i in range(n_bridges): bphys = layout[2 * norb + i] e1 = _edge_e(alpha[4 * i], bphys) e2 = _edge_e(bphys, beta[4 * i]) r = float(readout[bphys]) - add_i = r + e1 + e2 - prod_i = (max(0.0, 1.0 - r) * max(0.0, 1.0 - e1) - * max(0.0, 1.0 - e2)) bridges.append({ - 'phys': bphys, - 'slot': 4 * i, - 'add': add_i, - 'prod': prod_i, + 'phys': bphys, 'slot': 4 * i, 'add': r + e1 + e2, + 'prod': max(0.0, 1.0 - r) * max(0.0, 1.0 - e1) * max(0.0, 1.0 - e2), }) - # Alpha/beta swap normalization (mirror _deduplicate_layouts): the # representative alpha is the chain with the smaller first element. if alpha and beta and alpha[0] > beta[0]: norm_alpha, norm_beta = list(beta), list(alpha) else: norm_alpha, norm_beta = list(alpha), list(beta) - norm_chain = norm_alpha + norm_beta - + return { + 'chain_fs': frozenset(chain), + 'norm_alpha': norm_alpha, 'norm_beta': norm_beta, + 'norm_chain': norm_alpha + norm_beta, + 'cr_sum': float(readout[chain_qubits].sum()), + 'cr_prod': float(np.prod(np.clip(1.0 - readout[chain_qubits], 0.0, 1.0))), + 'cg_sum': float(chain_gate_errs.sum()), + 'cg_prod': float(np.prod(np.clip(1.0 - chain_gate_errs, 0.0, 1.0))), + 'bridges': bridges, + } + + def _add_variant(edata, k, source): + """Score the first-k prefix of this embedding and add it to + strata_pool[k]. Returns True iff a NEW (chain, ancilla) was inserted. + + LUCJ PREFIX CONTRACT: keep bridges at the first k standard slots + (0, 4, ..., 4*(k-1)) — for a direct k' embedding that IS every bridge; + for a derived one it drops the tail. Scattered subsets are invalid. + """ + bridges = edata['bridges'] + kept = range(k) + ancillas = [bridges[i]['phys'] for i in kept] + key = (edata['chain_fs'], frozenset(ancillas)) + if key in strata_pool[k]: + # Duplicate (alpha/beta swap, or a chain found both derived AND + # direct): identical qubits/edges → identical score, keep first. + return False + additive = (edata['cr_sum'] + edata['cg_sum'] + + sum(bridges[i]['add'] for i in kept)) + product = edata['cr_prod'] * edata['cg_prod'] + for i in kept: + product *= bridges[i]['prod'] + strata_pool[k][key] = { + 'layout': list(edata['norm_chain']), + 'alpha': list(edata['norm_alpha']), + 'beta': list(edata['norm_beta']), + 'ancillas': ancillas, + 'bridge_slots': tuple(bridges[i]['slot'] for i in kept), + 'product_score': product, + 'additive_score': additive, + 'rank_in_stratum': 0, # filled after sort + 'source': source, + } + return True + + # 6a. k_max embeddings → the k_max stratum (direct) + derived prefixes. + per_stratum[k_max_effective]['truncated'] = vf2_truncated + for layout in layouts: + edata = _embedding_data(layout, k_max_effective) for k in range(k_max_effective, min_bridges - 1, -1): - # LUCJ PREFIX CONTRACT: a derived k' candidate keeps the bridges - # at the FIRST k' standard slots (0, 4, ..., 4*(k'-1)) and drops - # the tail — exactly one variant per k', indistinguishable from a - # legacy exact-k' layout. NOT all C(k_max, k') subsets: scattered - # slots ({0, 8, 12}) are semantically invalid ansatz layouts. - kept = range(k) n_candidates_scored += 1 - ancillas = [bridges[i]['phys'] for i in kept] - ancilla_fs = frozenset(ancillas) - key = (chain_fs, ancilla_fs) - if key in strata_pool[k]: - # Duplicate (e.g. alpha/beta swap): identical qubits and - # edges -> identical score, so keep the first. + source = 'vf2' if k == k_max_effective else 'derived' + if _add_variant(edata, k, source): + bucket = 'n_direct' if k == k_max_effective else 'n_derived' + per_stratum[k][bucket] += 1 + + # 6b. HYBRID: a DIRECT VF2 at each lower-k template on the SAME (pruned) + # graph — recovers clean chains derivation can't reach from k_max. + if hybrid: + for k in range(k_max_effective - 1, min_bridges - 1, -1): + tmpl_k, nb_k = create_lucj_zigzag_layout( + num_orbitals=norb, backend_coupling_graph=search_graph, + requested_bridges=k) + if nb_k != k: + # The k' template auto-reduced to a different count — the + # derived stratum already covers this k; skip the direct pass. + _log.debug("Hybrid: k=%d template returned %d bridges; " + "skipping direct pass", k, nb_k) continue - additive = (chain_readout_sum + chain_gate_sum - + sum(bridges[i]['add'] for i in kept)) - product = chain_readout_prod * chain_gate_prod - for i in kept: - product *= bridges[i]['prod'] - strata_pool[k][key] = { - 'layout': list(norm_chain), - 'alpha': list(norm_alpha), - 'beta': list(norm_beta), - 'ancillas': ancillas, - # Always the first-k' standard slots — this field now - # certifies the prefix contract: tuple(range(0, 4*k, 4)). - 'bridge_slots': tuple(bridges[i]['slot'] for i in kept), - 'product_score': product, - 'additive_score': additive, - 'rank_in_stratum': 0, # filled after sort - 'source': 'vf2' if k == k_max_effective else 'derived', - } + maps_k = _collect_vf2_mappings(search_graph, tmpl_k, cap=cap) + if len(maps_k) >= cap: + per_stratum[k]['truncated'] = True + exp_k = 2 * norb + nb_k + for mapping in maps_k: + lay = [None] * exp_k + for key, value in mapping.items(): + lay[value] = _key_to_phys(key) + if any(v is None for v in lay): + continue + n_candidates_scored += 1 + if _add_variant(_embedding_data(lay, nb_k), k, 'vf2'): + per_stratum[k]['n_direct'] += 1 + + # Aggregate truncation for the existing banner (k_max OR any direct pass). + vf2_truncated = any(m['truncated'] for m in per_stratum.values()) # ---- 7. Rank each stratum by product_score desc, slice top_n --------- # product_score is the internal PRE-RANK (cross-stratum-comparable, cheap). @@ -392,4 +439,5 @@ def _edge_e(a, b): 'n_raw_embeddings': n_raw_embeddings, 'n_candidates_scored': n_candidates_scored, 'excluded_qubits': excluded_sorted, + 'per_stratum': per_stratum, } diff --git a/qpu_mapper/props_shim.py b/qpu_mapper/props_shim.py index cb7cb21..e826e0e 100644 --- a/qpu_mapper/props_shim.py +++ b/qpu_mapper/props_shim.py @@ -50,24 +50,68 @@ class CachedPropsShim: ``gate_props`` arrays. gate_key: which ``gate_props`` key holds the 2Q error (default ``'cz_error'``). + vintage: calibration provenance for the UI — ``'live'`` for the active + backend scored on the session's current props, or the cached + snapshot's UTC timestamp string for a remote backend. ``None`` when + unknown. + n_qubits: the backend's qubit count. When given, every ``qubit_props`` + array MUST have exactly this length (hard invariant below). - Missing lookups raise ``KeyError`` with a clear message; the scan's - per-backend isolation turns that into a per-backend error string. + HARD INVARIANTS (raise ValueError). The disk cache is POSITIONAL — it + stores no edge list — so the gate arrays pair 1:1 with ``edges`` (the + backend's OWN coupling map) purely by position. If a cached snapshot's + array lengths don't match this backend's edge/qubit counts, the pairing + is garbage (a dead coupler could land on the wrong edge, or vanish — + exactly the 66%-scan vs 0%-live bug). We refuse to construct rather than + silently mispair; the scan's per-backend isolation turns the ValueError + into an honest error row. + + Missing lookups raise ``KeyError`` with a clear message. """ - def __init__(self, qubit_props, gate_props, edges, gate_key=_DEFAULT_GATE_KEY): + def __init__(self, qubit_props, gate_props, edges, + gate_key=_DEFAULT_GATE_KEY, vintage=None, n_qubits=None): if 'readout_error' not in qubit_props: raise KeyError("qubit_props has no 'readout_error' entry") if gate_key not in gate_props: raise KeyError(f"gate_props has no {gate_key!r} entry") + + edges = list(edges) + n_edges = len(edges) + # Every gate array must pair 1:1 with the backend's edges. + for gk, arr in gate_props.items(): + if len(arr) != n_edges: + raise ValueError( + f"gate_props[{gk!r}] has {len(arr)} values but the " + f"backend exposes {n_edges} edges — cached snapshot does " + f"not match this backend's coupling map (positional " + f"mispairing would hide/relabel gates).") + # Every qubit array must have one value per qubit. + if n_qubits is not None: + for qk, arr in qubit_props.items(): + if len(arr) != n_qubits: + raise ValueError( + f"qubit_props[{qk!r}] has {len(arr)} values but the " + f"backend has {n_qubits} qubits — cached snapshot " + f"does not match this backend.") + + self.vintage = vintage + self.n_qubits = n_qubits self._readout = qubit_props['readout_error'] gate_arr = gate_props[gate_key] - # frozenset key → direction-insensitive lookup (mirrors the sweep's - # own edge_err map). Last write wins on duplicate undirected edges. + # Keep the RAW (edges, gate array) so score_layout can reproduce the + # C1 wrapper's EXACT edge surface — every coupling in the backend's + # own map (both directions, as edges_list carries them), paired + # positionally. Deduping here would halve the gate factors and inflate + # the product (SYM-1). + self._edges = [(int(u), int(v)) for (u, v) in edges] + self._gate_arr = gate_arr + # Deduped map for the direction-insensitive gate_error() the sweep's + # product_score uses (one value per undirected edge). Lengths are + # guaranteed equal above — no silent truncation. self._gate = {} - for i, (u, v) in enumerate(edges): - if i < len(gate_arr): - self._gate[frozenset((int(u), int(v)))] = gate_arr[i] + for i, (u, v) in enumerate(self._edges): + self._gate[frozenset((u, v))] = gate_arr[i] def readout_error(self, qubit): try: @@ -87,9 +131,11 @@ def gate_error(self, gate_name, pair): def score_layout(self, layout_qubit_ids): """Circuit-level fidelity for a layout on THIS backend, via the shared - ``export.scoring.estimate_fidelity_core`` — so a scan candidate lands - on the SAME scale as the local Estimated Layout-Quality box. Returns - the core dict (``None`` only if the layout is empty).""" + ``export.scoring.estimate_fidelity_core`` — the SAME edge surface as + the C1 wrapper (``estimate_circuit_fidelity``): every coupling among + the layout set, taken from the backend's OWN edge list (both + directions), so a scan candidate lands on exactly the C1 scale. + Returns the core dict (``None`` only if the layout is empty).""" from .export.scoring import estimate_fidelity_core ids = list(layout_qubit_ids) if not ids: @@ -100,9 +146,11 @@ def score_layout(self, layout_qubit_ids): readout_by_id[q] = self._readout[q] except (IndexError, KeyError, TypeError): pass - gate_edges = [(u, v, err) - for key, err in self._gate.items() - for (u, v) in (tuple(key),)] + # Full directed surface, positionally paired — mirrors the C1 wrapper's + # `for edge in edges_list` loop (which counts both directions). NOT the + # deduped self._gate, which would halve the factors and inflate. + gate_edges = [(u, v, self._gate_arr[i]) + for i, (u, v) in enumerate(self._edges)] return estimate_fidelity_core(ids, readout_by_id, gate_edges, all_readout=self._readout) @@ -117,22 +165,21 @@ def _backend_edges(backend): def make_scan_get_props(state, *, now=None): - """Build the cache-aware ``get_props(backend)`` callable the scan injects. - - Policy (per backend): - 1. Cache-first: look for today's cached snapshot under the backend's own - name (``data.list_known_calibrations`` + ``data._load_calibration``) - and adapt it. - 2. Miss: fetch ``backend.properties()`` live, build the shim directly - from it (correct regardless of array ordering), and best-effort warm - the disk cache via the same per-backend extract+save primitives the - app uses, so the next scan is instant. - 3. Hard failure: raise — the scan isolates it into a per-backend error. + """Build the ``get_props(backend)`` callable the scan injects. + + Product decision: scan scoring is ALWAYS LIVE — as if connecting to each + backend right now. The disk cache is NEVER a scoring source here: + * active backend → the session's current props (that IS live); + * remote backend → fetch ``backend.properties()`` live, build the shim + from the fresh data, and (side effect) warm the disk cache so the + 7/14/30-day HISTORY the stability filter reads stays fed; + * fetch failure → raise. NO silent fallback to a cached snapshot — a + stale score presented as current is the exact bug class we killed. Args: - state: SessionState (used only for read-through context; never mutated). - now: optional datetime for the "today" cache window (injectable for - tests). Defaults to ``datetime.now()``. + state: SessionState (read-through context; never mutated). + now: optional datetime stamped into the vintage as the fetch time + (injectable for tests). Defaults to ``datetime.now()``. """ from datetime import datetime as _dt from . import data @@ -142,35 +189,42 @@ def _gate_key_for(backend): name = _get_two_q_gate_name(backend) return f"{name}_error" if name else _DEFAULT_GATE_KEY - def _from_cache(backend_name, edges, gate_key): - try: - day = now or _dt.now() - known = data.list_known_calibrations(backend_name, day) - except Exception: - return None - if not known: - return None - # Newest snapshot for the day. - ts = sorted(k.get('last_update', '') for k in known)[-1] - cached = data._load_calibration(backend_name, ts) - if not cached: + def _live_stamp(): + dt = now or _dt.now() + return dt.strftime('%H:%M') if hasattr(dt, 'strftime') else str(dt) + + def _from_state(): + """(V1) The active backend is scored on the SESSION'S CURRENT props — + the same qubit_props_data/gate_props_data/edges_list the C1 box reads — + so the scan row for the active backend equals the C1 box exactly, live. + Returns None if the session hasn't loaded calibration yet.""" + qp = getattr(state, 'qubit_props_data', None) + gp = getattr(state, 'gate_props_data', None) + edges = getattr(state, 'edges_list', None) + if not qp or not gp or edges is None or 'readout_error' not in qp: return None - qp, gp = cached[0], cached[1] - key = gate_key if gate_key in gp else _DEFAULT_GATE_KEY - return CachedPropsShim(qp, gp, edges, gate_key=key) + key = _DEFAULT_GATE_KEY if _DEFAULT_GATE_KEY in gp else next(iter(gp)) + n_qubits = len(state.qubit_ids) if getattr(state, 'qubit_ids', None) else None + return CachedPropsShim(qp, gp, list(edges), gate_key=key, + vintage='live', n_qubits=n_qubits) def get_props(backend): backend_name = getattr(backend, 'name', None) - edges = _backend_edges(backend) - gate_key = _gate_key_for(backend) - shim = _from_cache(backend_name, edges, gate_key) - if shim is not None: - _log.debug("Scan props: cache hit for %s", backend_name) - return shim + # (V1) Active backend → live session props (that IS live). + if (backend_name is not None + and backend_name == getattr(state, 'active_backend_name', None)): + live = _from_state() + if live is not None: + _log.debug("Scan props: active backend %s → live state props", + backend_name) + return live + + edges = _backend_edges(backend) - # Live fetch. Build the shim directly from the BackendProperties so - # the edge mapping is self-consistent regardless of cache ordering. + # Remote backend → ALWAYS live fetch (no cache-first scoring read). + # Build the shim directly from the BackendProperties so the edge + # mapping is self-consistent regardless of cache ordering. props = backend.properties() if props is None: raise RuntimeError( @@ -188,7 +242,8 @@ def get_props(backend): except Exception: gate_arr.append(float('nan')) gate_props = {f"{gate_name}_error": gate_arr} - # Best-effort cache warm — never let a cache write break the scan. + # WRITE-ONLY cache warming (history feed) — never gates the score, and + # never breaks the scan if it fails. try: lu = data._extract_last_update(props) if lu: @@ -196,7 +251,11 @@ def get_props(backend): except Exception: _log.debug("Scan props: cache warm failed for %s", backend_name, exc_info=True) + # Vintage is 'live · ' by construction — all scan rows are + # freshly fetched, so there is no stale case for the table to badge. return CachedPropsShim(qubit_props, gate_props, edges, - gate_key=f"{gate_name}_error") + gate_key=f"{gate_name}_error", + vintage=f"live · {_live_stamp()}", + n_qubits=n or None) return get_props diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index 092663c..c9f21cd 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -305,7 +305,8 @@ def _run_pipeline(self): state=state, out=self.out, W=W, lucj_norb_slider=self.lucj_norb_slider, lucj_ancilla_dd=self.lucj_ancilla_dd, lucj_min_ancilla=self.lucj_min_ancilla, - lucj_chk_score=self.lucj_chk_score, btn_lucj_run=self.btn_lucj_run, + lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, + btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, @@ -1227,6 +1228,12 @@ def _build_auto_lucj_widgets(self, W): value=True, description='Score layouts (pick lowest error)', layout=W) + self.chk_deep_search = Checkbox( + value=True, + description='Deep search per ancilla count', + layout=W, + tooltip='adds a direct search per k — complete but slower; ' + 'off = fast derivation from k_max only') self.btn_lucj_run = Button( description='🤖 Generate LUCJ Layout', button_style='success', layout=W) @@ -1692,6 +1699,7 @@ def _build_auto_lucj_view(self): self.lucj_ancilla_dd, self.lucj_min_ancilla, self.lucj_chk_score, + self.chk_deep_search, self.chk_stability_filter, self.stability_ctrl_box, self.lbl_lucj_stability, diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index be1195a..c18ed23 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -44,6 +44,16 @@ def _format_best_per_k(strata): return ' · '.join(parts) +def _sweep_mode_label(res): + """(H2) 'direct+derived' when any lower stratum got a direct-VF2 hit, + else 'derived-only'.""" + kmax = res.get('k_max_effective') + ps = res.get('per_stratum', {}) + direct = any(v.get('n_direct', 0) > 0 for k, v in ps.items() + if kmax is not None and k < kmax) + return 'direct+derived' if direct else 'derived-only' + + def _format_sweep_status(res): """One-line sweep summary (M2): 'Sweep: k=6..3 · 214 embeddings · best per k: ...'. All interpolations esc()'d.""" @@ -93,6 +103,7 @@ def setup_lucj_callbacks(ctx): lucj_ancilla_dd = ctx.lucj_ancilla_dd lucj_min_ancilla = ctx.lucj_min_ancilla lucj_chk_score = ctx.lucj_chk_score + chk_deep_search = ctx.chk_deep_search btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status lbl_lucj_trunc = ctx.lbl_lucj_trunc @@ -289,6 +300,24 @@ def _annotate_circuit_lqs(res): except Exception: e['lqs_circuit'] = None + # ── P1: SINGLE SOURCE of sweep params — local AND scan read this ── + def _sweep_kwargs_from_ui(): + """The one place sweep parameters are derived from the UI. Both the + local sweep and every scan per-target call pass exactly this, so the + two can never diverge again (the tonight bug).""" + min_val = lucj_min_ancilla.value + min_bridges = None if (min_val is None or min_val <= 0) else min_val + return { + 'min_bridges': min_bridges, + 'top_n': 3, + 'hybrid': chk_deep_search.value, + } + + # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the + # active backend's reference in the scan table (P2), so the scan never + # re-searches self yet keeps the reference point. + _local_best_lqs = [None] + # ── Legacy single-count search ─────────────────────────────── def _generate_legacy(norb, requested_ancillas): from ..auto_lucj import get_all_zigzag_layouts @@ -345,9 +374,8 @@ def _generate_legacy(norb, requested_ancillas): def _generate_sweep(norb): from ..ancilla_sweep import sweep_ancilla_layouts - # 0 (or blank) → engine default min(3, k_max); else the user floor. - min_val = lucj_min_ancilla.value - min_bridges = None if (min_val is None or min_val <= 0) else min_val + # P1: exact same params the scan uses (min_bridges / top_n / hybrid). + kwargs = _sweep_kwargs_from_ui() # V2: opt-in stability filter (drop-in superset of the plain sweep). history = getattr(state, 'cal_history', None) @@ -357,7 +385,7 @@ def _generate_sweep(norb): norb, state.active_backend, state.initial_props, history, window_days=rb_stability_window.value, threshold=ft_stability_threshold.value, - min_bridges=min_bridges) + min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n']) _render_stability_banner(res.get('stability'), norb) # The frozen stability engine can't take circuit_score_fn — fill # circuit-level LQS on its survivors here (A2). @@ -365,8 +393,8 @@ def _generate_sweep(norb): else: res = sweep_ancilla_layouts( norb, state.active_backend, state.initial_props, - min_bridges=min_bridges, - circuit_score_fn=_circuit_score) # A2: aligned circuit LQS + circuit_score_fn=_circuit_score, # A2: aligned circuit LQS + **kwargs) # P1 single source (incl. hybrid) if _stability_filter_active(): # Checkbox on but no history dict → skipped note. _render_stability_banner(None, norb) @@ -389,6 +417,11 @@ def _generate_sweep(norb): )) flat.append(entry) + # Remember the best circuit-level LQS for the scan's active-row ref. + circ = [e['lqs_circuit'] for e in flat + if e.get('lqs_circuit') is not None] + _local_best_lqs[0] = max(circ) if circ else None + _seed_layout_dropdown(flat, dd_opts) # Truncation banner (U5): visible only when the VF2 cap was hit. @@ -407,10 +440,12 @@ def _generate_sweep(norb): if flat: cap = _k_cap_phrase(norb, res.get('k_max_effective')) cap_txt = f" · {esc(cap)}" if cap else "" + mode_txt = f" · {esc(_sweep_mode_label(res))}" lbl_lucj_status.value = ( f"
✅ {_format_sweep_status(res)}{cap_txt}
") + f"margin:3px 0;'>✅ {_format_sweep_status(res)}{mode_txt}" + f"{cap_txt}") else: lbl_lucj_status.value = ( f"
' by construction. The old + cached-snapshot stale-badge path (utc parse + >24h compare) is gone — + the scan never scores from a cached snapshot.""" + if not vintage: + return "—" + return f"{esc(str(vintage))}" + def _render_results(scan_result): results = scan_result['results'] head = ("" @@ -727,18 +786,36 @@ def _render_results(scan_result): "" "" "" - "") + "" + "") body = [] + # (P2) Active backend reference row — greyed, quotes the LOCAL number, + # never re-searched. Keeps the cross-QPU reference point at zero cost. + active = _scan.get('active') + if active: + lb = _local_best_lqs[0] + lqs_ref = (f"{lb * 100.0:.1f}% (local)" if lb is not None + else "run Auto above") + body.append( + f"" + f"" + f"" + f"" + f"") for r in results: name = esc(str(r['name'])) fam = esc(str(r['family'] or '?')) badge = _stability_badge(r) + vcell = _vintage_cell(r.get('vintage')) if r['error']: body.append( f"" f"" f"" - f"") elif r['best_lqs'] is None: body.append( @@ -748,17 +825,21 @@ def _render_results(scan_result): f"" f"") + f"{badge}" + f"") else: - # Scan sweeps aren't circuit-scored (remote backend props are - # not the current state's) → template heuristic, flagged. - best_entry = None - for _entries in r['sweep']['strata'].values(): - if _entries: - best_entry = _entries[0] - break - if best_entry is not None and best_entry.get('lqs_circuit') is not None: - lqs = esc(f"{best_entry['lqs_circuit'] * 100.0:.1f}%") + # (F3) Summary best-LQS = MAX circuit LQS over ALL entries, + # ignoring None (annotation failed) and NOT just the k_max + # stratum #1 — quoting k_max quoted its 0.0 dead-edge wall + # while lower strata were fine (SYM-2). Fall back to the + # product heuristic (flagged) only when NOTHING was scored. + lqs_vals = [e['lqs_circuit'] + for _entries in r['sweep']['strata'].values() + for e in _entries + if e.get('lqs_circuit') is not None] + if lqs_vals: + lqs = esc(f"{max(lqs_vals) * 100.0:.1f}%") else: lqs = esc(f"{r['best_lqs'] * 100.0:.1f}% (template)") ncand = sum(len(v) for v in r['sweep']['strata'].values()) @@ -775,7 +856,9 @@ def _render_results(scan_result): f"" f"") + f"{badge}{cap_html}" + f"") children = [HTML(head + "".join(body) + "
best LQSkcandsstability
stabilitycalib
📍 {esc(str(active['name']))}" + f"{esc(str(active['family'] or '?'))}" + f"{esc(lqs_ref)}current backend — " + f"see local results above
{name}{fam}✗ " + f"✗ " f"{esc(str(r['error']))}
no candidates" f"" - f"{badge}
" + f"{vcell}
" f"{esc(str(ncand))}" - f"{badge}{cap_html}
" + f"{vcell}
")] # Per-QPU stratified dropdowns (same label format as single-circuit). @@ -864,12 +947,10 @@ def _on_scan_click(b): "❌ Connect a " "backend first.") return - from ..qpu_scan import list_scan_targets, scan_qpus, _detect_family + from ..qpu_scan import list_scan_targets, _detect_family from ..props_shim import make_scan_get_props norb = lucj_norb_slider.value - min_val = lucj_min_ancilla.value - min_bridges = None if (min_val is None or min_val <= 0) else min_val try: family = _detect_family(state.active_backend) except Exception: @@ -879,6 +960,16 @@ def _on_scan_click(b): targets = list_scan_targets( state, norb, same_family_as=family, include_other_families=chk_scan_other_families.value) + + # (P2) Never re-search the active backend — mark it skipped and quote + # the local result instead. No sweep, no fetch for it. + active_name = getattr(state, 'active_backend_name', None) + _scan['active'] = None + for t in targets: + if t.get('name') == active_name: + t['eligible'] = False + t['reason'] = 'current backend — see local results above' + _scan['active'] = {'name': t['name'], 'family': t.get('family')} _render_targets(targets) # immediate feedback eligible = [t for t in targets if t['eligible']] @@ -909,13 +1000,9 @@ def _work(): except Exception: pass try: - if use_scan_filter: - result = _scan_filtered(eligible, norb, get_backend, - get_props, min_bridges) - else: - result = scan_qpus(eligible, norb, get_backend, get_props, - min_bridges=min_bridges, top_n=3, - progress_cb=_on_scan_progress) + # (P1) One scan path, one param source — forwards hybrid. + result = _scan_backends(eligible, norb, get_backend, + get_props, use_scan_filter) # (A3/S2) Circuit-level LQS per backend — one scale everywhere. _annotate_scan_circuit_lqs(result, get_backend, get_props) return (result, list(handler.records)) diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index a3b97f3..1a921be 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -188,15 +188,18 @@ def test_bridge_slots_are_prefix(backend, props): # ── F2d: a derived k' entry == its parent embedding's first-k' bridges ────── def test_prefix_legacy_equivalence(backend, props): - """A derived k' candidate must be indistinguishable from the original + """A DERIVED k' candidate must be indistinguishable from the original code computing exactly-k' on the same embedding: its kept ancilla physical qubits equal the first k' ancillas of a k_max parent on the - same chain (ancillas are stored in bridge-slot order).""" + same chain (ancillas are stored in bridge-slot order). Direct 'vf2' + hybrid entries are genuinely new chains and are exempt.""" res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) kmax = res['k_max_effective'] parents = res['strata'][kmax] # full-ancilla vf2 entries for k, entries in res['strata'].items(): for e in entries: + if e['source'] != 'derived': # skip direct-VF2 entries + continue chain = frozenset(e['alpha']) | frozenset(e['beta']) assert any( (frozenset(p['alpha']) | frozenset(p['beta'])) == chain @@ -343,6 +346,119 @@ def test_truncation(backend, props): assert len(e['ancillas']) == k +# ── Hybrid mode (H1) ──────────────────────────────────────────────────────── + +def _regression_backend(): + """A graph where the k_max (2-bridge) template ONLY fits a bad-qubit + corridor, but the k'=1 template ALSO fits a clean region: + + * BAD block (0..23): full ladder, bridges at every column → hosts k=2 + (through qubit 3, which is deliberately terrible). + * GOOD block (24..40): two clean chains with a bridge at column 0 ONLY + → hosts k=1 but NOT k=2 (no bridge at slot 4). + """ + edges = [] + top, bot, brg = list(range(8)), list(range(8, 16)), list(range(16, 24)) + for j in range(7): + edges += [(top[j], top[j + 1]), (bot[j], bot[j + 1])] + for j in range(8): + edges += [(top[j], brg[j]), (brg[j], bot[j])] + gtop, gbot = list(range(24, 32)), list(range(32, 40)) + for j in range(7): + edges += [(gtop[j], gtop[j + 1]), (gbot[j], gbot[j + 1])] + edges += [(gtop[0], 40), (40, gbot[0])] # single bridge at col 0 + g = rustworkx.PyDiGraph() + for i in range(41): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _RegressionProps: + def readout_error(self, q): + if q == 3: + return 0.5 # THE bad qubit + return 0.001 if q >= 24 else 0.02 + def gate_error(self, name, edge): + u, v = edge + if 3 in (u, v): + return 0.5 + return 0.001 if (u >= 24 and v >= 24) else 0.02 + + +def test_hybrid_regression_direct_finds_clean_chain(): + """THE live finding: the direct per-k VF2 recovers a clean k=1 chain the + derived stratum cannot contain by construction.""" + backend, props = _regression_backend(), _RegressionProps() + + res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) + assert res['k_max_effective'] == 2 + # k=2 only fits the BAD corridor → its top includes qubit 3. + k2 = res['strata'][2][0] + assert 3 in (set(k2['alpha']) | set(k2['beta'])) + # k=1 #1 AVOIDS qubit 3, lives in the GOOD region, via the DIRECT pass. + k1 = res['strata'][1][0] + used = set(k1['alpha']) | set(k1['beta']) | set(k1['ancillas']) + assert 3 not in used + assert used <= set(range(24, 41)) + assert k1['source'] == 'vf2' + + # hybrid=False: derivation-only → the SAME stratum is all 'derived' and + # includes the bad qubit. + res0 = sweep_ancilla_layouts(8, backend, props, min_bridges=1, + top_n=1000, hybrid=False) + k1_0 = res0['strata'][1][0] + assert 3 in (set(k1_0['alpha']) | set(k1_0['beta'])) + assert all(e['source'] == 'derived' for e in res0['strata'][1]) + + +def test_hybrid_false_byte_compatible(backend, props): + """hybrid=False → derivation-only: every k' + assert props.readout_error(0) == pytest.approx(0.02) -def test_factory_cache_hit(monkeypatch): - qp, gp, edges = _fixtures() - # Fake backend: coupling map + num_qubits + a 2Q gate + a name. +# ── V1: active backend scored on LIVE state props (cache NOT consulted) ────── + +def test_active_backend_uses_state_props_not_cache(monkeypatch): + qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04])} + gp = {'cz_error': np.array([0.001, 0.002, 0.003])} + edges = [(0, 1), (1, 2), (2, 3)] backend = SimpleNamespace( - name='ibm_fake', - num_qubits=4, + name='ibm_active', num_qubits=4, coupling_map=SimpleNamespace(get_edges=lambda: list(edges)), operation_names=['cz', 'sx', 'rz', 'x'], - ) + properties=lambda: (_ for _ in ()).throw( + AssertionError("must not fetch live for active backend"))) + + from qpu_mapper import data + cache_calls = [] + monkeypatch.setattr(data, 'list_known_calibrations', + lambda name, date=None: cache_calls.append(name) or []) + monkeypatch.setattr(data, '_load_calibration', + lambda name, ts: cache_calls.append(('load', name)) or None) + + state = SimpleNamespace( + active_backend_name='ibm_active', + qubit_props_data=qp, gate_props_data=gp, edges_list=edges, + qubit_ids=['0', '1', '2', '3']) + props = make_scan_get_props(state)(backend) + assert cache_calls == [] # cache NEVER consulted + assert props.vintage == 'live' + + # Score equals the C1 wrapper on the same fixture (identical data path). + from qpu_mapper.export.scoring import estimate_circuit_fidelity + st = SimpleNamespace( + layouts_data={0: {'alpha': ['0', '1'], 'beta': ['2', '3'], + 'other': [], 'ancilla': []}}, + qubit_props_data=qp, gate_props_data=gp, + qubit_ids=['0', '1', '2', '3'], edges_list=edges) + local = estimate_circuit_fidelity(st, 0, 'lucj')['fidelity'] + assert props.score_layout([0, 1, 2, 3])['fidelity'] == pytest.approx(local) + + +# ── L1/t2: a fetch failure raises (no cached fallback) ────────────────────── + +def test_remote_fetch_failure_raises_no_cache_fallback(monkeypatch): from qpu_mapper import data + # A cached snapshot EXISTS, but it must NOT be used as a fallback. monkeypatch.setattr(data, 'list_known_calibrations', - lambda name, day: [{'last_update': '2026-07-12 09:00:00'}]) - monkeypatch.setattr(data, '_load_calibration', lambda name, ts: (qp, gp)) - # properties() must NOT be called on a cache hit. - backend.properties = lambda: (_ for _ in ()).throw( - AssertionError("live fetch on cache hit")) - - state = SimpleNamespace(active_backend_name='current') - get_props = make_scan_get_props(state, now='2026-07-12') - props = get_props(backend) - - assert props.readout_error(2) == pytest.approx(0.030) - assert props.gate_error('cz', (2, 1)) == pytest.approx(0.002) + lambda *a, **k: [{'last_update': '2026-07-05 08:00:00'}]) + monkeypatch.setattr(data, '_load_calibration', + lambda *a, **k: ({'readout_error': [0.01, 0.02]}, + {'cz_error': [0.001]})) + + backend = _fake_remote_backend() + backend.properties = lambda: (_ for _ in ()).throw(RuntimeError("network down")) + state = SimpleNamespace(active_backend_name='current_other') + with pytest.raises(RuntimeError): + make_scan_get_props(state)(backend) # no silent cached fallback + + +# ── D2 t1: the shim scores against ITS OWN edges, not the current state ───── + +def test_shim_scores_against_own_edges(): + edges = [(0, 1), (1, 2), (2, 3)] + # Backend X: coupler (0,1) is DEAD. Backend Y: (0,1) is healthy. + x = CachedPropsShim({'readout_error': [0.001] * 4}, + {'cz_error': [1.0, 0.001, 0.001]}, edges) + y = CachedPropsShim({'readout_error': [0.001] * 4}, + {'cz_error': [0.001, 0.001, 0.001]}, edges) + # Candidate uses qubits 0,1,2 → only edges (0,1) and (1,2) count. + fx = x.score_layout([0, 1, 2])['fidelity'] + fy = y.score_layout([0, 1, 2])['fidelity'] + assert fx == pytest.approx(0.0) # X's dead (0,1) → zero + assert fy > 0.9 # Y's (0,1) healthy → high + # Each shim used its OWN per-edge errors, not a shared/state edge list. + + +# ── D2 t2: the hard invariants reject a mispaired snapshot ────────────────── + +def test_gate_length_mismatch_raises(): + with pytest.raises(ValueError): + CachedPropsShim({'readout_error': [0.01] * 4}, + {'cz_error': [0.001, 0.001]}, # 2 != 3 edges + [(0, 1), (1, 2), (2, 3)]) + + +def test_qubit_length_mismatch_raises(): + with pytest.raises(ValueError): + CachedPropsShim({'readout_error': [0.01, 0.02, 0.03]}, # 3 != 4 qubits + {'cz_error': [0.001]}, [(0, 1)], n_qubits=4) + + +# ── D2 t3: end-to-end pin — shim score == core hand-built from same snapshot ─ + +def test_shim_score_matches_core_handbuilt(): + from qpu_mapper.export.scoring import estimate_fidelity_core + qp = {'readout_error': [0.01, 0.02, 0.03, 0.04]} + gp = {'cz_error': [0.001, 0.002, 1.0]} # (2,3) dead + edges = [(0, 1), (1, 2), (2, 3)] + cand = [0, 1, 2, 3] + + shim_score = CachedPropsShim(qp, gp, edges).score_layout(cand)['fidelity'] + + readout_by_id = {q: qp['readout_error'][q] for q in cand} + gate_edges = [(u, v, gp['cz_error'][i]) for i, (u, v) in enumerate(edges)] + core = estimate_fidelity_core(cand, readout_by_id, gate_edges, + all_readout=qp['readout_error'])['fidelity'] + + assert shim_score == pytest.approx(core) + assert shim_score == pytest.approx(0.0) # dead coupler seen, not hidden + + +# ── SYM-1 t1: score_layout scores the FULL directed surface (== C1 core) ───── + +def test_score_layout_full_directed_surface(): + from qpu_mapper.export.scoring import estimate_fidelity_core + # Bidirectional coupling map + an INCIDENTAL edge (0,2) among the set + # (not on the chain path) carrying a large error. + edges = [(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)] + cz = [0.01, 0.01, 0.01, 0.01, 0.30, 0.30] + qp = {'readout_error': [0.01, 0.01, 0.01]} + gp = {'cz_error': cz} + cand = [0, 1, 2] + + shim = CachedPropsShim(qp, gp, edges) + sh = shim.score_layout(cand) + + core = estimate_fidelity_core( + cand, {q: qp['readout_error'][q] for q in cand}, + [(u, v, cz[i]) for i, (u, v) in enumerate(edges)], + all_readout=qp['readout_error']) + + assert sh['fidelity'] == pytest.approx(core['fidelity']) + assert sh['n_gates'] == 6 # all directed edges counted + # The incidental (0,2) 0.30 factor IS included (both dirs) — not skipped. + healthy_only = estimate_fidelity_core( + cand, {q: 0.01 for q in cand}, + [(0, 1, 0.01), (1, 0, 0.01), (1, 2, 0.01), (2, 1, 0.01)], + all_readout=qp['readout_error']) + assert sh['fidelity'] < healthy_only['fidelity'] + + +# ── SYM-3 t2: shim uses ITS OWN edges (no current-state leak) ──────────────── + +def test_shim_edges_are_its_own(): + edges = [(5, 6), (6, 5), (6, 7), (7, 6)] # backend X's own topology + shim = CachedPropsShim({'readout_error': [0.0] * 8}, + {'cz_error': [0.1, 0.1, 0.2, 0.2]}, edges, n_qubits=8) + assert shim._edges == [(5, 6), (6, 5), (6, 7), (7, 6)] # X's edges verbatim + # A mismatched-length snapshot for a different topology → ValueError (F2). + with pytest.raises(ValueError): + CachedPropsShim({'readout_error': [0.0] * 8}, + {'cz_error': [0.1, 0.1]}, edges, n_qubits=8) diff --git a/tests/test_scan_notices.py b/tests/test_scan_notices.py index a4950e8..eb206a3 100644 --- a/tests/test_scan_notices.py +++ b/tests/test_scan_notices.py @@ -48,7 +48,7 @@ def _build(monkeypatch): state.active_backend = object() state.active_backend_name = "stub" state.active_chip = "stub_chip" - state.active_service = SimpleNamespace(backend=lambda n: object()) + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) state.available_backends = ["ibm_a"] state.props_warning = None state.initial_props = object() @@ -69,6 +69,14 @@ def _patch_targets(monkeypatch, names=('ibm_a',)): for n in names]) +def _patch_engine(monkeypatch, sweep_fn): + """Drive _scan_backends: per-target sweep + a stub props factory.""" + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", sweep_fn) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: SimpleNamespace( + vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) + + def _all_html(box): from ipywidgets import HTML return " ".join(c.value for c in box.children if isinstance(c, HTML)) @@ -79,14 +87,7 @@ def _all_html(box): def test_k_capped_row_note(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - import qpu_mapper.qpu_scan as qs - - def scan_capped(*a, **k): - return {'results': [{'name': 'ibm_a', 'family': 'Heron', - 'sweep': _sweep(k_max_effective=2), - 'best_lqs': 0.5, 'best_k': 2, 'error': None}], - 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} - monkeypatch.setattr(qs, 'scan_qpus', scan_capped) + _patch_engine(monkeypatch, lambda *a, **k: _sweep(k_max_effective=2)) b.lucj_norb_slider.value = 12 # request = ceil(12/4) = 3 b.btn_scan_qpus.click() @@ -96,14 +97,7 @@ def scan_capped(*a, **k): def test_k_not_capped_no_note(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - import qpu_mapper.qpu_scan as qs - - def scan_ok(*a, **k): - return {'results': [{'name': 'ibm_a', 'family': 'Heron', - 'sweep': _sweep(k_max_effective=3), - 'best_lqs': 0.5, 'best_k': 3, 'error': None}], - 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} - monkeypatch.setattr(qs, 'scan_qpus', scan_ok) + _patch_engine(monkeypatch, lambda *a, **k: _sweep(k_max_effective=3)) b.lucj_norb_slider.value = 12 # request = 3, k_eff = 3 → equal b.btn_scan_qpus.click() @@ -118,18 +112,13 @@ def test_notices_capture_and_dedup(monkeypatch): import qpu_mapper.qpu_scan as qs lg = logging.getLogger('qpu_mapper') - def scan_warns(targets, norb, gb, gp, **kw): - cb = kw['progress_cb'] - cb('ibm_a', 'start', '') + def sweep_warns(norb, backend, props, **kw): + # Runs while _scan['current'] == 'ibm_a' (set by the 'start' event). lg.warning("stale cache housekeeping") lg.warning("stale cache housekeeping") lg.warning("other notice") - cb('ibm_a', 'ok', '') - return {'results': [{'name': 'ibm_a', 'family': 'Heron', - 'sweep': _sweep(), 'best_lqs': 0.5, 'best_k': 1, - 'error': None}], - 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0} - monkeypatch.setattr(qs, 'scan_qpus', scan_warns) + return _sweep() + _patch_engine(monkeypatch, sweep_warns) b.btn_scan_qpus.click() html = _all_html(b.scan_results_box) @@ -145,22 +134,18 @@ def scan_warns(targets, norb, gb, gp, **kw): def test_logger_restored_after_scan(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - import qpu_mapper.qpu_scan as qs lg = logging.getLogger('qpu_mapper') h0, p0 = list(lg.handlers), lg.propagate - monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { - 'results': [{'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(), - 'best_lqs': 0.5, 'best_k': 1, 'error': None}], - 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) - b.btn_scan_qpus.click() + _patch_engine(monkeypatch, lambda *a, **k: _sweep()) + b.btn_scan_qpus.click() # normal path assert list(lg.handlers) == h0 assert lg.propagate == p0 - def boom(*a, **k): - raise RuntimeError("scan blew up") - monkeypatch.setattr(qs, 'scan_qpus', boom) - b.btn_scan_qpus.click() # error path + # A malformed sweep makes _work raise (best_lqs loop is outside the + # per-target isolation) → the on_error/finally path must still restore. + _patch_engine(monkeypatch, lambda *a, **k: {'strata': None}) + b.btn_scan_qpus.click() assert list(lg.handlers) == h0 # still restored assert lg.propagate == p0 @@ -170,10 +155,6 @@ def boom(*a, **k): def test_no_notices_section_when_empty(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - import qpu_mapper.qpu_scan as qs - monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: { - 'results': [{'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(), - 'best_lqs': 0.5, 'best_k': 1, 'error': None}], - 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) + _patch_engine(monkeypatch, lambda *a, **k: _sweep()) b.btn_scan_qpus.click() assert '⚠ notices' not in _all_html(b.scan_results_box) diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index f191db5..48abb8f 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -1,14 +1,14 @@ -"""Headless tests for the multi-QPU scan UI (Component 3b) + M1/M2. +"""Headless tests for the multi-QPU scan UI. -Offline: the data layer is stubbed, and qpu_scan.scan_qpus / list_scan_targets -are monkeypatched with canned results (no VF2, no network). The background -spawn and the progress marshal primitive are injected synchronously so the -handler runs deterministically. +Offline: the scan runs through the single handler-side path (_scan_backends), +so we monkeypatch the per-target sweep (ancilla_sweep.sweep_ancilla_layouts), +list_scan_targets, and the props factory (make_scan_get_props → a stub with +score_layout + vintage). The spawn and progress marshal are injected +synchronously so the handler runs deterministically. """ from types import SimpleNamespace import numpy as np -import pytest from qpu_mapper.ui.lucj_panel import _format_sweep_status @@ -42,21 +42,22 @@ def entry(prod, k): 'rank_in_stratum': 1, 'source': 'vf2'} return {'strata': {2: [entry(prod_lo, 2)], 1: [entry(prod_hi, 1)]}, 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': False, - 'n_raw_embeddings': 10, 'n_candidates_scored': 20} + 'n_raw_embeddings': 10, 'n_candidates_scored': 20, + 'per_stratum': {2: {'n_direct': 1, 'n_derived': 0, 'truncated': False}, + 1: {'n_direct': 1, 'n_derived': 1, 'truncated': False}}} -def _fake_scan_result(error='fetch failed'): - return { - 'results': [ - {'name': 'ibm_b', 'family': 'Heron', 'sweep': _sweep(0.60, 0.50), - 'best_lqs': 0.60, 'best_k': 1, 'error': None}, - {'name': 'ibm_a', 'family': 'Heron', 'sweep': _sweep(0.40, 0.30), - 'best_lqs': 0.40, 'best_k': 1, 'error': None}, - {'name': 'ibm_c', 'family': 'Nighthawk', 'sweep': None, - 'best_lqs': None, 'best_k': None, 'error': error}, - ], - 'n_scanned': 2, 'n_failed': 1, 'n_skipped': 0, - } +class _StubProps: + """Per-backend props stand-in: score_layout returns a fixed fidelity; + carries a vintage. score_layout raises when fid is None.""" + def __init__(self, fid=0.5, vintage='live'): + self._fid = fid + self.vintage = vintage + + def score_layout(self, qubits): + if self._fid is None: + raise RuntimeError("no circuit score") + return {'fidelity': self._fid} def _targets(): @@ -82,9 +83,9 @@ def _build(monkeypatch, spawn=_sync_spawn, marshal=None): state = SessionState() state.active_backend = object() - state.active_backend_name = "stub" + state.active_backend_name = "stub" # NOT one of _targets → no ref row state.active_chip = "stub_chip" - state.active_service = SimpleNamespace(backend=lambda n: object()) + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) state.available_backends = ["ibm_a", "ibm_b", "ibm_c"] state.props_warning = None state.initial_props = object() @@ -99,20 +100,26 @@ def _build(monkeypatch, spawn=_sync_spawn, marshal=None): return b -def _patch_scan(monkeypatch, result=None, capture_progress=False): +def _patch_scan(monkeypatch, sweeps=None, props=None, targets=None): + """Drive _scan_backends: canned per-target sweep + stub props factory.""" import qpu_mapper.qpu_scan as qs - monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: _targets()) - res = result if result is not None else _fake_scan_result() - - def fake_scan(targets, norb, get_backend, get_props, **kw): - cb = kw.get('progress_cb') - if capture_progress and cb: - for r in res['results']: - cb(r['name'], 'start', '') - cb(r['name'], 'ok' if r['error'] is None else 'error', - r['error'] or '') - return res - monkeypatch.setattr(qs, 'scan_qpus', fake_scan) + import qpu_mapper.ancilla_sweep as asw + import qpu_mapper.props_shim as ps + monkeypatch.setattr(qs, 'list_scan_targets', + lambda *a, **k: targets or _targets()) + sweeps = sweeps or {'ibm_b': _sweep(0.60, 0.50), 'ibm_a': _sweep(0.40, 0.30), + 'ibm_c': RuntimeError('fetch failed')} + + def fake_sweep(norb, backend, propsobj, **kw): + s = sweeps[backend.name] + if isinstance(s, Exception): + raise s + return s + monkeypatch.setattr(asw, 'sweep_ancilla_layouts', fake_sweep) + props = props or {'ibm_b': _StubProps(0.60), 'ibm_a': _StubProps(0.40), + 'ibm_c': _StubProps(0.0)} + monkeypatch.setattr(ps, 'make_scan_get_props', + lambda state: (lambda backend: props[backend.name])) def _dropdowns(children): @@ -120,7 +127,7 @@ def _dropdowns(children): return [c for c in children if isinstance(c, Dropdown)] -# ── t2: scan happy path — table sorted, dropdowns, button re-enabled ──────── +# ── happy path — table sorted, dropdowns, button re-enabled ───────────────── def test_scan_happy_path(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -129,86 +136,77 @@ def test_scan_happy_path(monkeypatch): children = b.scan_results_box.children table_html = children[0].value - assert table_html.index('ibm_b') < table_html.index('ibm_a') # sorted + assert table_html.index('ibm_b') < table_html.index('ibm_a') # sorted assert '60.0%' in table_html and '40.0%' in table_html - # One stratified dropdown per successful QPU. - assert len(_dropdowns(children)) == 2 - # Button re-enabled after completion. + assert len(_dropdowns(children)) == 2 # per success assert b.btn_scan_qpus.disabled is False -# ── t3: progress marshaling — no direct-from-thread widget writes ─────────── +# ── progress marshaling — no direct-from-thread widget writes ─────────────── def test_scan_progress_marshaled(monkeypatch): captured = [] b = _build(monkeypatch, marshal=lambda cb: captured.append(cb)) - _patch_scan(monkeypatch, capture_progress=True) + _patch_scan(monkeypatch) b.btn_scan_qpus.click() - # Progress callbacks were marshaled, NOT applied directly: the progress - # label is still empty even though progress_cb fired during the scan. - assert b.lbl_scan_progress.value == "" - assert captured, "progress updates should have been marshaled" - - # Draining the marshaled callbacks updates the label on the main loop. + assert b.lbl_scan_progress.value == "" # marshaled, not direct + assert captured for cb in captured: cb() assert 'ibm_b' in b.lbl_scan_progress.value assert '✓' in b.lbl_scan_progress.value -# ── t4: failed-backend row greyed with esc()'d error ──────────────────────── +# ── failed-backend row greyed with esc()'d error ──────────────────────────── def test_scan_failed_row_escaped(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) - _patch_scan(monkeypatch, result=_fake_scan_result(error='boom ')) + _patch_scan(monkeypatch, sweeps={ + 'ibm_b': _sweep(0.60, 0.50), 'ibm_a': _sweep(0.40, 0.30), + 'ibm_c': RuntimeError('boom ')}) b.btn_scan_qpus.click() table_html = b.scan_results_box.children[0].value - assert 'color:#999' in table_html # greyed - assert 'boom <x>' in table_html # esc()'d error, not raw '' + assert 'color:#999' in table_html + assert 'boom <x>' in table_html assert '' not in table_html -# ── t7: handoff — selecting a remote candidate stages it ──────────────────── +# ── handoff — selecting a remote candidate stages it ──────────────────────── def test_scan_handoff_on_select(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) _patch_scan(monkeypatch) - staged = [] b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) b.btn_scan_qpus.click() dds = _dropdowns(b.scan_results_box.children) - dds[0].value = 0 # pick ibm_b's top candidate + dds[0].value = 0 # ibm_b top candidate assert len(staged) == 1 name, cand = staged[0] assert name == 'ibm_b' - # flat index 0 = top stratum (k descending) = the k=2 entry. - assert cand['ancillas'] == [4, 5] + assert cand['ancillas'] == [4, 5] # flat[0] = k=2 entry -# ── t5: M1 — sweep mode greys out the score checkbox ──────────────────────── +# ── M1 — sweep mode greys the score checkbox ──────────────────────────────── def test_m1_score_checkbox_toggle(monkeypatch): b = _build(monkeypatch) - # Default: Ancilla='Auto' (-1) → sweep mode → score checkbox disabled. assert b.lucj_ancilla_dd.value == -1 assert b.lucj_chk_score.disabled is True - - b.lucj_ancilla_dd.value = 2 # exact count → legacy mode + b.lucj_ancilla_dd.value = 2 assert b.lucj_chk_score.disabled is False - - b.lucj_ancilla_dd.value = -1 # back to sweep + b.lucj_ancilla_dd.value = -1 assert b.lucj_chk_score.disabled is True -# ── t6: M2 — per-stratum status line format ───────────────────────────────── +# ── M2 — per-stratum status line format ───────────────────────────────────── def test_m2_status_line_format(): - res = _sweep(0.40, 0.30) # strata 2→30%, 1→40% + res = _sweep(0.40, 0.30) res['k_max_effective'] = 2 res['min_bridges'] = 1 res['n_raw_embeddings'] = 214 @@ -216,28 +214,217 @@ def test_m2_status_line_format(): assert line == "Sweep: k=2..1 · 214 embeddings · best per k: 2→30.0% · 1→40.0%" -# ── A3 t4: scan circuit-LQS annotation (success → number, failure → template) +# ── A3: circuit-LQS annotation (success → number, failure → template) ─────── def test_scan_circuit_lqs_annotated(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) - _patch_scan(monkeypatch) # canned entries, no lqs_circuit - # A working per-backend shim → annotation fills circuit LQS on every entry. - from qpu_mapper.props_shim import CachedPropsShim - qp = {'readout_error': np.array([0.01] * 8)} - gp = {'cz_error': np.array([0.001] * 7)} - shim = CachedPropsShim(qp, gp, [(i, i + 1) for i in range(7)]) + _patch_scan(monkeypatch) # stub props score → circuit LQS + b.btn_scan_qpus.click() + assert '(template)' not in b.scan_results_box.children[0].value + + +def test_scan_template_suffix_only_on_failure(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + # Props whose score_layout raises → lqs_circuit stays None → template. + _patch_scan(monkeypatch, props={'ibm_b': _StubProps(None), 'ibm_a': _StubProps(None), + 'ibm_c': _StubProps(None)}) + b.btn_scan_qpus.click() + assert '(template)' in b.scan_results_box.children[0].value + + +# ── L2/t5: vintage renders 'live · ' (no stale badge) ─────────── + +def test_scan_live_vintage(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch, props={'ibm_b': _StubProps(0.6, 'live · 09:30'), + 'ibm_a': _StubProps(0.4, 'live · 09:30'), + 'ibm_c': _StubProps(0.0, 'live · 09:30')}) + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert 'live · 09:30' in table + assert 'stale calib' not in table # stale-badge path removed + + +# ── L1/t2: a fetch failure → honest error row, others complete ────────────── + +def test_scan_fetch_failure_error_row(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _sweep(0.6, 0.5)) + + def get_props(state): + def gp(backend): + if backend.name == 'ibm_a': + raise RuntimeError("network down fetching calibration") + return _StubProps(0.6, 'live · 09:30') + return gp + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", get_props) + + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert 'network down' in table # ibm_a → honest error row + assert 'live · 09:30' in table # ibm_b completed + + +# ── L4/t4: stability filter still reads the cache for HISTORY ──────────────── + +def test_stability_history_reads_cache(monkeypatch): + from qpu_mapper.state import SessionState + b = _build(monkeypatch, marshal=lambda cb: cb()) + # Enable the filter (needs local history available) + the scan sub-filter. + b.state.cal_history_dates = ['2026-07-01'] + b.state.cal_history = {'2026-07-01': {'qubit_props': {'readout_error': [0.01] * 8}, + 'gate_props': {}}} + b._refresh_stability_filter_availability() + b.chk_stability_filter.value = True + b.chk_scan_stability.value = True + + from qpu_mapper import data + loads = [] + monkeypatch.setattr(data, 'list_known_calibrations', + lambda name, date=None: [{'last_update': '2026-07-05 08:00:00'}]) + monkeypatch.setattr(data, '_load_calibration', + lambda name, ts: loads.append(name) or + ({'readout_error': [0.01] * 8}, {'cz_error': [0.001] * 7})) + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: {**_sweep(0.6, 0.5), 'stability': {'available': True}}) monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", - lambda state: (lambda backend: shim)) + lambda state: (lambda backend: _StubProps(0.6, 'live · 09:30'))) + b.btn_scan_qpus.click() + assert loads # cache loader used for HISTORY + + +# ── P1: local and scan pass IDENTICAL sweep params (the tonight bug) ──────── + +def test_local_and_scan_identical_sweep_kwargs(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + calls = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", + lambda *a, **k: _targets()) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: _StubProps(0.6))) + + b.chk_deep_search.value = False # a non-default value + b.lucj_min_ancilla.value = 2 + + b.btn_lucj_run.click() # local sweep + local_kw = calls[-1] + calls.clear() + b.btn_scan_qpus.click() # scan (per-target) + scan_kw = calls[0] + + keys = ('min_bridges', 'top_n', 'hybrid') + assert {k: local_kw.get(k) for k in keys} == {k: scan_kw.get(k) for k in keys} + assert scan_kw['hybrid'] is False # honored, not the engine default + + +# ── P2: active backend skipped-with-reference (never re-searched) ─────────── + +def test_active_backend_skipped_with_reference(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + swept = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: swept.append(bk.name) or _sweep(0.6, 0.5)) + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'stub', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: _StubProps(0.6))) + + b.btn_scan_qpus.click() + assert 'stub' not in swept # active never swept table = b.scan_results_box.children[0].value - assert '(template)' not in table # circuit-scored, not fallback + assert '📍 stub' in table + assert 'current backend' in table + assert 'run Auto above' in table # no local sweep yet → hint -def test_scan_template_suffix_only_on_failure(monkeypatch): +# ── P3: scan honors the hybrid checkbox ───────────────────────────────────── + +def test_scan_honors_hybrid_checkbox(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) - _patch_scan(monkeypatch) - # Default get_backend returns a bare object() → the real get_props raises - # (no coupling_map) → annotation skips → lqs_circuit stays None → template. + calls = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", + lambda *a, **k: _targets()) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: _StubProps(0.6))) + + b.chk_deep_search.value = True + b.btn_scan_qpus.click() + assert calls and all(kw['hybrid'] is True for kw in calls) + + +# ── SYM-2 t3/t4: None vs 0.0 distinguishable; summary = max over non-None ──── + +def _scan_html(b): + from ipywidgets import HTML + return " ".join(c.value for c in b.scan_results_box.children + if isinstance(c, HTML)) + + +def _patch_one_target(monkeypatch, sweep, props_obj): + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: sweep) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: props_obj)) + + +def test_annotation_failure_is_none_not_zero(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + + class _RaiseProps: + vintage = 'live' + def score_layout(self, q): + raise RuntimeError("edge cz absent from snapshot") + _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _RaiseProps()) + + b.btn_scan_qpus.click() + html = _scan_html(b) + assert '(template)' in html # None → template, not 0.0% + assert 'circuit score unavailable' in html # failure named in notices + + +def test_genuine_zero_renders_as_zero(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + + class _ZeroProps: + vintage = 'live' + def score_layout(self, q): + return {'fidelity': 0.0} # a real dead-edge zero + _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _ZeroProps()) + + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + assert '0.0%' in table # genuine zero shown as 0.0% + assert '(template)' not in table # 0.0 is a real score + + +def test_summary_best_is_max_over_non_none(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + + class _VaryProps: + vintage = 'live' + def score_layout(self, q): + # k=2 entry has 6 qubits → 0.0 (dead edge); k=1 has 5 → 0.62. + return {'fidelity': 0.0 if len(q) >= 6 else 0.62} + _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _VaryProps()) + b.btn_scan_qpus.click() table = b.scan_results_box.children[0].value - assert '(template)' in table + assert '62.0%' in table # summary = max, NOT the + assert not table.split('ibm_a')[1].startswith('0.0') # k_max 0.0 wall diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index d5c0ae0..c6cfa8a 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -151,23 +151,28 @@ def test_banner_states(monkeypatch): def test_scan_stability_badges(monkeypatch): b = _build(monkeypatch, history=True) + b.chk_stability_filter.value = True # enabled (history available) + b.chk_scan_stability.value = True # filter the scan too - import qpu_mapper.qpu_scan as qs - monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) - - def fake_scan(*a, **k): - return {'results': [ - {'name': 'ibm_a', 'family': 'Heron', 'sweep': _canned_res(None), - 'best_lqs': 0.5, 'best_k': 1, 'error': None, - 'stability': {'available': True, 'relaxed': False, - 'excluded_final': [3, 4], 'window_days': 14}}, - {'name': 'ibm_b', 'family': 'Heron', 'sweep': _canned_res(None), - 'best_lqs': 0.4, 'best_k': 1, 'error': None, - 'stability': {'available': False, 'reason': 'no cached history'}}, - ], 'n_scanned': 2, 'n_failed': 0, 'n_skipped': 0} - monkeypatch.setattr(qs, 'scan_qpus', fake_scan) + # ibm_a has CACHED history, ibm_b does not. + from qpu_mapper import data + monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: + [{'last_update': '2026-07-05 08:00:00'}] if name == 'ibm_a' else []) + monkeypatch.setattr(data, '_load_calibration', lambda name, ts: + ({'readout_error': [0.01] * 8}, {'cz_error': [0.001] * 7})) + # ibm_a → filtered (excluded_final); ibm_b → plain sweep. + filt = dict(_canned_res({'available': True, 'relaxed': False, + 'excluded_final': [3, 4], 'window_days': 14})) + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: filt) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned_res(None)) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: SimpleNamespace( + vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) b.btn_scan_qpus.click() table = b.scan_results_box.children[0].value diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index 2cddd95..3a7c8a3 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -202,3 +202,33 @@ def boom(*a, **k): assert "min_bridges=99 out of range" in b.lbl_lucj_status.value # UI stays usable: the button is re-enabled after the failure. assert b.btn_lucj_run.disabled is False + + +# ── H2: the deep-search checkbox wires hybrid= and the M2 mode label ──────── + +def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): + calls = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: (calls.append(k) or _fake_sweep_result())) + b = builder + b.chk_deep_search.value = False + b.btn_lucj_run.click() + assert calls[-1]['hybrid'] is False + b.chk_deep_search.value = True + b.btn_lucj_run.click() + assert calls[-1]['hybrid'] is True + + +def test_sweep_mode_label(): + from qpu_mapper.ui.lucj_panel import _sweep_mode_label + hy = {'k_max_effective': 3, + 'per_stratum': {3: {'n_direct': 5, 'n_derived': 0}, + 2: {'n_direct': 2, 'n_derived': 3}, + 1: {'n_direct': 0, 'n_derived': 4}}} + assert _sweep_mode_label(hy) == 'direct+derived' # k=2 got direct hits + dv = {'k_max_effective': 3, + 'per_stratum': {3: {'n_direct': 5, 'n_derived': 0}, + 2: {'n_direct': 0, 'n_derived': 3}, + 1: {'n_direct': 0, 'n_derived': 4}}} + assert _sweep_mode_label(dv) == 'derived-only' From f107b9b637b26f5b5451123ff8cf62917ecec282 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 15:33:16 -0400 Subject: [PATCH 11/66] email update --- pyproject.toml | 4 +- qpu_mapper/ancilla_sweep.py | 19 ++++- tests/test_cascade.py | 134 ++++++++++++++++++++++++++++++++++++ 3 files changed, 152 insertions(+), 5 deletions(-) create mode 100644 tests/test_cascade.py diff --git a/pyproject.toml b/pyproject.toml index 7efb3ff..3d39933 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,8 +9,8 @@ description = "Interactive, noise-aware QPU layout mapper for Jupyter Lab" readme = "README.md" requires-python = ">=3.10" authors = [ - { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com", email = "merzk@ccf.org" } - { name = "Milana Bazayeva", email = "m.bazayeva@gmail.com", email = "bazayem@ccf.org" }, + { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com" } + { name = "Milana Bazayeva", email = "m.bazayeva@gmail.com" }, ] keywords = ["quantum", "qiskit", "qpu", "layout", "visualization"] classifiers = [ diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index 1c928eb..13252dc 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -399,9 +399,18 @@ def _add_variant(edata, k, source): lay[value] = _key_to_phys(key) if any(v is None for v in lay): continue - n_candidates_scored += 1 - if _add_variant(_embedding_data(lay, nb_k), k, 'vf2'): - per_stratum[k]['n_direct'] += 1 + edata = _embedding_data(lay, nb_k) + # (K1) CASCADE: this direct k'-embedding seeds its OWN stratum + # (source 'vf2') AND every stratum below it via the prefix rule + # (source 'derived'). So a region that only a k'-search reaches + # — never enumerated at k_max — still populates all lower + # strata, and best-per-k stays monotone as k decreases. + for kk in range(k, min_bridges - 1, -1): + n_candidates_scored += 1 + src = 'vf2' if kk == k else 'derived' + if _add_variant(edata, kk, src): + bucket = 'n_direct' if kk == k else 'n_derived' + per_stratum[kk][bucket] += 1 # Aggregate truncation for the existing banner (k_max OR any direct pass). vf2_truncated = any(m['truncated'] for m in per_stratum.values()) @@ -440,4 +449,8 @@ def _add_variant(edata, k, source): 'n_candidates_scored': n_candidates_scored, 'excluded_qubits': excluded_sorted, 'per_stratum': per_stratum, + # (K3) The ACTUAL VF2 cap, so the truncation banner can name it + # ("truncated at 2000 mappings") instead of n_raw_embeddings, and + # per_stratum[k]['truncated'] says WHICH strata hit it. + 'mapping_cap': cap, } diff --git a/tests/test_cascade.py b/tests/test_cascade.py new file mode 100644 index 0000000..08a3805 --- /dev/null +++ b/tests/test_cascade.py @@ -0,0 +1,134 @@ +"""K2 — the cascade invariant (every direct stratum seeds all lower strata). + +Reproduces the live failure shape offline, deterministically, with a real VF2 +run on a tiny two-region host: + + * POOR region P (low ids): a width-16 ladder with bridge columns + {0,1,2,3,4,8}. It hosts the full k_max=3 template (bridges at cols 0,4,8), + and — crucially — it yields MANY more k=1 embeddings than k=2, so a small + mapping_cap fills up inside P (in node-index order) before the search ever + reaches the good region. + * GOOD region G (high ids): a width-12 ladder with bridge columns {0,4}. It + hosts k=2 but NOT k=3 (no col-8 bridge), so k_max derivation can never + reach it — only a direct k'=2 search does. Its qubits have near-zero error. + +With mapping_cap=8 the k'=1 DIRECT search truncates inside P and never sees G, +yet G's k=1 layout is still delivered to the k=1 stratum — proving it arrived +by CASCADE from the k'=2 winner, not by a direct search. The best-per-k series +is then monotonically non-decreasing as k decreases, and the delivered prefix +child scores >= its direct parent (fewer error factors can only raise the +product). +""" +from types import SimpleNamespace + +import rustworkx + +from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts + +NORB = 12 +GOOD = set(range(100, 126)) # region G qubit ids +CAP = 8 # small enough to truncate the k=1 direct + + +def _ladder(edges, width_top, width_bot, brg_cols, base_top, base_bot, base_brg): + tids = [base_top + j for j in range(width_top)] + bids = [base_bot + j for j in range(width_bot)] + for j in range(width_top - 1): + edges.append((tids[j], tids[j + 1])) + for j in range(width_bot - 1): + edges.append((bids[j], bids[j + 1])) + for i, c in enumerate(brg_cols): + bq = base_brg + i + edges.append((tids[c], bq)) + edges.append((bq, bids[c])) + + +def _make_backend(): + edges = [] + # POOR P (ids 0..47): many k=1 placements, few k=2, one k=3. + _ladder(edges, 16, 16, [0, 1, 2, 3, 4, 8], 0, 16, 32) + # GOOD G (ids 100..125): hosts k=2, never k=3; enumerated last. + _ladder(edges, 12, 12, [0, 4], 100, 112, 124) + g = rustworkx.PyDiGraph() + for i in range(126): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _Props: + """G is pristine; P is noisy — so any G layout dominates any P layout.""" + def readout_error(self, q): + return 0.001 if q in GOOD else 0.05 + + def gate_error(self, name, edge): + u, v = edge + return 0.001 if (u in GOOD and v in GOOD) else 0.05 + + +def _run(): + return sweep_ancilla_layouts(NORB, _make_backend(), _Props(), + min_bridges=1, top_n=50, mapping_cap=CAP) + + +def _in_good(e): + return set(e['alpha']) | set(e['beta']) | set(e['ancillas']) <= GOOD + + +def _best_good(res, k): + goods = [e for e in res['strata'].get(k, []) if _in_good(e)] + return max(goods, key=lambda e: e['product_score'], default=None) + + +# ── the invariant: best-per-k is monotone non-decreasing as k decreases ───── + +def test_best_per_k_is_monotone_non_decreasing(): + res = _run() + ks = sorted(res['strata'], reverse=True) # high k → low k + bests = [max(e['product_score'] for e in res['strata'][k]) for k in ks] + # k_max region is poor; the good region only appears at k<=2, so the + # series must climb (or hold) as k drops. Never fall. + for hi, lo in zip(bests, bests[1:]): + assert lo >= hi - 1e-9, f"best-per-k fell: {bests} for k={ks}" + # And concretely: the k_max stratum is stuck in the poor region. + assert not _in_good(max(res['strata'][3], key=lambda e: e['product_score'])) + + +# ── the cascade delivered G's k=1 prefix that no direct k=1 search could ──── + +def test_cascade_delivers_prefix_a_truncated_direct_search_missed(): + res = _run() + # The k'=1 DIRECT search hit the cap inside the poor region. + assert res['per_stratum'][1]['truncated'] is True + + k2 = _best_good(res, 2) + k1 = _best_good(res, 1) + assert k2 is not None, "k'=2 direct must have found the good region" + assert k1 is not None, "the good k=1 prefix must be present" + + # It arrived by cascade (prefix-derived), not a direct VF2 hit. + assert k1['source'] == 'derived' + # It IS the prefix of the k=2 winner: same chains, ancillas truncated. + assert k1['alpha'] == k2['alpha'] + assert k1['beta'] == k2['beta'] + assert k1['ancillas'] == k2['ancillas'][:len(k1['ancillas'])] + + +def test_prefix_child_scores_at_least_its_direct_parent(): + res = _run() + k2, k1 = _best_good(res, 2), _best_good(res, 1) + # The user's live proof: 67.8% child from a 67.2% parent — dropping one + # bridge's error factors can only raise the product. + assert k1['product_score'] >= k2['product_score'] - 1e-12 + + +# ── K3: the actual cap is surfaced for an honest truncation banner ────────── + +def test_result_exposes_mapping_cap_for_the_banner(): + res = _run() + assert res['mapping_cap'] == CAP + # per-stratum truncation flags say WHICH strata hit it (k=1 did, k=2 didn't). + assert res['per_stratum'][1]['truncated'] is True + assert res['per_stratum'][2]['truncated'] is False From c489f57c0f67ca3ffca401dac5993183a485d175 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 15:46:44 -0400 Subject: [PATCH 12/66] Cascade derivation + top-N field --- pyproject.toml | 2 +- qpu_mapper/ui/builder.py | 11 ++++++++- qpu_mapper/ui/lucj_panel.py | 18 ++++++++++---- tests/test_scan_ui.py | 3 +++ tests/test_sweep_ui.py | 47 ++++++++++++++++++++++++++++++++++++- 5 files changed, 74 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 3d39933..3030ef7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ description = "Interactive, noise-aware QPU layout mapper for Jupyter Lab" readme = "README.md" requires-python = ">=3.10" authors = [ - { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com" } + { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com" }, { name = "Milana Bazayeva", email = "m.bazayeva@gmail.com" }, ] keywords = ["quantum", "qiskit", "qpu", "layout", "visualization"] diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index c9f21cd..f96c6c9 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -304,7 +304,7 @@ def _run_pipeline(self): _lucj_ctx = _NS( state=state, out=self.out, W=W, lucj_norb_slider=self.lucj_norb_slider, lucj_ancilla_dd=self.lucj_ancilla_dd, - lucj_min_ancilla=self.lucj_min_ancilla, + lucj_min_ancilla=self.lucj_min_ancilla, lucj_top_n=self.lucj_top_n, lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, @@ -1224,6 +1224,14 @@ def _build_auto_lucj_widgets(self, W): style={'description_width': '110px'}, tooltip='Sweep all counts from max down to this floor ' '(0 = auto)') + # (K4) How many candidates to keep/show per ancilla count. Wired to the + # sweep's top_n through _sweep_kwargs_from_ui, so the scan inherits it. + self.lucj_top_n = BoundedIntText( + value=3, min=1, max=25, + description='Show top:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='candidates shown per ancilla count') self.lucj_chk_score = Checkbox( value=True, description='Score layouts (pick lowest error)', @@ -1698,6 +1706,7 @@ def _build_auto_lucj_view(self): self.lucj_norb_slider, self.lucj_ancilla_dd, self.lucj_min_ancilla, + self.lucj_top_n, self.lucj_chk_score, self.chk_deep_search, self.chk_stability_filter, diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index c18ed23..49fac62 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -102,6 +102,7 @@ def setup_lucj_callbacks(ctx): lucj_norb_slider = ctx.lucj_norb_slider lucj_ancilla_dd = ctx.lucj_ancilla_dd lucj_min_ancilla = ctx.lucj_min_ancilla + lucj_top_n = ctx.lucj_top_n lucj_chk_score = ctx.lucj_chk_score chk_deep_search = ctx.chk_deep_search btn_lucj_run = ctx.btn_lucj_run @@ -307,9 +308,10 @@ def _sweep_kwargs_from_ui(): two can never diverge again (the tonight bug).""" min_val = lucj_min_ancilla.value min_bridges = None if (min_val is None or min_val <= 0) else min_val + top_val = lucj_top_n.value return { 'min_bridges': min_bridges, - 'top_n': 3, + 'top_n': top_val if (top_val and top_val >= 1) else 3, 'hybrid': chk_deep_search.value, } @@ -424,13 +426,21 @@ def _generate_sweep(norb): _seed_layout_dropdown(flat, dd_opts) - # Truncation banner (U5): visible only when the VF2 cap was hit. + # Truncation banner (U5/K3): visible only when the VF2 cap was hit. + # Name the REAL cap (mapping_cap) and WHICH strata truncated — not + # k_max's n_raw_embeddings, which is an embedding count, not the cap. if res['vf2_truncated']: + trunc_ks = sorted((k for k, m in res.get('per_stratum', {}).items() + if m.get('truncated')), reverse=True) + ks_txt = (', '.join(f"k={k}" for k in trunc_ks) + if trunc_ks else "one or more strata") + cap = res.get('mapping_cap') + cap_txt = f"{cap:,}" if isinstance(cap, int) else "the" lbl_lucj_trunc.value = ( f"
⚠️ Enumeration capped at " - f"{esc(str(res['n_raw_embeddings']))} mappings — ranking may " + f"margin:3px 0;'>⚠️ direct search truncated at " + f"{esc(cap_txt)} mappings for {esc(ks_txt)} — ranking may " f"be non-exhaustive.
") else: lbl_lucj_trunc.value = "" diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index 48abb8f..090bff1 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -315,6 +315,7 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.chk_deep_search.value = False # a non-default value b.lucj_min_ancilla.value = 2 + b.lucj_top_n.value = 7 # (K4) non-default top_n b.btn_lucj_run.click() # local sweep local_kw = calls[-1] @@ -325,6 +326,8 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): keys = ('min_bridges', 'top_n', 'hybrid') assert {k: local_kw.get(k) for k in keys} == {k: scan_kw.get(k) for k in keys} assert scan_kw['hybrid'] is False # honored, not the engine default + # (K4) the Show-top field reaches BOTH paths — parity by construction. + assert local_kw['top_n'] == 7 and scan_kw['top_n'] == 7 # ── P2: active backend skipped-with-reference (never re-searched) ─────────── diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index 3a7c8a3..a8d8f54 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -73,6 +73,13 @@ def entry(anc, prod, add, src): 'k_max_effective': 3, 'min_bridges': 1, 'vf2_truncated': vf2_truncated, 'n_raw_embeddings': 214, 'n_candidates_scored': 1891, + # (K3) real engine metadata: which strata hit the cap, and the cap. + 'per_stratum': { + 3: {'n_direct': 5, 'n_derived': 0, 'truncated': vf2_truncated}, + 2: {'n_direct': 0, 'n_derived': 5, 'truncated': False}, + 1: {'n_direct': 0, 'n_derived': 5, 'truncated': False}, + }, + 'mapping_cap': 2000, } @@ -117,6 +124,42 @@ def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): assert [opt[1] for opt in b.dd_lucj_layout.options] == [0, 1, 2] +# ── K4: the "Show top" field controls entries-per-stratum in the dropdown ─── + +def _fake_sweep_topn(*a, **k): + """Echo the requested top_n: k_max=3, each stratum gets top_n entries.""" + n = k['top_n'] + + def entry(kk, rank): + anc = list(range(4, 4 + kk)) + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': anc, 'bridge_slots': tuple(range(0, 4 * kk, 4)), + 'product_score': 0.3, 'additive_score': 0.5, 'lqs_circuit': 0.3, + 'rank_in_stratum': rank, 'source': 'derived'} + return { + 'strata': {kk: [entry(kk, r + 1) for r in range(n)] + for kk in (3, 2, 1)}, + 'k_max_effective': 3, 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 50, 'n_candidates_scored': 90, + 'per_stratum': {kk: {'n_direct': 0, 'n_derived': n, 'truncated': False} + for kk in (3, 2, 1)}, + 'mapping_cap': 2000, + } + + +def test_top_n_field_controls_dropdown_entries(builder, monkeypatch): + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + _fake_sweep_topn) + b = builder + b.lucj_top_n.value = 7 # Show top = 7 + b.btn_lucj_run.click() + + labels = _labels(b.dd_lucj_layout) + for kk in (3, 2, 1): + assert sum(lbl.startswith(f"k={kk} · ") for lbl in labels) == 7 + assert len(labels) == 21 # 3 strata × 7 + + # ── t2: legacy mode → single-search path, sweep NOT called ────────────────── def test_legacy_mode_skips_sweep(builder, monkeypatch): @@ -174,7 +217,9 @@ def test_truncation_banner(builder, monkeypatch): lambda *a, **k: _fake_sweep_result(vf2_truncated=True)) b = builder b.btn_lucj_run.click() - assert "capped at 214 mappings" in b.lbl_lucj_trunc.value + # (K3) names the REAL cap and the truncated stratum — not n_raw_embeddings. + assert "truncated at 2,000 mappings for k=3" in b.lbl_lucj_trunc.value + assert "214" not in b.lbl_lucj_trunc.value # old embedding-count gone assert b.lbl_lucj_trunc.value != "" # False → hidden (empty). From edf410333f838f0ceaf5b72ef5826520204fa94d Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 20:34:30 -0400 Subject: [PATCH 13/66] Anchor all scoring to the selected calibration date --- qpu_mapper/ancilla_sweep.py | 164 ++++++++++++++++++---- qpu_mapper/stability_filter.py | 8 +- qpu_mapper/ui/builder.py | 11 ++ qpu_mapper/ui/lucj_panel.py | 72 ++++++++-- tests/test_ancilla_sweep.py | 33 +++-- tests/test_cascade.py | 111 ++++++++++++++- tests/test_scan_ui.py | 6 +- tests/test_shuffle_search.py | 132 ++++++++++++++++++ tests/test_temporal_anchoring.py | 224 +++++++++++++++++++++++++++++++ 9 files changed, 706 insertions(+), 55 deletions(-) create mode 100644 tests/test_shuffle_search.py create mode 100644 tests/test_temporal_anchoring.py diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index 13252dc..8889f46 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -80,9 +80,12 @@ suitable for ranking, not absolute fidelity prediction. """ +import hashlib import logging +import random import numpy as np +import rustworkx from .auto_lucj import ( _collect_vf2_mappings, @@ -101,6 +104,21 @@ # excluded from the top ranks. _UNCALIBRATED_PENALTY = 1.0 +# Sentinel for the `shuffle_seed` keyword: AUTO derives a deterministic +# per-stratum seed from (backend_name, norb, k). None disables the shuffle +# (natural node-index order == pre-shuffle behaviour, byte-compatible). An +# explicit int is combined with k so strata still sample differently yet +# reproducibly. See S1 in the SHUFFLED SEARCH ORDER change. +_AUTO_SHUFFLE = object() + + +def _stable_seed(*parts) -> int: + """Process-independent 32-bit seed from the parts (Python's built-in + hash() is salted per run and unusable here). Deterministic across runs + and machines so a shuffled search is reproducible.""" + digest = hashlib.md5('|'.join(str(p) for p in parts).encode()).hexdigest() + return int(digest[:8], 16) + def _safe_readout(props, qubit): """Readout error for `qubit`, NaN/None -> penalty (mirrors lightweight).""" @@ -129,7 +147,8 @@ def _safe_gate_error(props, gate_name, u, v): def sweep_ancilla_layouts(norb, backend, props, *, min_bridges=None, top_n=3, mapping_cap=None, exclude_qubits=None, - circuit_score_fn=None, hybrid=True) -> dict: + circuit_score_fn=None, hybrid=True, + shuffle_seed=_AUTO_SHUFFLE) -> dict: """One-shot ancilla sweep: VF2 at the geometric max bridge count, then derive every lower-k variant by bridge subtraction, score, and return the top_n candidates per ancilla count. @@ -161,6 +180,17 @@ def sweep_ancilla_layouts(norb, backend, props, *, leaves ``lqs_circuit=None`` and never aborts the sweep. When ``None`` (default) the returned dict is byte-compatible with the pre-A2 shape — no ``lqs_circuit`` key is added. + shuffle_seed: controls the node-INSERTION order of the graph handed to + each VF2 call, so a truncated search samples the whole chip instead + of one geographic corner (node-index prefix). ``AUTO`` (default) + derives a deterministic per-stratum seed from + ``(backend_name, norb, k)`` — reproducible across runs, and each + stratum samples a different region. ``None`` keeps the natural + order (byte-for-byte identical to the pre-shuffle sweep — the + pinned compatibility path). An explicit ``int`` is combined with + ``k`` (still per-stratum, still reproducible; for tests). Physical + qubit ids ride in node data and are recovered order-independently + via ``_key_to_phys`` — no relabel leakage. hybrid: when True (default), each stratum k' < k_max_effective is the UNION of (a) the derived prefix candidates AND (b) a DIRECT VF2 at the k' template on the same (possibly pruned) graph. Derivation @@ -179,9 +209,10 @@ def sweep_ancilla_layouts(norb, backend, props, *, 'n_candidates_scored': int, # total variants scored (pre-dedupe) 'excluded_qubits': [...], # sorted list actually pruned (empty # when exclude_qubits is None) - 'per_stratum': {k: {'n_direct', 'n_derived', 'truncated'}}, + 'per_stratum': {k: {'n_direct', 'n_derived', 'truncated', 'shuffled'}}, # per-k provenance; vf2_truncated is - # any(per-stratum truncated) + # any(per-stratum truncated); + # 'shuffled' = search order permuted } entry = { 'layout': [...], # chain qubits (alpha+beta) @@ -214,6 +245,37 @@ def _key_to_phys(k): def _key_to_phys(k): return k + # ---- 1b. Per-stratum shuffled search graph (S1) ----------------------- + # The template (WHAT to search for) is always built on the natural + # `search_graph`, so k_max_effective and every k' template are stable and + # seed-independent. Only the TARGET graph handed to VF2 is permuted, which + # merely changes the ORDER embeddings are yielded — so a cap truncates a + # chip-wide SAMPLE, not one low-index corner. Node data carries the + # physical id; recovery is order-independent. + backend_name = str(getattr(backend, 'name', '') or '') + + def _seed_for(k): + if shuffle_seed is None: + return None + if shuffle_seed is _AUTO_SHUFFLE: + return _stable_seed(backend_name, norb, k) + return _stable_seed(shuffle_seed, k) + + def _search_for(k): + """(graph, key_to_phys, shuffled) for the VF2 call at stratum k.""" + seed = _seed_for(k) + if seed is None: + return search_graph, _key_to_phys, False + order = list(search_graph.node_indices()) + random.Random(seed).shuffle(order) + g = rustworkx.PyGraph() + old_to_new = {} + for old in order: + old_to_new[old] = g.add_node(_key_to_phys(old)) # data = phys id + for u, v in search_graph.edge_list(): + g.add_edge(old_to_new[u], old_to_new[v], None) + return g, (lambda key: g[key]), True + k_max = (norb + 3) // 4 # ceil(norb / 4): the geometric bridge ceiling template, k_max_effective = create_lucj_zigzag_layout( num_orbitals=norb, @@ -238,7 +300,8 @@ def _key_to_phys(k): # ---- 3. Collect VF2 embeddings, detect truncation --------------------- cap = mapping_cap if mapping_cap is not None else _MAX_RAW_VF2_MAPPINGS - mappings = _collect_vf2_mappings(search_graph, template, cap=cap) + kmax_graph, kmax_key_to_phys, kmax_shuffled = _search_for(k_max_effective) + mappings = _collect_vf2_mappings(kmax_graph, template, cap=cap) # The helper only *logs* truncation; detect it by the cap being reached. vf2_truncated = len(mappings) >= cap if vf2_truncated: @@ -250,7 +313,7 @@ def _key_to_phys(k): for mapping in mappings: layout = [None] * expected_size for key, value in mapping.items(): - layout[value] = _key_to_phys(key) + layout[value] = kmax_key_to_phys(key) if any(v is None for v in layout): _log.debug("Ancilla sweep: skipping incomplete VF2 mapping") continue @@ -289,7 +352,8 @@ def _edge_e(a, b): # strata_pool[k] : dict keyed by (frozenset(chain), frozenset(ancilla)) # -> entry, giving per-stratum dedupe for free. strata_pool = {k: {} for k in range(k_max_effective, min_bridges - 1, -1)} - per_stratum = {k: {'n_direct': 0, 'n_derived': 0, 'truncated': False} + per_stratum = {k: {'n_direct': 0, 'n_derived': 0, 'truncated': False, + 'shuffled': False} for k in range(k_max_effective, min_bridges - 1, -1)} n_candidates_scored = 0 @@ -367,6 +431,7 @@ def _add_variant(edata, k, source): # 6a. k_max embeddings → the k_max stratum (direct) + derived prefixes. per_stratum[k_max_effective]['truncated'] = vf2_truncated + per_stratum[k_max_effective]['shuffled'] = kmax_shuffled for layout in layouts: edata = _embedding_data(layout, k_max_effective) for k in range(k_max_effective, min_bridges - 1, -1): @@ -389,14 +454,16 @@ def _add_variant(edata, k, source): _log.debug("Hybrid: k=%d template returned %d bridges; " "skipping direct pass", k, nb_k) continue - maps_k = _collect_vf2_mappings(search_graph, tmpl_k, cap=cap) + k_graph, k_key_to_phys, k_shuffled = _search_for(k) + per_stratum[k]['shuffled'] = k_shuffled + maps_k = _collect_vf2_mappings(k_graph, tmpl_k, cap=cap) if len(maps_k) >= cap: per_stratum[k]['truncated'] = True exp_k = 2 * norb + nb_k for mapping in maps_k: lay = [None] * exp_k for key, value in mapping.items(): - lay[value] = _key_to_phys(key) + lay[value] = k_key_to_phys(key) if any(v is None for v in lay): continue edata = _embedding_data(lay, nb_k) @@ -415,30 +482,73 @@ def _add_variant(edata, k, source): # Aggregate truncation for the existing banner (k_max OR any direct pass). vf2_truncated = any(m['truncated'] for m in per_stratum.values()) - # ---- 7. Rank each stratum by product_score desc, slice top_n --------- - # product_score is the internal PRE-RANK (cross-stratum-comparable, cheap). - # Circuit-level scoring (A2) runs ONLY on the sliced survivors — top_n per - # stratum — so the expensive state-bound scorer is called O(top_n * strata) - # times, not per raw candidate. + # ---- 7. Slice each stratum by the DISPLAYED metric (W1) --------------- + # product_score (template scale) is the cheap PRE-FILTER for the pool, but + # the final slice must be chosen by the metric the UI shows (lqs_circuit). + # The two scales diverge, so slicing to top_n by product_score BEFORE + # circuit-scoring can drop the true circuit-best below the line unseen — + # the live "3->49.3% . 2->40.8%" monotonicity violation. + # + # Fix: circuit-score a WIDENED window = the top W by product_score + # (W = max(top_n*5, 25)) PLUS, guaranteed regardless of rank, the + # prefix-child of every higher stratum's already-selected winner (the + # monotonicity anchors — the cascade already generated them, so they live + # in this pool). Then rank the scored window by lqs_circuit (None sinks) + # and slice to top_n. With no circuit scorer the pre-A2 product-sliced + # shape is preserved byte-for-byte. strata = {} + # higher_winners: (chain_fs, ancillas) of every selected entry in a higher + # stratum, so stratum k can pull in each one's k-prefix child as an anchor. + higher_winners = [] for k in range(k_max_effective, min_bridges - 1, -1): - entries = sorted(strata_pool[k].values(), - key=lambda e: e['product_score'], reverse=True) - entries = entries[:top_n] + pool = strata_pool[k] + by_product = sorted(pool.items(), + key=lambda kv: kv[1]['product_score'], reverse=True) + + if circuit_score_fn is None: + # Byte-compatible pre-A2 path: product slice, no lqs_circuit. + entries = [e for _, e in by_product[:top_n]] + for rank, entry in enumerate(entries, start=1): + entry['rank_in_stratum'] = rank + strata[k] = entries + continue + + W = max(top_n * 5, 25) + window_keys = [key for key, _ in by_product[:W]] + seen = set(window_keys) + # Guarantee anchors: the k-prefix child of each higher winner. + for chain_fs, anc_full in higher_winners: + if len(anc_full) < k: + continue + akey = (chain_fs, frozenset(anc_full[:k])) + if akey in pool and akey not in seen: + seen.add(akey) + window_keys.append(akey) + window = [pool[key] for key in window_keys] + + for entry in window: + try: + entry['lqs_circuit'] = circuit_score_fn(entry) + except Exception as exc: + # A scoring error must never abort the sweep. + _log.warning("Circuit scoring failed for a candidate " + "(k=%d): %s", k, exc) + entry['lqs_circuit'] = None + # Rank by the DISPLAYED metric; None sinks; product_score breaks ties. + window.sort( + key=lambda e: (e['lqs_circuit'] is not None, + e['lqs_circuit'] if e['lqs_circuit'] is not None + else 0.0, + e['product_score']), + reverse=True) + entries = window[:top_n] for rank, entry in enumerate(entries, start=1): entry['rank_in_stratum'] = rank - if circuit_score_fn is not None: - for entry in entries: - try: - entry['lqs_circuit'] = circuit_score_fn(entry) - except Exception as exc: - # A scoring error must never abort the sweep. - _log.warning("Circuit scoring failed for a candidate " - "(k=%d): %s", k, exc) - entry['lqs_circuit'] = None strata[k] = entries - _log.debug("Ancilla sweep stratum k=%d: %d candidates (top_n=%d)", - k, len(entries), top_n) + higher_winners.extend( + (frozenset(e['layout']), tuple(e['ancillas'])) for e in entries) + _log.debug("Ancilla sweep stratum k=%d: scored %d, kept top %d", + k, len(window), len(entries)) return { 'strata': strata, diff --git a/qpu_mapper/stability_filter.py b/qpu_mapper/stability_filter.py index 95a263b..167a4e1 100644 --- a/qpu_mapper/stability_filter.py +++ b/qpu_mapper/stability_filter.py @@ -98,7 +98,8 @@ def select_excluded(volatility, *, threshold): def sweep_with_stability(norb, backend, props, history, *, window_days=14, threshold=_DEFAULT_THRESHOLD, - min_bridges=None, top_n=3, mapping_cap=None): + min_bridges=None, top_n=3, mapping_cap=None, + today=None): """Stability-filtered ancilla sweep with an automatic relax valve. 1. Score volatility over the windowed history and build the excluded set. @@ -123,7 +124,10 @@ def _plain(): if not history: return _plain() - volatility = compute_qubit_volatility(history, window_days) + # (F2) Anchor the window to the SELECTED date when one is active — dates + # after `today` are ignored, so the window is [today-window_days, today]. + # today=None keeps the now-anchored latest-window behaviour (live mode). + volatility = compute_qubit_volatility(history, window_days, today=today) if not volatility: return _plain() diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index f96c6c9..eee8d82 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -305,6 +305,7 @@ def _run_pipeline(self): state=state, out=self.out, W=W, lucj_norb_slider=self.lucj_norb_slider, lucj_ancilla_dd=self.lucj_ancilla_dd, lucj_min_ancilla=self.lucj_min_ancilla, lucj_top_n=self.lucj_top_n, + lucj_search_cap=self.lucj_search_cap, lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, @@ -1232,6 +1233,15 @@ def _build_auto_lucj_widgets(self, W): layout=Layout(width='220px'), style={'description_width': '110px'}, tooltip='candidates shown per ancilla count') + # (S4) Advanced: the VF2 mapping cap. Raise to trade time for + # exhaustiveness (default matches auto_lucj._MAX_RAW_VF2_MAPPINGS). + self.lucj_search_cap = BoundedIntText( + value=2000, min=100, max=20000, step=500, + description='Search cap:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='max VF2 mappings enumerated per search — higher = more ' + 'exhaustive, slower') self.lucj_chk_score = Checkbox( value=True, description='Score layouts (pick lowest error)', @@ -1707,6 +1717,7 @@ def _build_auto_lucj_view(self): self.lucj_ancilla_dd, self.lucj_min_ancilla, self.lucj_top_n, + self.lucj_search_cap, self.lucj_chk_score, self.chk_deep_search, self.chk_stability_filter, diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 49fac62..c739393 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -103,6 +103,7 @@ def setup_lucj_callbacks(ctx): lucj_ancilla_dd = ctx.lucj_ancilla_dd lucj_min_ancilla = ctx.lucj_min_ancilla lucj_top_n = ctx.lucj_top_n + lucj_search_cap = ctx.lucj_search_cap lucj_chk_score = ctx.lucj_chk_score chk_deep_search = ctx.chk_deep_search btn_lucj_run = ctx.btn_lucj_run @@ -301,6 +302,35 @@ def _annotate_circuit_lqs(res): except Exception: e['lqs_circuit'] = None + # ── Temporal anchoring: one epoch per search ───────────────────── + def _selected_date_anchor(): + """(F2) The selected calibration's date 'YYYY-MM-DD' when a PAST date + is active, else None (live). Used to anchor the stability window and + the epoch-mixing header note to the user's chosen date.""" + if getattr(state, 'time_mode', 'live') == 'live': + return None + ts = getattr(state, 'point_timestamp', None) + return ts[:10] if isinstance(ts, str) and len(ts) >= 10 else None + + def _local_scoring_props(): + """(F1) Pre-rank on the SAME epoch as the C1 circuit-score — the + selected date's arrays — so product_score and lqs_circuit never mix + epochs inside one search. Reuses the scan's CachedPropsShim adapter. + Falls back to live initial_props if the arrays aren't loaded / mis-shape + (never break the sweep for a scoring-input choice).""" + from ..props_shim import CachedPropsShim + qp = getattr(state, 'qubit_props_data', None) + gp = getattr(state, 'gate_props_data', None) + edges = getattr(state, 'edges_list', None) + if not qp or not gp or edges is None or 'readout_error' not in qp: + return state.initial_props + key = 'cz_error' if 'cz_error' in gp else next(iter(gp)) + n = len(state.qubit_ids) if getattr(state, 'qubit_ids', None) else None + try: + return CachedPropsShim(qp, gp, list(edges), gate_key=key, n_qubits=n) + except Exception: + return state.initial_props + # ── P1: SINGLE SOURCE of sweep params — local AND scan read this ── def _sweep_kwargs_from_ui(): """The one place sweep parameters are derived from the UI. Both the @@ -309,10 +339,12 @@ def _sweep_kwargs_from_ui(): min_val = lucj_min_ancilla.value min_bridges = None if (min_val is None or min_val <= 0) else min_val top_val = lucj_top_n.value + cap_val = lucj_search_cap.value return { 'min_bridges': min_bridges, 'top_n': top_val if (top_val and top_val >= 1) else 3, 'hybrid': chk_deep_search.value, + 'mapping_cap': cap_val if (cap_val and cap_val >= 1) else None, } # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the @@ -379,22 +411,26 @@ def _generate_sweep(norb): # P1: exact same params the scan uses (min_bridges / top_n / hybrid). kwargs = _sweep_kwargs_from_ui() + # F1: pre-rank on the same epoch as the circuit-score (selected date). + scoring_props = _local_scoring_props() + anchor = _selected_date_anchor() # F2: window/header anchor # V2: opt-in stability filter (drop-in superset of the plain sweep). history = getattr(state, 'cal_history', None) if _stability_filter_active() and history: from ..stability_filter import sweep_with_stability res = sweep_with_stability( - norb, state.active_backend, state.initial_props, history, + norb, state.active_backend, scoring_props, history, window_days=rb_stability_window.value, threshold=ft_stability_threshold.value, - min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n']) - _render_stability_banner(res.get('stability'), norb) + min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], + mapping_cap=kwargs['mapping_cap'], today=anchor) + _render_stability_banner(res.get('stability'), norb, anchor=anchor) # The frozen stability engine can't take circuit_score_fn — fill # circuit-level LQS on its survivors here (A2). _annotate_circuit_lqs(res) else: res = sweep_ancilla_layouts( - norb, state.active_backend, state.initial_props, + norb, state.active_backend, scoring_props, circuit_score_fn=_circuit_score, # A2: aligned circuit LQS **kwargs) # P1 single source (incl. hybrid) if _stability_filter_active(): @@ -540,8 +576,14 @@ def _stability_filter_active(): return bool(chk_stability_filter.value and not chk_stability_filter.disabled) - def _render_stability_banner(stab, norb): - """Render res['stability'] (V2): filtered / relaxed / unavailable.""" + def _render_stability_banner(stab, norb, anchor=None): + """Render res['stability'] (V2): filtered / relaxed / unavailable. + `anchor` (a 'YYYY-MM-DD' selected date) names the window's upper bound + when a past date is active (F2).""" + # F2: "14d before " when a past date anchors the window, else "14d". + def _window_txt(): + wd = esc(str(stab.get('window_days'))) + return (f"{wd}d before {esc(anchor)}" if anchor else f"{wd}d") if stab is None or not stab.get('available', False): lbl_lucj_stability.value = ( "
" @@ -562,7 +604,7 @@ def _render_stability_banner(stab, norb): f"
🛡 filtered {esc(str(n))} volatile qubits " - f"(window {esc(str(stab.get('window_days')))}d)
") + f"(window {_window_txt()})
") def _cached_history_for(backend_name): """Assemble a per-backend history dict from the DISK CACHE ONLY (no @@ -663,12 +705,13 @@ def _scan_backends(eligible, norb, get_backend, get_props, use_filter): hist = _cached_history_for(name) if use_filter else None if hist: # sweep_with_stability (frozen) can't take hybrid; it uses - # the engine default. Forward the shared min_bridges/top_n. + # the engine default. Forward min_bridges/top_n/mapping_cap. res = sweep_with_stability( norb, backend, props, hist, window_days=window, threshold=threshold, min_bridges=kwargs['min_bridges'], - top_n=kwargs['top_n']) + top_n=kwargs['top_n'], + mapping_cap=kwargs['mapping_cap']) stab = res.get('stability', {'available': False}) else: res = sweep_ancilla_layouts(norb, backend, props, **kwargs) @@ -871,6 +914,17 @@ def _render_results(scan_result): f"{vcell}") children = [HTML(head + "".join(body) + "")] + # F3: when a PAST date is active locally, the local backend was scored + # on that date but remote backends are scored LIVE — say so, no silent + # mixing. + _anchor = _selected_date_anchor() + if _anchor: + children.insert(0, HTML( + f"
⏱ local backend scored on " + f"{esc(_anchor)}; remote backends on live calibrations
")) + # Per-QPU stratified dropdowns (same label format as single-circuit). for r in results: sweep = r.get('sweep') diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index 1a921be..a982b2b 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -211,9 +211,11 @@ def test_prefix_legacy_equivalence(backend, props): # ── A2: circuit_score_fn on the sliced survivors only ────────────────────── -def test_circuit_score_fn_on_sliced_only(backend, props): - """(A2) The injected scorer runs ONCE per sliced entry (top_n per - stratum), and its value lands on entry['lqs_circuit'].""" +def test_circuit_score_fn_scores_widened_window(backend, props): + """(W1) The scorer runs on a WIDENED window — top W by product_score plus + the monotonicity anchors — not merely the sliced top_n, so the displayed + metric's best can't hide below the product_score line. Every survivor still + carries lqs_circuit, and the window is bounded (not the whole raw pool).""" calls = [] def scorer(entry): @@ -223,31 +225,34 @@ def scorer(entry): res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3, circuit_score_fn=scorer) total = sum(len(v) for v in res['strata'].values()) - assert len(calls) == total # exactly once per survivor - assert total <= 3 * len(res['strata']) # cheap-slice property + assert len(calls) >= total # window is >= the slice + W = max(3 * 5, 25) + assert len(calls) <= (W + total) * len(res['strata']) # bounded window for entries in res['strata'].values(): for e in entries: assert e['lqs_circuit'] == 0.5 -def test_circuit_score_error_keeps_entry_none(backend, props): - """(A2) A scorer that raises on one candidate leaves it lqs_circuit=None; - the sweep still completes and other entries are scored.""" - calls = [] +def test_circuit_score_error_sinks_below_slice_not_aborts(backend, props): + """(W1) A scorer that raises leaves that candidate lqs_circuit=None; None + sinks below the displayed-metric slice, so the sweep completes and its + survivors are exactly the successfully-scored candidates.""" + raised = [] def scorer(entry): - calls.append(1) - if len(calls) == 1: + if not raised: + raised.append(entry) raise ValueError("boom") return 0.5 res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3, circuit_score_fn=scorer) + assert res['strata'] # completed, no abort + assert len(raised) == 1 # the error path ran vals = [e['lqs_circuit'] for entries in res['strata'].values() for e in entries] - assert vals.count(None) == 1 # the failed one - assert 0.5 in vals # the rest scored - assert res['strata'] # sweep completed + assert 0.5 in vals + assert all(v == 0.5 for v in vals) # the errored one sank out def test_no_circuit_score_fn_is_byte_compatible(backend, props): diff --git a/tests/test_cascade.py b/tests/test_cascade.py index 08a3805..047a6ae 100644 --- a/tests/test_cascade.py +++ b/tests/test_cascade.py @@ -69,8 +69,12 @@ def gate_error(self, name, edge): def _run(): + # shuffle_seed=None pins the NATURAL node order this fixture's truncation + # story depends on (poor region enumerated first). The cascade is what's + # under test here; the shuffle has its own suite (test_shuffle_search.py). return sweep_ancilla_layouts(NORB, _make_backend(), _Props(), - min_bridges=1, top_n=50, mapping_cap=CAP) + min_bridges=1, top_n=50, mapping_cap=CAP, + shuffle_seed=None) def _in_good(e): @@ -132,3 +136,108 @@ def test_result_exposes_mapping_cap_for_the_banner(): # per-stratum truncation flags say WHICH strata hit it (k=1 did, k=2 didn't). assert res['per_stratum'][1]['truncated'] is True assert res['per_stratum'][2]['truncated'] is False + + +# ── W2: monotonicity on the DISPLAYED metric (product ≠ circuit scale) ─────── +# +# The live bug: strata are sliced to top_n by product_score BEFORE the UI's +# lqs_circuit is computed. Where the scales diverge, the true circuit-best +# falls below the product line unseen and the status line reads e.g. +# "3→49.3% · 2→40.8%" — non-monotone on the DISPLAYED metric. +# +# Fixture with the scales deliberately opposed: +# * region D (low ids): width-16 ladder, bridges cols 0..7 → k=2 only, MANY +# decoys, props error 0.001 → HIGH product_score (product's favourites). +# * region G (high ids): width-12 ladder, bridges cols 0,4,8 → hosts k=3, +# props error 0.02 → LOW product_score, but the canned circuit scorer rates +# G's qubits ~1.0 and D's ~0.5 → G is the DISPLAYED-metric winner. +# The k=3 winner is in G; its k=2 prefix (the monotonicity anchor) has product +# BELOW every D decoy, so product-only slicing drops it — W1 must keep it in the +# scoring window and surface it once ranked by lqs_circuit. + +_WG = set(range(100, 127)) # region G ids + + +def _w2_ladder(edges, w_top, w_bot, brg_cols, bt, bb, bg): + t = [bt + j for j in range(w_top)] + b = [bb + j for j in range(w_bot)] + for j in range(w_top - 1): + edges.append((t[j], t[j + 1])) + for j in range(w_bot - 1): + edges.append((b[j], b[j + 1])) + for i, c in enumerate(brg_cols): + edges.append((t[c], bg + i)) + edges.append((bg + i, b[c])) + + +def _w2_backend(): + edges = [] + _w2_ladder(edges, 16, 16, list(range(8)), 0, 16, 32) # D: k=2 decoys + _w2_ladder(edges, 12, 12, [0, 4, 8], 100, 112, 124) # G: hosts k=3 + g = rustworkx.PyDiGraph() + for i in range(127): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x'], name='chip') + + +class _W2Props: # product_score PRE-FILTER favours D + def readout_error(self, q): + return 0.02 if q in _WG else 0.001 + + def gate_error(self, name, edge): + u, v = edge + return 0.02 if (u in _WG and v in _WG) else 0.001 + + +def _w2_circuit(entry): # DISPLAYED metric favours G, fewer bridges higher + qs = entry['alpha'] + entry['beta'] + entry['ancillas'] + f = 1.0 + for q in qs: + f *= 0.999 if q in _WG else 0.5 + return f + + +def _w2_region(entry): + return 'G' if set(entry['alpha'] + entry['beta'] + entry['ancillas']) <= _WG else 'D' + + +def _w2_run(**kw): + return sweep_ancilla_layouts(NORB, _w2_backend(), _W2Props(), min_bridges=1, + top_n=3, shuffle_seed=None, **kw) + + +def test_displayed_metric_best_per_k_is_monotone(): + res = _w2_run(circuit_score_fn=_w2_circuit) + ks = sorted(res['strata'], reverse=True) + bests = [res['strata'][k][0]['lqs_circuit'] for k in ks] + for hi, lo in zip(bests, bests[1:]): + assert lo >= hi - 1e-9, f"displayed-metric best fell: {bests} for {ks}" + # Each stratum's displayed winner is region G (the circuit-good region). + for k in ks: + assert _w2_region(res['strata'][k][0]) == 'G' + + +def test_slice_contains_higher_winners_prefix_anchor(): + res = _w2_run(circuit_score_fn=_w2_circuit) + k3 = res['strata'][3][0] + assert _w2_region(k3) == 'G' + chain, anc2 = frozenset(k3['layout']), frozenset(k3['ancillas'][:2]) + # The k=3 winner's k=2 prefix survives into the k=2 slice (W1 anchor), + # and it is the displayed winner there (circuit >= its k=3 parent). + k2_top = res['strata'][2][0] + assert frozenset(k2_top['layout']) == chain + assert frozenset(k2_top['ancillas']) == anc2 + assert k2_top['lqs_circuit'] >= k3['lqs_circuit'] - 1e-9 + + +def test_product_only_slice_would_have_hidden_the_anchor(): + # The divergence is real: without the circuit scorer, product-only slicing + # fills the k=2 top_n with the low-error D decoys — the G anchor is nowhere + # in the displayed slice. This is exactly what W1 rescues. + res = _w2_run() # no circuit_score_fn + regions = [_w2_region(e) for e in res['strata'][2]] + assert regions == ['D', 'D', 'D'] + assert 'lqs_circuit' not in res['strata'][2][0] # byte-compat shape intact diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index 090bff1..e6d9257 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -316,6 +316,7 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.chk_deep_search.value = False # a non-default value b.lucj_min_ancilla.value = 2 b.lucj_top_n.value = 7 # (K4) non-default top_n + b.lucj_search_cap.value = 5000 # (S4) non-default cap b.btn_lucj_run.click() # local sweep local_kw = calls[-1] @@ -323,11 +324,12 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.btn_scan_qpus.click() # scan (per-target) scan_kw = calls[0] - keys = ('min_bridges', 'top_n', 'hybrid') + keys = ('min_bridges', 'top_n', 'hybrid', 'mapping_cap') assert {k: local_kw.get(k) for k in keys} == {k: scan_kw.get(k) for k in keys} assert scan_kw['hybrid'] is False # honored, not the engine default - # (K4) the Show-top field reaches BOTH paths — parity by construction. + # (K4/S4) Show-top and Search-cap reach BOTH paths — parity by construction. assert local_kw['top_n'] == 7 and scan_kw['top_n'] == 7 + assert local_kw['mapping_cap'] == 5000 and scan_kw['mapping_cap'] == 5000 # ── P2: active backend skipped-with-reference (never re-searched) ─────────── diff --git a/tests/test_shuffle_search.py b/tests/test_shuffle_search.py new file mode 100644 index 0000000..a53f1a5 --- /dev/null +++ b/tests/test_shuffle_search.py @@ -0,0 +1,132 @@ +"""S3 — shuffled VF2 search order kills the geographic-prefix truncation bias. + +Deterministic, offline, real VF2. Two identical blocks on one chip: + * block A (ids 0..23) — NOISY (readout/gate error 0.06) + * block B (ids 24..47) — CLEAN (error 0.0005) +Both host the norb=8 zigzag. VF2 enumerates in node-index order, so with a +tiny mapping_cap the NATURAL search truncates inside block A and never scores +a block-B layout — the best it can return is noisy. A seeded shuffle permutes +the node insertion order, samples block B within the same cap, and returns the +clean layout. Physical ids ride in node data and are recovered order- +independently, so a shuffled result still names real chip qubits. +""" +from types import SimpleNamespace + +import rustworkx + +from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts + +NORB = 8 +CAP = 2 # smaller than block A's embedding count → truncates +CLEAN = set(range(24, 48)) # block B ids +SEED = 0 # empirically samples block B (see probe) + + +def _block(base, edges): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges.append((top[j], top[j + 1])) + edges.append((bot[j], bot[j + 1])) + for j in range(8): + edges.append((top[j], brg[j])) + edges.append((brg[j], bot[j])) + + +def _backend(): + edges = [] + _block(0, edges) # A: noisy, low ids → enumerated first + _block(24, edges) # B: clean, high ids → beyond the cap in natural order + g = rustworkx.PyDiGraph() + for i in range(48): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x'], name='chip') + + +class _Props: + def readout_error(self, q): + return 0.0005 if q in CLEAN else 0.06 + + def gate_error(self, name, edge): + u, v = edge + return 0.0005 if (u in CLEAN and v in CLEAN) else 0.06 + + +def _sweep(seed): + return sweep_ancilla_layouts(NORB, _backend(), _Props(), min_bridges=1, + top_n=10, mapping_cap=CAP, shuffle_seed=seed) + + +def _best(res, k): + return max(res['strata'][k], key=lambda e: e['product_score']) + + +def _qubits(e): + return set(e['alpha']) | set(e['beta']) | set(e['ancillas']) + + +# ── t1: natural order misses the clean region; the shuffle finds it ───────── + +def test_shuffle_reaches_a_region_natural_order_truncates_past(): + nat = _sweep(None) + shuf = _sweep(SEED) + + nat_best = _best(nat, 1) + shuf_best = _best(shuf, 1) + + # Natural order is trapped in the noisy block (truncated before block B). + assert _qubits(nat_best).isdisjoint(CLEAN) + assert nat['per_stratum'][1]['shuffled'] is False + + # The shuffle samples the clean block and returns a strictly better layout. + assert _qubits(shuf_best) <= CLEAN + assert shuf['per_stratum'][1]['shuffled'] is True + assert shuf_best['product_score'] > nat_best['product_score'] + 1e-6 + + +# ── t2: seed=None is the pinned natural-order (byte-compat) path ──────────── + +def test_seed_none_is_natural_order_and_deterministic(): + a = _sweep(None) + b = _sweep(None) + # No shuffle anywhere, and the run is reproducible bit-for-bit. + assert all(not m['shuffled'] for m in a['per_stratum'].values()) + for k in a['strata']: + assert [e['product_score'] for e in a['strata'][k]] == \ + [e['product_score'] for e in b['strata'][k]] + assert [e['ancillas'] for e in a['strata'][k]] == \ + [e['ancillas'] for e in b['strata'][k]] + # And it is the NOISY solution — natural order never left block A. + assert _qubits(_best(a, 1)).isdisjoint(CLEAN) + + +# ── t3: same seed → identical results (reproducibility) ───────────────────── + +def test_same_seed_is_reproducible(): + a = _sweep(SEED) + b = _sweep(SEED) + assert list(a['strata']) == list(b['strata']) + for k in a['strata']: + ea, eb = a['strata'][k], b['strata'][k] + assert [e['product_score'] for e in ea] == [e['product_score'] for e in eb] + assert [e['layout'] for e in ea] == [e['layout'] for e in eb] + assert [e['ancillas'] for e in ea] == [e['ancillas'] for e in eb] + + +# ── t4: shuffled results still name REAL chip ids (no relabel leakage) ────── + +def test_shuffle_recovers_physical_ids(): + shuf = _sweep(SEED) + chip = set(range(48)) + for entries in shuf['strata'].values(): + for e in entries: + qs = e['alpha'] + e['beta'] + e['ancillas'] + assert all(q in chip for q in qs) # real physical ids + assert len(set(qs)) == len(qs) # no qubit reused + # chains are length norb; ancillas match the stratum's bridge count + assert len(e['alpha']) == NORB and len(e['beta']) == NORB + assert len(e['ancillas']) == len(e['bridge_slots']) diff --git a/tests/test_temporal_anchoring.py b/tests/test_temporal_anchoring.py new file mode 100644 index 0000000..e4e4501 --- /dev/null +++ b/tests/test_temporal_anchoring.py @@ -0,0 +1,224 @@ +"""Temporal-anchoring audit fixes (F1/F2/F3): the SELECTED calibration date +must govern all scoring in one search. + + * t1 — epoch consistency: when a past date is active, the sweep's pre-rank + props are built from the SAME arrays the C1 circuit-score reads (the + selected date's), not the live BackendProperties. + * t2 — window anchor: volatility windows over [date-14d, date], not + [now-14d, now]; sweep_with_stability forwards `today=`. + * t3 — the scan header names the epoch mix when a past date is active. +""" +from types import SimpleNamespace + +import numpy as np +import rustworkx + +from qpu_mapper.stability_filter import ( + compute_qubit_volatility, sweep_with_stability, +) + + +# ── t2: the volatility window anchors to the selected date (engine) ───────── + +def _divergent_history(n_qubits=48): + """30 daily snapshots. q3 spikes EARLY (07-05, inside [.. ,07-14]); q5 + spikes LATE (07-28, inside the now-anchored last-14 window). So the window + the anchor picks decides which qubit reads volatile.""" + dates = [f"2026-07-{i + 1:02d}" for i in range(30)] + hist = {} + for d in dates: + arr = [0.01] * n_qubits + if d == '2026-07-05': + arr[3] = 0.09 + if d == '2026-07-28': + arr[5] = 0.09 + hist[d] = {'qubit_props': {'readout_error': arr}, 'gate_props': {}} + return hist + + +def test_volatility_anchors_to_selected_date(): + hist = _divergent_history() + early = compute_qubit_volatility(hist, 14, today='2026-07-14') + live = compute_qubit_volatility(hist, 14, today=None) + + # Anchored to the past date: the EARLY spike (q3) is volatile, the late one + # (q5) is outside the window and flat. + assert early[3] > 0 and early[5] == 0 + # Now-anchored (default): the reverse. + assert live[5] > 0 and live[3] == 0 + + +def _two_block_backend(): + edges = [] + for base in (0, 24): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges.append((top[j], top[j + 1])) + edges.append((bot[j], bot[j + 1])) + for j in range(8): + edges.append((top[j], brg[j])) + edges.append((brg[j], bot[j])) + g = rustworkx.PyDiGraph() + for i in range(48): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x'], name='b') + + +class _Props: + def readout_error(self, q): + return 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def test_sweep_with_stability_forwards_today(): + hist = _divergent_history() + bk, pr = _two_block_backend(), _Props() + early = sweep_with_stability(8, bk, pr, hist, window_days=14, threshold=1.0, + min_bridges=1, today='2026-07-14') + live = sweep_with_stability(8, bk, pr, hist, window_days=14, threshold=1.0, + min_bridges=1, today=None) + # The anchor decides which qubit the filter prunes. + assert 3 in early['stability']['excluded_final'] + assert 3 not in live['stability']['excluded_final'] + assert 5 in live['stability']['excluded_final'] + assert 5 not in early['stability']['excluded_final'] + + +# ── UI harness for t1 / t3 ────────────────────────────────────────────────── + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _canned(): + e = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.4, + 'additive_score': 0.5, 'lqs_circuit': 0.4, 'rank_in_stratum': 1, + 'source': 'derived'} + return {'strata': {1: [e]}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 5, + 'n_candidates_scored': 5, 'excluded_qubits': [], + 'per_stratum': {1: {'n_direct': 0, 'n_derived': 1, + 'truncated': False, 'shuffled': False}}, + 'mapping_cap': 2000} + + +def _build(monkeypatch, *, past_date=None): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = SimpleNamespace(name='ibm_here') + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = ["ibm_here", "ibm_other"] + state.props_warning = None + state.initial_props = SimpleNamespace( + readout_error=lambda q: 0.99, # LIVE sentinel: deliberately wrong + gate_error=lambda n, e: 0.99) + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + # Selected-date arrays (what C1 reads) — distinct from initial_props. + state.qubit_ids = [str(i) for i in range(8)] + state.edges_list = [(i, i + 1) for i in range(7)] + state.qubit_props_data = {'readout_error': np.array([0.001 * (i + 1) + for i in range(8)])} + state.gate_props_data = {'cz_error': np.array([0.002 * (i + 1) + for i in range(7)])} + b = MapperUIBuilder(state) + b.build() + # build() resets time_mode→'live'; apply the past-date selection AFTER it. + if past_date: + state.time_mode = 'point' + state.point_timestamp = past_date + return b, state + + +# ── t1: pre-rank props == circuit-score arrays (one epoch) ────────────────── + +def test_prerank_uses_selected_date_not_live_props(monkeypatch): + b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') + captured = {} + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: captured.update(props=pr) or _canned()) + + b.btn_lucj_run.click() + pr = captured['props'] + # NOT the live BackendProperties (which returns the 0.99 sentinel)... + assert pr is not state.initial_props + assert abs(pr.readout_error(3) - 0.99) > 1e-6 + # ...it is the selected date's arrays — identical to what C1 reads. + assert pr.readout_error(3) == state.qubit_props_data['readout_error'][3] + assert pr.readout_error(7) == state.qubit_props_data['readout_error'][7] + + +# ── t3: the scan header names the epoch mix on a past date ────────────────── + +def test_scan_header_notes_epoch_mix_on_past_date(monkeypatch): + b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, + 'reason': None}]) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state, **k: (lambda backend: SimpleNamespace( + vintage='live · 09:30', + score_layout=lambda q: {'fidelity': 0.5}))) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned()) + + b.btn_scan_qpus.click() + html = "".join(c.value for c in b.scan_results_box.children + if isinstance(getattr(c, 'value', None), str)) + assert 'local backend scored on 2026-07-01' in html + assert 'remote backends on live' in html + + +def test_scan_header_absent_in_live_mode(monkeypatch): + b, state = _build(monkeypatch, past_date=None) # live + import qpu_mapper.qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, + 'reason': None}]) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state, **k: (lambda backend: SimpleNamespace( + vintage='live · 09:30', + score_layout=lambda q: {'fidelity': 0.5}))) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned()) + + b.btn_scan_qpus.click() + html = "".join(c.value for c in b.scan_results_box.children + if isinstance(getattr(c, 'value', None), str)) + assert 'scored on' not in html From 406b65dd6772f83a0edc860c2f6824dde5ee23c2 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 21:15:53 -0400 Subject: [PATCH 14/66] Fix event-loop acquisition in async_util (zero warnings restored) --- qpu_mapper/async_util.py | 42 +++++++++++++++----------- tests/test_async_util.py | 65 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 18 deletions(-) diff --git a/qpu_mapper/async_util.py b/qpu_mapper/async_util.py index 35d1a56..d95ee6f 100644 --- a/qpu_mapper/async_util.py +++ b/qpu_mapper/async_util.py @@ -36,27 +36,33 @@ def _resolve_main_loop_scheduler(): same thread the kernel runs on. Resolution order: - 1. tornado IOLoop (classic notebook + most JupyterLab kernels) - 2. asyncio event loop (asyncio-native kernels) - 3. inline fallback (run on the worker thread, original behaviour) + 1. a RUNNING event loop → tornado IOLoop (classic notebook + most + JupyterLab kernels), else asyncio call_soon_threadsafe + 2. inline fallback (run on the worker thread, original behaviour) + + We gate on a *running* loop via ``asyncio.get_running_loop()`` FIRST. + That call never warns; ``tornado.ioloop.IOLoop.current()`` (and the + ``asyncio.get_event_loop()`` it wraps) emits Python ≥3.10's "There is no + current event loop" DeprecationWarning when called with no loop running — + the headless-test case. With no running loop the correct scheduler is the + inline fallback anyway (a non-running loop's ``add_callback`` would never + fire), so we must never reach that deprecated path. """ + import asyncio try: - from tornado.ioloop import IOLoop - loop = IOLoop.current() - return lambda cb: loop.add_callback(cb) - except Exception: - _log.debug("tornado IOLoop unavailable", exc_info=True) - try: - import asyncio + running = asyncio.get_running_loop() + except RuntimeError: + running = None + if running is not None: try: - aloop = asyncio.get_running_loop() - except RuntimeError: - aloop = None - if aloop is not None: - return lambda cb: aloop.call_soon_threadsafe(cb) - except Exception: - _log.debug("asyncio event loop unavailable", exc_info=True) - # No event loop available — run inline on the worker thread. + from tornado.ioloop import IOLoop + loop = IOLoop.current() # safe: a loop is running + return lambda cb: loop.add_callback(cb) + except Exception: + _log.debug("tornado IOLoop unavailable", exc_info=True) + return lambda cb: running.call_soon_threadsafe(cb) + # No running event loop (headless tests, or kernel loop not yet started) — + # run inline on the worker thread (original fallback behaviour). return lambda cb: cb() diff --git a/tests/test_async_util.py b/tests/test_async_util.py index ae989fd..a0a3f37 100644 --- a/tests/test_async_util.py +++ b/tests/test_async_util.py @@ -122,3 +122,68 @@ def _on_done_that_raises(_r): # logs it and returns. for cb in queued: cb() + + +# ── Zero-warnings guard: the scheduler resolver must never trip tornado's +# "There is no current event loop" DeprecationWarning in a headless +# context (no running loop) — the regression that put 1 warning back in +# the suite after the calibration-epoch merge. ─────────────────────────── + +def _install_warning_tornado(monkeypatch): + """Inject a fake tornado.ioloop whose IOLoop.current() emits the exact + deprecation, so we can assert our resolver does NOT reach it with no + running loop — independent of whether real tornado is installed.""" + import sys + import types + import warnings as _w + + class _IOLoop: + @staticmethod + def current(): + # Faithful to real tornado: the deprecation fires ONLY when there + # is no running loop (IOLoop.current() → asyncio.get_event_loop()). + import asyncio as _a + try: + _a.get_running_loop() + except RuntimeError: + _w.warn("There is no current event loop", DeprecationWarning) + return types.SimpleNamespace(add_callback=lambda cb: cb()) + + tornado = types.ModuleType("tornado") + ioloop = types.ModuleType("tornado.ioloop") + ioloop.IOLoop = _IOLoop + tornado.ioloop = ioloop + monkeypatch.setitem(sys.modules, "tornado", tornado) + monkeypatch.setitem(sys.modules, "tornado.ioloop", ioloop) + + +def test_resolver_no_deprecation_without_running_loop(monkeypatch): + import warnings + import asyncio + _install_warning_tornado(monkeypatch) + # Guarantee no current/running loop in this thread. + monkeypatch.setattr(asyncio, "get_running_loop", + lambda: (_ for _ in ()).throw(RuntimeError("no loop"))) + with warnings.catch_warnings(record=True) as rec: + warnings.simplefilter("always") + sched = async_util._resolve_main_loop_scheduler() + assert [str(x.message) for x in rec] == [] # tornado never touched + ran = [] + sched(lambda: ran.append(1)) # inline fallback runs cb + assert ran == [1] + + +def test_resolver_uses_loop_scheduler_when_running(monkeypatch): + """With a running loop the tornado path IS taken (real tornado does not + warn in that case). Proves the fix didn't disable marshaling.""" + import asyncio + _install_warning_tornado(monkeypatch) + + async def _main(): + return async_util._resolve_main_loop_scheduler() + + sched = asyncio.run(_main()) + # Not the inline fallback: the tornado IOLoop scheduler was selected. + delivered = [] + sched(lambda: delivered.append(1)) + assert delivered == [1] From 9be4f2ba75072b8b503e5c25210a6db1cea67b6e Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 21:40:59 -0400 Subject: [PATCH 15/66] Add quality floor to stability filter; scan-filtered isolation test --- qpu_mapper/stability_filter.py | 141 ++++++++++++++++++++++++++++----- qpu_mapper/ui/builder.py | 15 +++- qpu_mapper/ui/lucj_panel.py | 24 ++++-- tests/test_stability_filter.py | 99 ++++++++++++++++++++++- tests/test_stability_ui.py | 73 +++++++++++++++++ 5 files changed, 326 insertions(+), 26 deletions(-) diff --git a/qpu_mapper/stability_filter.py b/qpu_mapper/stability_filter.py index 167a4e1..68cd907 100644 --- a/qpu_mapper/stability_filter.py +++ b/qpu_mapper/stability_filter.py @@ -20,11 +20,22 @@ import logging +import numpy as np + from .ancilla_sweep import sweep_ancilla_layouts from .stability import analyze_property_stability _log = logging.getLogger(__name__) +# Quality floor mirrors the C1 box's device-outlier rule — the `outliers` +# block in ``export/scoring.py`` (readout > mean + sigma*std over the non-NaN +# device readouts, guarded by ``len > OUTLIER_MIN_SAMPLES``). The source +# constants OUTLIER_SIGMA=3.0 / OUTLIER_MIN_SAMPLES=10 live in +# ``export/__init__.py``; we mirror the min-samples guard here to keep this +# lean engine free of the heavy ``export`` package import (the sigma is a +# caller parameter, defaulting to the same 3.0). +_OUTLIER_MIN_SAMPLES = 10 + # Volatility = analyze_property_stability's 'error' score = max/median - 1. # The default threshold flags a qubit whose worst windowed day exceeded ~1.5× # its own median readout error (score > 0.5) — a clear, repeated instability, @@ -96,23 +107,93 @@ def select_excluded(volatility, *, threshold): return [q for q, _ in over] +def select_quality_floor(current_props_arrays, *, sigma=3.0): + """Qubit ids whose CURRENT readout_error is a device OUTLIER — greater than + ``mean + sigma*std`` over the non-NaN device readouts. + + This promotes the C1 Estimated-Layout-Quality box's ">3σ from device mean" + warning (the ``outliers`` block in ``export/scoring.py``) from a warning to + a FILTER component. It catches STABLY-terrible qubits — a qubit parked at + ~73× the device median but flat over time — which the volatility score + (``max/median − 1`` ≈ 0 when flat) is blind to by construction. + + Args: + current_props_arrays: either a ``{'readout_error': seq}`` dict + (``qubit_props`` shape) or a bare per-qubit readout sequence, + indexed by physical qubit id. "Current" — not historical: a + stably-terrible qubit is terrible NOW. + sigma: outlier cutoff in standard deviations (default 3.0, matching + ``export.OUTLIER_SIGMA``). + + Returns sorted ``list[int]`` of offending qubit ids. Empty when there are + too few samples to judge (``<= OUTLIER_MIN_SAMPLES``, the same guard C1 + uses) or no valid readouts. + """ + arr = (current_props_arrays.get(_READOUT_KEY) + if isinstance(current_props_arrays, dict) else current_props_arrays) + if arr is None: + return [] + arr = np.asarray(arr, dtype=float) + if arr.size <= _OUTLIER_MIN_SAMPLES: + return [] + valid = arr[~np.isnan(arr)] + if valid.size == 0: + return [] + threshold = float(np.mean(valid) + sigma * float(np.std(valid))) + return sorted(int(q) for q in range(arr.size) + if not np.isnan(arr[q]) and arr[q] > threshold) + + +def _n_qubits_from_history(history): + """Qubit count from the first history snapshot's readout array.""" + for snap in history.values(): + arr = snap.get('qubit_props', {}).get(_READOUT_KEY) + if arr is not None: + return len(arr) + return 0 + + +def _current_readout_array(props, n_qubits): + """The CURRENT props' readout_error for every qubit (NaN-safe), so the + quality floor's device statistics are computed on the epoch being scored, + not on history.""" + out = [] + for q in range(n_qubits): + try: + v = props.readout_error(q) + except Exception: + v = None + out.append(float('nan') if v is None else float(v)) + return out + + def sweep_with_stability(norb, backend, props, history, *, window_days=14, threshold=_DEFAULT_THRESHOLD, min_bridges=None, top_n=3, mapping_cap=None, - today=None): + today=None, quality_sigma=3.0): """Stability-filtered ancilla sweep with an automatic relax valve. - 1. Score volatility over the windowed history and build the excluded set. + 1. Build the excluded set = VOLATILITY-excluded (windowed history) ∪ + QUALITY-FLOOR-excluded (current device outliers, F2). The floor is + computed on the CURRENT props, not history — a stably-terrible qubit + is terrible NOW, and volatility scoring is blind to it. 2. Run the sweep excluding those qubits. 3. If the pruned graph cannot host ``norb`` (the sweep raises — zero embeddings, no bridges fit, or template creation fails), re-admit the - LEAST-volatile excluded qubits in batches (``_RELAX_BATCH_FRAC`` of the - initial set per step, at least 1) and retry, until it fits or nothing - is left excluded. - 4. Return the sweep dict EXTENDED with a ``stability`` block. + LEAST-bad excluded qubits in batches and retry. RE-ADMISSION ORDER: + volatility qubits first (least-volatile of them first), quality-floor + qubits LAST — a stably-terrible outlier is the last thing we want back, + so floor qubits sit at the HEAD of the list and the tail-first valve + reaches them only after every volatility qubit has been re-admitted (a + single batch is capped at the volatility/floor boundary so it can never + cross early). + 4. Return the sweep dict EXTENDED with a ``stability`` block. When + ``quality_sigma`` is not None the block also carries + ``n_floor_excluded`` and ``floor_qubits`` (sorted). - No / empty history → run the plain sweep and set - ``stability={'available': False}`` (never raises for lack of history). + ``quality_sigma=None`` disables the floor entirely — byte-identical to the + pre-floor behaviour (no floor keys added). No / empty history AND no floor + hit → the plain sweep with ``stability={'available': False}``. """ def _plain(): res = sweep_ancilla_layouts( @@ -124,18 +205,34 @@ def _plain(): if not history: return _plain() - # (F2) Anchor the window to the SELECTED date when one is active — dates - # after `today` are ignored, so the window is [today-window_days, today]. + # Anchor the window to the SELECTED date when one is active — dates after + # `today` are ignored, so the window is [today-window_days, today]. # today=None keeps the now-anchored latest-window behaviour (live mode). volatility = compute_qubit_volatility(history, window_days, today=today) - if not volatility: + + # (F2) Quality floor on the CURRENT props (independent of history). + floor_qubits = [] + if quality_sigma is not None: + n_q = _n_qubits_from_history(history) + if n_q: + floor_qubits = select_quality_floor( + _current_readout_array(props, n_q), sigma=quality_sigma) + + if not volatility and not floor_qubits: return _plain() - excluded = select_excluded(volatility, threshold=threshold) # most→least - n_excluded_initial = len(excluded) + # Combined exclusion: floor at the HEAD, volatility (most→least) at the + # TAIL, so the tail-first relax valve re-admits volatility before floor. + vol_excluded = select_excluded(volatility, threshold=threshold) + floor_set = set(floor_qubits) + vol_only = [q for q in vol_excluded if q not in floor_set] + floor_head = sorted(floor_set) + combined = floor_head + vol_only + n_floor = len(floor_head) + n_excluded_initial = len(combined) batch = max(1, int(n_excluded_initial * _RELAX_BATCH_FRAC)) - current = list(excluded) + current = list(combined) n_readmitted = 0 relaxed = False while True: @@ -151,12 +248,16 @@ def _plain(): # not a filter-too-strict one. Propagate. raise relaxed = True - # Re-admit the least-volatile tail (current is most→least). - readmit = current[-batch:] - current = current[:-batch] + # Peel the tail (least-volatile first). Cap at the vol/floor + # boundary so a batch never re-admits a floor qubit while any + # volatility qubit is still excluded. + n_vol_left = max(0, len(current) - n_floor) + peel = min(batch, n_vol_left) if n_vol_left > 0 else min(batch, len(current)) + readmit = current[-peel:] + current = current[:-peel] n_readmitted += len(readmit) _log.info("Stability sweep: norb=%d didn't fit with %d excluded " - "(%s); re-admitted %d least-volatile, retrying", + "(%s); re-admitted %d least-bad, retrying", norb, len(current) + len(readmit), exc, len(readmit)) res['stability'] = { @@ -168,4 +269,8 @@ def _plain(): 'excluded_final': sorted(current), 'relaxed': relaxed, } + if quality_sigma is not None: + floor_final = sorted(q for q in current if q in floor_set) + res['stability']['n_floor_excluded'] = len(floor_final) + res['stability']['floor_qubits'] = floor_final return res diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index eee8d82..f171dc2 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -336,6 +336,7 @@ def _run_pipeline(self): chk_stability_filter=self.chk_stability_filter, rb_stability_window=self.rb_stability_window_auto, ft_stability_threshold=self.ft_stability_threshold, + ft_stability_floor=self.ft_stability_floor, stability_ctrl_box=self.stability_ctrl_box, lbl_lucj_stability=self.lbl_lucj_stability, chk_scan_stability=self.chk_scan_stability, @@ -1274,9 +1275,19 @@ def _build_auto_lucj_widgets(self, W): style={'description_width': '90px'}, tooltip='Volatility score = max/median − 1; higher threshold = ' 'more tolerant (fewer qubits excluded)') - # Window + threshold row, revealed only when the filter is on. + # (F3) Quality floor: also exclude STABLY-terrible qubits — current + # readout outliers the volatility score is blind to. σ from device mean. + self.ft_stability_floor = BoundedFloatText( + value=3.0, min=0.0, max=20.0, step=0.5, + description='Quality floor:', layout=Layout(width='230px'), + style={'description_width': '90px'}, + tooltip='Exclude qubits whose CURRENT readout error is more than ' + 'this many σ above the device mean (0 = off). Catches ' + 'consistently-bad qubits, not just volatile ones.') + # Window + threshold + floor row, revealed only when the filter is on. self.stability_ctrl_box = VBox( - [self.rb_stability_window_auto, self.ft_stability_threshold]) + [self.rb_stability_window_auto, self.ft_stability_threshold, + self.ft_stability_floor]) self.stability_ctrl_box.layout.display = 'none' self.lbl_lucj_stability = HTML("") # Scan sub-option: filter each scanned backend with CACHED history only. diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index c739393..3a8a8bb 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -423,7 +423,8 @@ def _generate_sweep(norb): window_days=rb_stability_window.value, threshold=ft_stability_threshold.value, min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], - mapping_cap=kwargs['mapping_cap'], today=anchor) + mapping_cap=kwargs['mapping_cap'], today=anchor, + quality_sigma=_floor_sigma()) _render_stability_banner(res.get('stability'), norb, anchor=anchor) # The frozen stability engine can't take circuit_score_fn — fill # circuit-level LQS on its survivors here (A2). @@ -559,7 +560,15 @@ def _on_ancilla_mode_change(change=None): chk_stability_filter = ctx.chk_stability_filter rb_stability_window = ctx.rb_stability_window ft_stability_threshold = ctx.ft_stability_threshold + ft_stability_floor = ctx.ft_stability_floor stability_ctrl_box = ctx.stability_ctrl_box + + def _floor_sigma(): + """(F3) Quality-floor σ from the UI; 0 → None (floor off). Read at + each sweep_with_stability call site (like window/threshold), so the + local sweep and the scan share it by construction.""" + v = getattr(ft_stability_floor, 'value', None) + return v if (v and v > 0) else None lbl_lucj_stability = ctx.lbl_lucj_stability chk_scan_stability = ctx.chk_scan_stability @@ -599,12 +608,15 @@ def _window_txt(): f"{esc(str(stab.get('n_excluded_initial')))} " f"(most-volatile still excluded)
") else: - n = len(stab.get('excluded_final', [])) + total = len(stab.get('excluded_final', [])) + m_floor = stab.get('n_floor_excluded', 0) # (F3) outliers + n_vol = total - m_floor + floor_txt = f" + {esc(str(m_floor))} outlier" if m_floor else "" lbl_lucj_stability.value = ( f"
🛡 filtered {esc(str(n))} volatile qubits " - f"(window {_window_txt()})
") + f"margin:3px 0;'>🛡 filtered {esc(str(n_vol))} volatile" + f"{floor_txt} qubits (window {_window_txt()})") def _cached_history_for(backend_name): """Assemble a per-backend history dict from the DISK CACHE ONLY (no @@ -693,6 +705,7 @@ def _scan_backends(eligible, norb, get_backend, get_props, use_filter): kwargs = _sweep_kwargs_from_ui() window = rb_stability_window.value threshold = ft_stability_threshold.value + floor_sigma = _floor_sigma() # (F3) scan inherits the floor results = [] n_scanned = n_failed = n_skipped = 0 for t in eligible: @@ -711,7 +724,8 @@ def _scan_backends(eligible, norb, get_backend, get_props, use_filter): threshold=threshold, min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], - mapping_cap=kwargs['mapping_cap']) + mapping_cap=kwargs['mapping_cap'], + quality_sigma=floor_sigma) stab = res.get('stability', {'available': False}) else: res = sweep_ancilla_layouts(norb, backend, props, **kwargs) diff --git a/tests/test_stability_filter.py b/tests/test_stability_filter.py index 85ab35c..f2a3402 100644 --- a/tests/test_stability_filter.py +++ b/tests/test_stability_filter.py @@ -12,7 +12,8 @@ from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts from qpu_mapper.stability_filter import ( - compute_qubit_volatility, select_excluded, sweep_with_stability, + compute_qubit_volatility, select_excluded, select_quality_floor, + sweep_with_stability, ) @@ -167,3 +168,99 @@ def test_metadata_and_truncation_propagation(): assert st['available'] is True assert st['excluded_final'] == sorted(st['excluded_final']) assert res['excluded_qubits'] == sorted(res['excluded_qubits']) + + +# ── F1/F2: quality floor — stably-terrible qubits volatility is blind to ──── + +class _OutlierProps: + """Current props where qubit 24 is a stable device outlier (~73× the + rest); everything else uniform. Volatility (history) can't see this.""" + def readout_error(self, q): + return 0.73 if q == 24 else 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def test_quality_floor_excludes_stably_terrible_not_volatility(): + backend = _make_backend() + hist = _history({}) # perfectly flat → volatility 0 + res = sweep_with_stability(8, backend, _OutlierProps(), hist, + window_days=14, threshold=1.0, min_bridges=1, + quality_sigma=3.0) + st = res['stability'] + assert st['floor_qubits'] == [24] # the outlier + assert st['n_floor_excluded'] == 1 + assert 24 in st['excluded_final'] + # Volatility alone (floor off) leaves the stably-terrible qubit untouched. + res_off = sweep_with_stability(8, backend, _OutlierProps(), hist, + window_days=14, threshold=1.0, min_bridges=1, + quality_sigma=None) + assert 24 not in res_off['stability'].get('excluded_final', []) + + +def test_select_quality_floor_is_the_c1_outlier_rule(): + # Flat device with one 3σ+ outlier at index 5. + arr = [0.01] * 20 + arr[5] = 0.5 + assert select_quality_floor({'readout_error': arr}, sigma=3.0) == [5] + assert select_quality_floor(arr, sigma=3.0) == [5] # bare array too + assert select_quality_floor(arr, sigma=50.0) == [] # loosen → none + assert select_quality_floor([0.01] * 5) == [] # < min samples + + +def _single_block_backend(): + """One 24-qubit block (ids 0..23) — the ONLY host, so pruning a chain + qubit genuinely breaks the fit and forces the relax valve.""" + edges = [] + _build_block(0, edges) + g = rustworkx.PyDiGraph() + for i in range(24): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _BridgeOutlierProps: + """Current outlier at bridge qubit 20 (excludable without breaking the + chain); everything else uniform.""" + def readout_error(self, q): + return 0.73 if q == 20 else 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def test_relax_readmits_volatility_before_floor(): + backend = _single_block_backend() + # Top-row qubits 5,6 are volatile (chain-critical); bridge 20 is a CURRENT + # outlier (non-critical). Excluding {5,6,20} breaks the top chain → relax. + # The valve must re-admit the volatility qubits (5,6) and NEVER re-admit + # the floor qubit 20 — a stably-terrible qubit is the last thing back. + hist = _history({5: 0.06, 6: 0.055}, n_qubits=24) + res = sweep_with_stability(8, backend, _BridgeOutlierProps(), hist, + window_days=14, threshold=1.0, min_bridges=1, + quality_sigma=3.0) + st = res['stability'] + assert st['relaxed'] is True + assert st['floor_qubits'] == [20] + assert 20 in st['excluded_final'] # floor never re-admitted + assert not ({5, 6} <= set(st['excluded_final'])) # volatility re-admitted + assert st['n_readmitted'] >= 1 + assert res['strata'] # sweep succeeded + + +def test_quality_sigma_none_is_byte_compatible(): + backend = _make_backend() + hist = _history({3: 0.06, 2: 0.055}) + res = sweep_with_stability(8, backend, _OutlierProps(), hist, + window_days=14, threshold=1.0, min_bridges=1, + quality_sigma=None) + st = res['stability'] + assert 'n_floor_excluded' not in st and 'floor_qubits' not in st + # Exactly the volatility-only exclusion; the current outlier is ignored. + vol = compute_qubit_volatility(hist, 14) + assert set(st['excluded_final']) == set(select_excluded(vol, threshold=1.0)) + assert 24 not in st['excluded_final'] diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index c6cfa8a..2284e90 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -197,3 +197,76 @@ def test_filter_off_uses_plain_sweep(monkeypatch): assert plain == [1] # plain sweep used assert sws == [] # filter engine untouched assert b.lbl_lucj_stability.value == "" # no banner + + +# ── F3: banner counts N volatile + M outlier from the metadata ────────────── + +def test_banner_counts_volatile_and_outlier(monkeypatch): + b = _build(monkeypatch, history=True) + monkeypatch.setattr( + "qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: _canned_res({ + 'available': True, 'relaxed': False, + 'excluded_final': [1, 2, 3, 4, 5], # 5 total + 'n_floor_excluded': 2, 'floor_qubits': [4, 5], + 'window_days': 14})) + b.chk_stability_filter.value = True + b.btn_lucj_run.click() + v = b.lbl_lucj_stability.value + assert 'filtered 3 volatile + 2 outlier qubits' in v # 5 − 2 floor = 3 + + +def test_banner_no_outlier_suffix_when_floor_empty(monkeypatch): + b = _build(monkeypatch, history=True) + monkeypatch.setattr( + "qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: _canned_res({ + 'available': True, 'relaxed': False, + 'excluded_final': [1, 2], 'n_floor_excluded': 0, + 'floor_qubits': [], 'window_days': 14})) + b.chk_stability_filter.value = True + b.btn_lucj_run.click() + v = b.lbl_lucj_stability.value + assert 'filtered 2 volatile qubits' in v and 'outlier' not in v + + +# ── t5: _scan_filtered per-backend isolation + both badge paths ───────────── + +def test_scan_filtered_per_backend_isolation(monkeypatch): + b = _build(monkeypatch, history=True) + b.chk_stability_filter.value = True + b.chk_scan_stability.value = True + # ibm_c (the MIDDLE target) blows up during history assembly; the loop + # must survive so ibm_b (after it) still completes. + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_c', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) + from qpu_mapper import data + monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: + [{'last_update': '2026-07-05 08:00:00'}] + if name in ('ibm_a', 'ibm_c') else []) + + def _load(name, ts): + if name == 'ibm_c': + raise RuntimeError('cache read exploded') + return ({'readout_error': [0.01] * 8}, {'cz_error': [0.001] * 7}) + monkeypatch.setattr(data, '_load_calibration', _load) + + filt = dict(_canned_res({'available': True, 'relaxed': False, + 'excluded_final': [3, 4], 'window_days': 14})) + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: filt) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned_res(None)) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: SimpleNamespace( + vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) + + b.btn_scan_qpus.click() + table = b.scan_results_box.children[0].value + # (a) isolation: ibm_c's raise became an error row, loop not killed. + assert 'cache read exploded' in table + # (b) both badge paths: cached → filtered, fresh → n/a. + assert '🛡 −2 qubits' in table # ibm_a cached → filtered + assert 'n/a (no cached history)' in table # ibm_b (after ibm_c) fresh From da141bc887ece336d95fa4a8eb911868a6fc860b Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 21:54:08 -0400 Subject: [PATCH 16/66] Unify scan paths behind sweep_fn hook --- qpu_mapper/qpu_scan.py | 20 ++++++- qpu_mapper/ui/lucj_panel.py | 110 +++++++++++++++--------------------- tests/test_qpu_scan.py | 66 ++++++++++++++++++++++ tests/test_stability_ui.py | 2 +- 4 files changed, 131 insertions(+), 67 deletions(-) diff --git a/qpu_mapper/qpu_scan.py b/qpu_mapper/qpu_scan.py index ea73ee7..8a0f09e 100644 --- a/qpu_mapper/qpu_scan.py +++ b/qpu_mapper/qpu_scan.py @@ -166,7 +166,7 @@ def _best_from_sweep(sweep): def scan_qpus(targets, norb, get_backend, get_props, *, - min_bridges=None, top_n=3, progress_cb=None): + min_bridges=None, top_n=3, progress_cb=None, sweep_fn=None): """Run the ancilla sweep on each target backend, isolating failures. Args: @@ -178,10 +178,23 @@ def scan_qpus(targets, norb, get_backend, get_props, *, free of service/network specifics and makes it testable). get_props: ``backend -> props`` (injected; MUST be wired by 3b to the cache-aware ``data.py`` path). - min_bridges, top_n: forwarded to ``sweep_ancilla_layouts``. + min_bridges, top_n: forwarded to the sweep. progress_cb: optional ``callable(name, status, detail)`` with status in ``'start' | 'ok' | 'skipped' | 'error'``. Exceptions raised by the callback are swallowed — progress reporting must never break a scan. + sweep_fn: optional ``callable(norb, backend, props, *, min_bridges, + top_n) -> sweep_dict`` used INSTEAD OF ``sweep_ancilla_layouts`` per + eligible target. ``None`` (default) is byte-compatible with the + historical behaviour (calls ``sweep_ancilla_layouts`` directly). + When provided, the ONE isolation / progress / best-LQS-ranking loop + below is reused unchanged — the injected function decides only WHAT + sweep runs (e.g. a ``sweep_with_stability`` closure that assembles + per-backend cached history and applies the volatility + quality- + floor filter). It must return the same sweep-dict shape (a + ``strata`` map, optionally an extra ``stability`` block the caller + post-processes); any extra metadata it stashes rides along on the + returned ``sweep``. A per-target exception it raises is caught here + like any other, becoming that backend's error row. Returns:: @@ -197,6 +210,7 @@ def scan_qpus(targets, norb, get_backend, get_props, *, # Lazy import so tests can monkeypatch the module attribute, and so this # module stays import-light for the list_scan_targets-only callers. from .ancilla_sweep import sweep_ancilla_layouts + _sweep = sweep_fn if sweep_fn is not None else sweep_ancilla_layouts def _emit(name, status, detail=''): if progress_cb is None: @@ -229,7 +243,7 @@ def _entry(name, family, sweep=None, best_lqs=None, best_k=None, error=None): try: backend = get_backend(name) props = get_props(backend) - sweep = sweep_ancilla_layouts( + sweep = _sweep( norb, backend, props, min_bridges=min_bridges, top_n=top_n) except Exception as exc: diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 3a8a8bb..d8f31c1 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -692,76 +692,60 @@ def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): "k=%d: %s", r['name'], k, exc) def _scan_backends(eligible, norb, get_backend, get_props, use_filter): - """The SINGLE handler-side scan path. Per target it calls the sweep - with EXACTLY _sweep_kwargs_from_ui() — the same params as the local - sweep (incl. hybrid) — so scan and local can't diverge (P1). When - use_filter is on and the backend has CACHED history, it routes through - sweep_with_stability instead. Not qpu_scan.scan_qpus, which is frozen - and can't forward hybrid; this mirrors its contract (per-backend - isolation, progress_cb, best_lqs sort) plus stability + vintage. + """The SINGLE handler-side scan path (U2). The per-backend isolation / + progress / best-LQS ranking loop lives ONCE, in qpu_scan.scan_qpus; we + inject a ``sweep_fn`` closure that carries the only handler-specific + parts: the SAME params as the local sweep (_sweep_kwargs_from_ui, incl. + hybrid & cap — so scan and local can't diverge, P1) plus, when the + filter is on and the backend has CACHED history, the volatility + + quality-floor filter via sweep_with_stability. The stability block the + closure attaches to each sweep is lifted to the row level afterwards so + the badges render unchanged. """ + from .. import qpu_scan from ..ancilla_sweep import sweep_ancilla_layouts from ..stability_filter import sweep_with_stability kwargs = _sweep_kwargs_from_ui() window = rb_stability_window.value threshold = ft_stability_threshold.value floor_sigma = _floor_sigma() # (F3) scan inherits the floor - results = [] - n_scanned = n_failed = n_skipped = 0 - for t in eligible: - name = t.get('name') if isinstance(t, dict) else t - family = t.get('family') if isinstance(t, dict) else None - _on_scan_progress(name, 'start', 'fetching calibration…') - try: - backend = get_backend(name) - props = get_props(backend) - hist = _cached_history_for(name) if use_filter else None - if hist: - # sweep_with_stability (frozen) can't take hybrid; it uses - # the engine default. Forward min_bridges/top_n/mapping_cap. - res = sweep_with_stability( - norb, backend, props, hist, window_days=window, - threshold=threshold, - min_bridges=kwargs['min_bridges'], - top_n=kwargs['top_n'], - mapping_cap=kwargs['mapping_cap'], - quality_sigma=floor_sigma) - stab = res.get('stability', {'available': False}) - else: - res = sweep_ancilla_layouts(norb, backend, props, **kwargs) - stab = ({'available': False, 'reason': 'no cached history'} - if use_filter else None) - except Exception as exc: - n_failed += 1 - results.append({'name': name, 'family': family, 'sweep': None, - 'best_lqs': None, 'best_k': None, - 'error': str(exc), - 'stability': ({'available': False} - if use_filter else None)}) - _on_scan_progress(name, 'error', str(exc)) - continue - best_lqs, best_k = None, None - for k, entries in res['strata'].items(): - for e in entries: - if best_lqs is None or e['product_score'] > best_lqs: - best_lqs, best_k = e['product_score'], k - if best_lqs is None: - n_skipped += 1 - results.append({'name': name, 'family': family, 'sweep': res, - 'best_lqs': None, 'best_k': None, - 'error': None, 'stability': stab}) - _on_scan_progress(name, 'skipped', 'no candidates') - continue - n_scanned += 1 - results.append({'name': name, 'family': family, 'sweep': res, - 'best_lqs': best_lqs, 'best_k': best_k, - 'error': None, 'stability': stab}) - _on_scan_progress(name, 'ok', f'best LQS {best_lqs * 100:.1f}%') - ranked = [r for r in results if r['best_lqs'] is not None] - rest = [r for r in results if r['best_lqs'] is None] - ranked.sort(key=lambda r: r['best_lqs'], reverse=True) - return {'results': ranked + rest, 'n_scanned': n_scanned, - 'n_failed': n_failed, 'n_skipped': n_skipped} + + def _sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): + # min_bridges/top_n arrive from scan_qpus (they equal kwargs); the + # shared UI source also supplies hybrid & mapping_cap. + name = getattr(backend, 'name', None) + hist = _cached_history_for(name) if (use_filter and name) else None + if hist: + res = sweep_with_stability( + norb, backend, props, hist, window_days=window, + threshold=threshold, min_bridges=kwargs['min_bridges'], + top_n=kwargs['top_n'], mapping_cap=kwargs['mapping_cap'], + quality_sigma=floor_sigma) + else: + res = sweep_ancilla_layouts(norb, backend, props, **kwargs) + res['stability'] = ({'available': False, + 'reason': 'no cached history'} + if use_filter else None) + return res + + def _progress(name, status, detail=''): + # Preserve the pre-U2 'start' detail (scan_qpus emits it empty). + if status == 'start' and not detail: + detail = 'fetching calibration…' + _on_scan_progress(name, status, detail) + + result = qpu_scan.scan_qpus( + eligible, norb, get_backend, get_props, + min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], + progress_cb=_progress, sweep_fn=_sweep_fn) + + # Lift each sweep's stability block to the row level (badges read + # r['stability']); error rows (sweep=None) reflect filter availability. + for r in result['results']: + sweep = r.get('sweep') + r['stability'] = (sweep.get('stability') if sweep is not None + else ({'available': False} if use_filter else None)) + return result _scan = {'progress': {}, 'order': []} _STATUS_ICON = {'start': '⏳', 'ok': '✓', 'skipped': '·', 'error': '✗'} diff --git a/tests/test_qpu_scan.py b/tests/test_qpu_scan.py index 430a4c8..e3b2506 100644 --- a/tests/test_qpu_scan.py +++ b/tests/test_qpu_scan.py @@ -184,3 +184,69 @@ def test_scan_skips_ineligible_targets(monkeypatch): assert called == [] # sweep never invoked assert out['n_skipped'] == 1 and out['n_scanned'] == 0 assert out['results'][0]['sweep'] is None + + +# ── U1/U3: sweep_fn injection hook — the ONE loop, a pluggable sweep ──────── + +def test_sweep_fn_injected_per_target_with_isolation(): + """t-new-1: sweep_fn is called per eligible target with the forwarded + kwargs, and the shared loop keeps per-backend isolation (one raise → error + row, the others complete).""" + calls = [] + + def fake_sweep(norb, backend, props, *, min_bridges=None, top_n=3): + calls.append((backend.name, min_bridges, top_n)) + if backend.name == 'bad': + raise RuntimeError('boom') + return _canned_sweep({1: [{'product_score': 0.5}]}) + + backends = {n: SimpleNamespace(name=n) for n in ('good', 'bad', 'good2')} + targets = [{'name': n, 'family': 'Heron', 'eligible': True} + for n in ('good', 'bad', 'good2')] + out = scan_qpus(targets, 6, get_backend=lambda n: backends[n], + get_props=lambda b: object(), + min_bridges=2, top_n=5, sweep_fn=fake_sweep) + + assert len(calls) == 3 # per eligible target + assert all(mb == 2 and tn == 5 for _, mb, tn in calls) # kwargs forwarded + rows = {r['name']: r for r in out['results']} + assert rows['bad']['error'] == 'boom' and rows['bad']['sweep'] is None + assert rows['good']['sweep'] is not None # isolation held + assert rows['good2']['sweep'] is not None + assert out['n_failed'] == 1 and out['n_scanned'] == 2 + + +def test_sweep_fn_none_uses_sweep_ancilla_layouts(monkeypatch): + """sweep_fn=None (default) is byte-compatible: the built-in sweep runs.""" + seen = [] + monkeypatch.setattr( + "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, b, p, **k: seen.append(k) or _canned_sweep({1: [{'product_score': 0.4}]})) + out = scan_qpus([{'name': 'a', 'family': 'H', 'eligible': True}], 6, + get_backend=lambda n: SimpleNamespace(name=n), + get_props=lambda b: object(), min_bridges=1, top_n=3) + assert seen == [{'min_bridges': 1, 'top_n': 3}] # exactly today's call + assert out['results'][0]['best_lqs'] == 0.4 + + +def test_filtered_and_unfiltered_same_row_schema(): + """t-new-3: injecting a stability-carrying sweep_fn does not change the + result schema — the stability block rides inside `sweep`, the rows stay + identical to the plain path.""" + def plain(norb, backend, props, *, min_bridges=None, top_n=3): + return _canned_sweep({1: [{'product_score': 0.5}]}) + + def filtered(norb, backend, props, *, min_bridges=None, top_n=3): + s = _canned_sweep({1: [{'product_score': 0.5}]}) + s['stability'] = {'available': True, 'excluded_final': [1]} + return s + + tgts = [{'name': 'a', 'family': 'Heron', 'eligible': True}] + bk = lambda n: SimpleNamespace(name=n) + out_u = scan_qpus(tgts, 6, bk, lambda b: object(), sweep_fn=plain) + out_f = scan_qpus(tgts, 6, bk, lambda b: object(), sweep_fn=filtered) + + assert set(out_u) == set(out_f) == { + 'results', 'n_scanned', 'n_failed', 'n_skipped'} + ku = set(out_u['results'][0]); kf = set(out_f['results'][0]) + assert ku == kf == {'name', 'family', 'sweep', 'best_lqs', 'best_k', 'error'} diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index 2284e90..6415aaf 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -59,7 +59,7 @@ def _build(monkeypatch, *, history=False, spawn=_sync_spawn, state.active_backend = object() state.active_backend_name = "stub" state.active_chip = "stub_chip" - state.active_service = SimpleNamespace(backend=lambda n: object()) + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) state.available_backends = ["ibm_a", "ibm_b"] state.props_warning = None state.initial_props = object() From 329e820c92576873dfef046a468ce2b4c0626c70 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 22:09:45 -0400 Subject: [PATCH 17/66] Unify scan paths behind sweep_fn hook --- qpu_mapper/ui/inter_qpu.py | 89 ++++++++++++++- tests/test_inter_qpu_handoff.py | 187 ++++++++++++++++++++++++++++++++ tests/test_ui_cleanup.py | 1 + 3 files changed, 274 insertions(+), 3 deletions(-) create mode 100644 tests/test_inter_qpu_handoff.py diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index c926cb4..1c79a35 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -90,9 +90,19 @@ def setup_inter_qpu(ctx): # this function — no other UI code reads them. _state2 = [None] # SessionState for QPU 2 _fig2 = [None] # FigureWidget for QPU 2 + _w2 = [None] # WidgetsRef for QPU 2 (for refresh_plot repaint) _sidebar2 = [None] # QPU 2 sidebar VBox _zoom2 = [None] # QPU 2 zoom toolbar _dispose2 = [None] # callable that unobserves all QPU 2 widgets + _connect_in_flight = [False] # (O4) race guard: one auto-connect at a time + + # (O2) Background runner for the ONE-CLICK auto-connect. The Connect-QPU2 + # button handler is SYNCHRONOUS + network-touching; the scan pattern + # (default_spawn_bg + marshalled on_done/on_error) keeps the kernel + # responsive. Injectable via ctx for headless tests. + _spawn_bg = getattr(ctx, 'spawn_bg', None) + if _spawn_bg is None: + from ..async_util import default_spawn_bg as _spawn_bg _pre_inter_fig_size = [None, None] # (width, height) before toggling on _qpu_toggle = [None] # ToggleButtons for QPU1/QPU2 sidebar swap _pending_handoff = [None] # (backend_name, candidate) staged from a scan pick @@ -298,24 +308,31 @@ def stage_remote_candidate(backend_name, candidate): with contextlib.suppress(Exception): _qpu2_content_box[0].children = [HTML(staged_html)] + # (O2) The scan handoff now triggers ONE-CLICK connect (stage + auto- + # connect), defined after the connect handler below. Bound via a trampoline + # so this assignment can precede _auto_connect's definition. if handoff_cell is not None: - handoff_cell[0] = stage_remote_candidate + handoff_cell[0] = lambda bn, cand: _auto_connect(bn, cand) # ── Connect-QPU2 handler ──────────────────────────────────── def _on_connect_qpu2(b): + # Returns None on success, or an error STRING on failure — so the + # one-click auto path (O2) can tell whether to fall back to staged. + # The button's on_click ignores the return, so its behaviour is + # unchanged. backend_name = dd_backend_qpu2.value if not backend_name: lbl_qpu2_status.value = ( "" "Select a backend" ) - return + return 'Select a backend' if state.active_service is None: lbl_qpu2_status.value = ( "" "No service connected" ) - return + return 'No service connected' lbl_qpu2_status.value = ( f"" @@ -378,6 +395,7 @@ def _on_connect_qpu2(b): _state2[0] = s2 _fig2[0] = f2 + _w2[0] = w2 # (O4) kept for same-backend repaint _sidebar2[0] = sidebar2 _zoom2[0] = zoom2_bar # Disposer: walk the full widget tree (sidebar + fig_box) and @@ -440,9 +458,74 @@ def _on_connect_qpu2(b): f"" f"❌ {esc(str(e))}" ) + return str(e) btn_connect_qpu2.on_click(_on_connect_qpu2) + # ── O2/O3/O4: one-click auto-connect on a scan-candidate pick ─────── + def _staged_with_error(backend_name, candidate, err): + """(O3) Failure → back to today's STAGED state (re-stage so a manual + Connect re-applies the candidate) plus an esc()'d one-line error. The + user loses nothing; one click recovers.""" + stage_remote_candidate(backend_name, candidate) + lbl_qpu2_status.value = lbl_qpu2_status.value + ( + f"
" + f"❌ auto-connect failed: {esc(str(err))}
") + + def _auto_connect(backend_name, candidate): + """The scan handoff hook (replaces bare staging): stage, then drive the + SAME Connect-QPU2 handler automatically. Idempotent + race-guarded.""" + # Always stage first (reveal panel, prefill dropdown, preload candidate, + # staged banner) — identical to the pre-O2 behaviour and the fallback. + stage_remote_candidate(backend_name, candidate) + + # (O4) Same backend already connected as QPU-2 → skip the reconnect, + # just apply the candidate and repaint. _state2[0] holds the connected + # QPU-2 SessionState. + s2 = _state2[0] + if (s2 is not None + and getattr(s2, 'active_backend_name', None) == backend_name): + _pending_handoff[0] = None + with contextlib.suppress(Exception): + _apply_candidate_to_state(s2, candidate) + if _fig2[0] is not None and _w2[0] is not None: + from .. import plot as _plot + _plot.refresh_plot(_fig2[0], s2, _w2[0]) + lbl_qpu2_status.value = ( + f"
✅ Applied to already-connected " + f"{esc(str(backend_name))}.
") + return + + # (O4) A connect already in flight → the staging above is enough; + # don't launch a second connect. + if _connect_in_flight[0]: + return + + _connect_in_flight[0] = True + btn_connect_qpu2.disabled = True # disable the manual trigger too + lbl_qpu2_status.value = ( + f"
📡 connecting " + f"{esc(str(backend_name))}…
") + + def _finish(): + _connect_in_flight[0] = False + btn_connect_qpu2.disabled = False + + def _done(err): + _finish() + if err: # handler swallowed the exception, returned it + _staged_with_error(backend_name, candidate, err) + + def _error(exc): # handler itself raised unexpectedly + _finish() + _staged_with_error(backend_name, candidate, exc) + + _spawn_bg(lambda: _on_connect_qpu2(None), on_done=_done, on_error=_error) + # Expose the label-refresh hook so ui.backend_switch can call it after a # backend switch (the switcher has no other handle on this closure). return refresh_qpu1_label diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py new file mode 100644 index 0000000..29149e4 --- /dev/null +++ b/tests/test_inter_qpu_handoff.py @@ -0,0 +1,187 @@ +"""O5 — one-click inter-QPU handoff: selecting a remote scan candidate stages +AND auto-connects QPU 2, with graceful fallback, race guards, and a same-backend +shortcut. Headless: the network-touching connect deps are stubbed. +""" +from types import SimpleNamespace + +import pytest + + +# ── a label that records every value it is assigned (to watch transitions) ── + +class _RecLabel: + def __init__(self): + self.history = [] + + @property + def value(self): + return self.history[-1] if self.history else '' + + @value.setter + def value(self, v): + self.history.append(v) + + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._handlers = [] + + def observe(self, fn, names=None): + self._handlers.append(fn) + + def on_click(self, fn): + self._click = fn + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return + if on_done: + on_done(r) + + +def _ctx(*, spawn, backend_calls, raise_connect=False): + def _backend(n): + backend_calls.append(n) + if raise_connect: + raise RuntimeError('network down') + return SimpleNamespace(name=n) + + state = SimpleNamespace( + available_backends=['ibm_k'], active_backend_name='ibm_here', + active_service=SimpleNamespace(backend=_backend), + active_ansatz='lucj', current_colorscale='Viridis') + ctx = SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_RecLabel(), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), + full_ui=_Stub(children=[]), + handoff_cell=[None], + spawn_bg=spawn, + ) + return ctx, state + + +def _stub_connect_deps(monkeypatch): + """Stub the network/UI-building deps so a connect SUCCEEDS headlessly.""" + def _fake_build(s2, is_secondary=False, return_widgets=False): + s2.qubit_ids = ['0', '1', '2'] + s2.edges_list = [(0, 1), (1, 2)] + fig = SimpleNamespace() + fig_box2 = SimpleNamespace(children=[SimpleNamespace(), + SimpleNamespace(), fig]) + full_ui = SimpleNamespace(children=[SimpleNamespace(), fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'chip_label')) + monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + + +_CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} + + +# ── t1: selection triggers connect once; staged→connecting→connected ──────── + +def test_selection_auto_connects_once(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + _stub_connect_deps(monkeypatch) + calls = [] + ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) + + assert calls == ['ibm_k'] # connect path run exactly once + hist = ctx.lbl_qpu2_status.history + assert any('staged' in h for h in hist) # staged first + assert any('onnecting' in h for h in hist) # then connecting + assert 'Connected' in hist[-1] and 'ibm_k' in hist[-1] # cleared to connected + assert ctx.btn_connect_qpu2.disabled is False # trigger re-enabled + + +# ── t2: connect raising → staged fallback + error, trigger re-enabled ─────── + +def test_connect_failure_falls_back_to_staged(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + _stub_connect_deps(monkeypatch) + calls = [] + ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls, raise_connect=True) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) + + final = ctx.lbl_qpu2_status.value + assert 'staged' in final and 'Connect QPU 2' in final # back to staged + assert 'network down' in final # esc'd error line + assert ctx.btn_connect_qpu2.disabled is False # re-enabled + # The candidate is re-staged so one manual click can recover. + # (a manual connect would read dd_backend_qpu2.value) + assert ctx.dd_backend_qpu2.value == 'ibm_k' + + +# ── t3: in-flight guard — a second selection does not double-connect ──────── + +def test_in_flight_guard_no_double_connect(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + _stub_connect_deps(monkeypatch) + calls = [] + queued = [] + + def _manual_spawn(fn, on_done=None, on_error=None): + queued.append((fn, on_done, on_error)) # defer — stays in flight + + ctx, state = _ctx(spawn=_manual_spawn, backend_calls=calls) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) # starts a connect (queued) + ctx.handoff_cell[0]('ibm_k', _CAND) # second pick while in flight + + assert len(queued) == 1 # only ONE connect launched + assert calls == [] # nothing has run yet + # Draining the single queued connect runs the path exactly once. + fn, done, _ = queued[0] + done(fn()) + assert calls == ['ibm_k'] + + +# ── t4: same backend already connected → apply + repaint, no reconnect ────── + +def test_same_backend_applies_without_reconnect(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + _stub_connect_deps(monkeypatch) + repaints = [] + monkeypatch.setattr("qpu_mapper.plot.refresh_plot", + lambda fig, st, w: repaints.append(st)) + calls = [] + ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) # first: real connect + assert calls == ['ibm_k'] + + cand2 = {'alpha': [3], 'beta': [4], 'ancillas': [5]} + ctx.handoff_cell[0]('ibm_k', cand2) # same backend again + + assert calls == ['ibm_k'] # NO reconnect (still one call) + assert repaints # repainted in place + # The new candidate was applied to QPU-2's live state. + d = repaints[-1].layouts_data[0] + assert d['alpha'] == ['3'] and d['beta'] == ['4'] and d['ancilla'] == ['5'] + assert 'Applied to already-connected' in ctx.lbl_qpu2_status.value diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py index 80eeca8..dfdbec0 100644 --- a/tests/test_ui_cleanup.py +++ b/tests/test_ui_cleanup.py @@ -159,6 +159,7 @@ def _inter_ctx(): qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), full_ui=_Stub(children=[]), handoff_cell=[None], + spawn_bg=_sync_spawn, # deterministic one-click auto-connect ) return ctx, state From ef7a672868749f5eac872aaec1e2a6f19179bc4e Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 22:23:59 -0400 Subject: [PATCH 18/66] Add diversity option to top-N selection --- qpu_mapper/ancilla_sweep.py | 84 ++++++++++++++++++++++++- qpu_mapper/ui/builder.py | 9 +++ qpu_mapper/ui/lucj_panel.py | 10 ++- tests/test_diversity.py | 121 ++++++++++++++++++++++++++++++++++++ tests/test_scan_ui.py | 6 +- tests/test_sweep_ui.py | 27 ++++++++ 6 files changed, 250 insertions(+), 7 deletions(-) create mode 100644 tests/test_diversity.py diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index 8889f46..c7deb91 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -120,6 +120,62 @@ def _stable_seed(*parts) -> int: return int(digest[:8], 16) +def _entry_qubit_set(entry): + """Full physical qubit footprint of a candidate: alpha ∪ beta ∪ ancillas.""" + return frozenset(entry['alpha']) | frozenset(entry['beta']) \ + | frozenset(entry['ancillas']) + + +def _jaccard(a, b): + """|A ∩ B| / |A ∪ B| — 0 for two empty sets (no overlap to speak of).""" + union = a | b + if not union: + return 0.0 + return len(a & b) / len(union) + + +def _select_with_diversity(ranked, top_n, threshold): + """Quota-balanced top_n slice (user-approved option B). + + ``ranked`` is a best-first list of entries. The first ceil(top_n/2) slots + are the best entries ABSOLUTELY (unchanged). Each remaining slot is filled + with the best not-yet-picked entry whose Jaccard similarity + (``_jaccard`` over the full qubit set) to EVERY already-selected entry is + ``<= threshold`` — i.e. from a genuinely different chip region. If the + scored window holds no such candidate, it falls back to the next best + (similar) entry, so we never return fewer than ``min(top_n, len(ranked))`` + — diversity is a preference, not a constraint. + + Marks each returned entry: ``entry['diverse'] = True`` iff it was chosen + for dissimilarity (the UI badges those), else ``False``. + """ + n = min(top_n, len(ranked)) + if n <= 0: + return [] + half = (top_n + 1) // 2 # ceil(top_n / 2) + selected = list(ranked[:half]) + for e in selected: + e['diverse'] = False + sel_sets = [_entry_qubit_set(e) for e in selected] + remaining = list(ranked[half:]) + while len(selected) < n and remaining: + pick = None + for i, cand in enumerate(remaining): + cs = _entry_qubit_set(cand) + if all(_jaccard(cs, s) <= threshold for s in sel_sets): + pick = i + break + if pick is None: # no dissimilar candidate left + cand = remaining.pop(0) # fall back to next best + cand['diverse'] = False + else: + cand = remaining.pop(pick) + cand['diverse'] = True + selected.append(cand) + sel_sets.append(_entry_qubit_set(cand)) + return selected + + def _safe_readout(props, qubit): """Readout error for `qubit`, NaN/None -> penalty (mirrors lightweight).""" try: @@ -148,7 +204,8 @@ def sweep_ancilla_layouts(norb, backend, props, *, min_bridges=None, top_n=3, mapping_cap=None, exclude_qubits=None, circuit_score_fn=None, hybrid=True, - shuffle_seed=_AUTO_SHUFFLE) -> dict: + shuffle_seed=_AUTO_SHUFFLE, + diversity_threshold=None) -> dict: """One-shot ancilla sweep: VF2 at the geometric max bridge count, then derive every lower-k variant by bridge subtraction, score, and return the top_n candidates per ancilla count. @@ -191,6 +248,17 @@ def sweep_ancilla_layouts(norb, backend, props, *, ``k`` (still per-stratum, still reproducible; for tests). Physical qubit ids ride in node data and are recovered order-independently via ``_key_to_phys`` — no relabel leakage. + diversity_threshold: when a float in (0, 1), rebalance each stratum's + top_n for REGION diversity (D1). After the displayed-metric + ranking, the first ceil(top_n/2) slots keep the best entries + absolutely; each remaining slot takes the best entry whose Jaccard + similarity — ``|A∩B|/|A∪B|`` over the full qubit set (alpha ∪ beta ∪ + ancillas) — to EVERY already-selected entry is ``<= threshold`` + (0.8 ⇒ >0.8 is "same region, variant"). If the scored window has no + dissimilar candidate, it falls back to the next best (never fewer + than ``min(top_n, pool)``). Diversity-selected entries are tagged + ``entry['diverse'] = True``. ``None`` (default) → the exact top_n + slice, byte-compatible (no ``diverse`` key added). hybrid: when True (default), each stratum k' < k_max_effective is the UNION of (a) the derived prefix candidates AND (b) a DIRECT VF2 at the k' template on the same (possibly pruned) graph. Derivation @@ -507,7 +575,11 @@ def _add_variant(edata, k, source): if circuit_score_fn is None: # Byte-compatible pre-A2 path: product slice, no lqs_circuit. - entries = [e for _, e in by_product[:top_n]] + if diversity_threshold is None: + entries = [e for _, e in by_product[:top_n]] + else: + entries = _select_with_diversity( + [e for _, e in by_product], top_n, diversity_threshold) for rank, entry in enumerate(entries, start=1): entry['rank_in_stratum'] = rank strata[k] = entries @@ -541,7 +613,13 @@ def _add_variant(edata, k, source): else 0.0, e['product_score']), reverse=True) - entries = window[:top_n] + # (D1) Diversity quota: reserve later slots for different-region + # layouts (Jaccard <= threshold), applied AFTER the displayed-metric + # ranking, BEFORE rank numbering. None → exact top-N slice. + if diversity_threshold is None: + entries = window[:top_n] + else: + entries = _select_with_diversity(window, top_n, diversity_threshold) for rank, entry in enumerate(entries, start=1): entry['rank_in_stratum'] = rank strata[k] = entries diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index f171dc2..68360e2 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -307,6 +307,7 @@ def _run_pipeline(self): lucj_min_ancilla=self.lucj_min_ancilla, lucj_top_n=self.lucj_top_n, lucj_search_cap=self.lucj_search_cap, lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, + chk_lucj_diverse=self.chk_lucj_diverse, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, dd_lucj_layout=self.dd_lucj_layout, @@ -1253,6 +1254,13 @@ def _build_auto_lucj_widgets(self, W): layout=W, tooltip='adds a direct search per k — complete but slower; ' 'off = fast derivation from k_max only') + # (D2) Region diversity in the top-N slice. Default OFF. + self.chk_lucj_diverse = Checkbox( + value=False, + description='Prefer diverse regions', + layout=W, + tooltip='reserve top-N slots for layouts from different chip ' + 'regions (Jaccard > 0.8 = same region)') self.btn_lucj_run = Button( description='🤖 Generate LUCJ Layout', button_style='success', layout=W) @@ -1731,6 +1739,7 @@ def _build_auto_lucj_view(self): self.lucj_search_cap, self.lucj_chk_score, self.chk_deep_search, + self.chk_lucj_diverse, self.chk_stability_filter, self.stability_ctrl_box, self.lbl_lucj_stability, diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index d8f31c1..8153e00 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -106,6 +106,7 @@ def setup_lucj_callbacks(ctx): lucj_search_cap = ctx.lucj_search_cap lucj_chk_score = ctx.lucj_chk_score chk_deep_search = ctx.chk_deep_search + chk_lucj_diverse = ctx.chk_lucj_diverse btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status lbl_lucj_trunc = ctx.lbl_lucj_trunc @@ -345,6 +346,8 @@ def _sweep_kwargs_from_ui(): 'top_n': top_val if (top_val and top_val >= 1) else 3, 'hybrid': chk_deep_search.value, 'mapping_cap': cap_val if (cap_val and cap_val >= 1) else None, + # (D2) 0.8 default when ON; None → exact top-N (byte-compatible). + 'diversity_threshold': 0.8 if chk_lucj_diverse.value else None, } # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the @@ -450,8 +453,10 @@ def _generate_sweep(norb): for entry in strata[k]: pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" + alt = " · alt region" if entry.get('diverse') else "" # (D2) dd_opts.append(( - f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}", + f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" + f"{alt}", len(flat), )) flat.append(entry) @@ -793,7 +798,8 @@ def _entry_label(entry): k = len(entry['ancillas']) pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - return f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" + alt = " · alt region" if entry.get('diverse') else "" # (D2) + return f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}{alt}" def _render_targets(targets): rows = [] diff --git a/tests/test_diversity.py b/tests/test_diversity.py new file mode 100644 index 0000000..571e222 --- /dev/null +++ b/tests/test_diversity.py @@ -0,0 +1,121 @@ +"""D3 — quota-balanced diverse top-N slicing. + +Unit tests for the ranking-agnostic selector `_select_with_diversity` (the +quota math) plus an engine byte-compat pin for diversity_threshold=None. +""" +from types import SimpleNamespace + +import rustworkx + +from qpu_mapper.ancilla_sweep import ( + _jaccard, _select_with_diversity, sweep_ancilla_layouts, +) + + +def _mk(qubits): + """A candidate entry with a given qubit footprint (split alpha/beta).""" + q = list(qubits) + h = len(q) // 2 + return {'alpha': q[:h], 'beta': q[h:], 'ancillas': []} + + +# ── Jaccard sanity ────────────────────────────────────────────────────────── + +def test_jaccard_basics(): + assert _jaccard(frozenset(), frozenset()) == 0.0 + assert _jaccard(frozenset({1, 2}), frozenset({1, 2})) == 1.0 + assert _jaccard(frozenset({1, 2, 3}), frozenset({1, 2, 4})) == 0.5 + + +# ── t1: quota picks a different-region entry for the reserved slot ────────── + +def test_quota_reserves_slot_for_diverse_region(): + e1 = _mk(range(10)) # {0..9} + e2 = _mk(list(range(9)) + [10]) # {0..8,10} — Jaccard(e1)=9/11≈.82 + e3 = _mk(list(range(9)) + [11]) + e4 = _mk(list(range(9)) + [12]) + e5 = _mk(range(20, 30)) # {20..29} — disjoint + out = _select_with_diversity([e1, e2, e3, e4, e5], top_n=3, threshold=0.8) + + assert out == [e1, e2, e5] # slots 1,2 = best; slot 3 = elsewhere + assert e5['diverse'] is True + assert e1['diverse'] is False and e2['diverse'] is False + + +# ── t2: all similar → fallback to plain top-3, nothing marked diverse ─────── + +def test_all_similar_falls_back_to_plain(): + es = [_mk(list(range(9)) + [10 + i]) for i in range(5)] # all ≈ {0..8}+1 + out = _select_with_diversity(es, top_n=3, threshold=0.8) + assert out == es[:3] # identical to plain slicing + assert all(e['diverse'] is False for e in out) # no genuine diversity pick + + +# ── t5: threshold→0.99 makes ~everything "dissimilar" → plain slicing ─────── + +def test_high_threshold_behaves_like_plain_slice(): + e1 = _mk(range(10)) + e2 = _mk(list(range(9)) + [10]) + e3 = _mk(list(range(9)) + [11]) + e4 = _mk(range(20, 30)) + plain = [e1, e2, e3, e4][:3] + out = _select_with_diversity([e1, e2, e3, e4], top_n=3, threshold=0.99) + # Same ENTRIES as a plain top-3 slice (0.99 admits the next-best). + assert out == plain + + +def test_never_returns_fewer_than_pool(): + e1, e2 = _mk(range(10)), _mk(range(20, 30)) + assert _select_with_diversity([e1, e2], top_n=5, threshold=0.8) == [e1, e2] + assert _select_with_diversity([], top_n=3, threshold=0.8) == [] + + +# ── t3: diversity_threshold=None is byte-compatible (no 'diverse' key) ────── + +def _make_backend(): + edges = [] + for base in (0, 24): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges.append((top[j], top[j + 1])) + edges.append((bot[j], bot[j + 1])) + for j in range(8): + edges.append((top[j], brg[j])) + edges.append((brg[j], bot[j])) + g = rustworkx.PyDiGraph() + for i in range(48): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x'], name='b') + + +class _Props: + def readout_error(self, q): + return 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def _all_entries(res): + return [e for entries in res['strata'].values() for e in entries] + + +def test_none_threshold_is_byte_compatible(): + bk, pr = _make_backend(), _Props() + res = sweep_ancilla_layouts(8, bk, pr, min_bridges=1, top_n=3, + shuffle_seed=None, diversity_threshold=None) + assert all('diverse' not in e for e in _all_entries(res)) # no key added + + +def test_threshold_set_marks_entries(): + bk, pr = _make_backend(), _Props() + res = sweep_ancilla_layouts(8, bk, pr, min_bridges=1, top_n=3, + shuffle_seed=None, diversity_threshold=0.8) + # Every returned entry now carries the (bool) diverse flag. + entries = _all_entries(res) + assert entries and all('diverse' in e for e in entries) diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index e6d9257..d400774 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -317,6 +317,7 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.lucj_min_ancilla.value = 2 b.lucj_top_n.value = 7 # (K4) non-default top_n b.lucj_search_cap.value = 5000 # (S4) non-default cap + b.chk_lucj_diverse.value = True # (D2) non-default diversity b.btn_lucj_run.click() # local sweep local_kw = calls[-1] @@ -324,12 +325,13 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.btn_scan_qpus.click() # scan (per-target) scan_kw = calls[0] - keys = ('min_bridges', 'top_n', 'hybrid', 'mapping_cap') + keys = ('min_bridges', 'top_n', 'hybrid', 'mapping_cap', 'diversity_threshold') assert {k: local_kw.get(k) for k in keys} == {k: scan_kw.get(k) for k in keys} assert scan_kw['hybrid'] is False # honored, not the engine default - # (K4/S4) Show-top and Search-cap reach BOTH paths — parity by construction. + # (K4/S4/D2) Show-top, Search-cap, diversity reach BOTH paths — parity. assert local_kw['top_n'] == 7 and scan_kw['top_n'] == 7 assert local_kw['mapping_cap'] == 5000 and scan_kw['mapping_cap'] == 5000 + assert local_kw['diversity_threshold'] == 0.8 and scan_kw['diversity_threshold'] == 0.8 # ── P2: active backend skipped-with-reference (never re-searched) ─────────── diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index a8d8f54..d5f148c 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -277,3 +277,30 @@ def test_sweep_mode_label(): 2: {'n_direct': 0, 'n_derived': 3}, 1: {'n_direct': 0, 'n_derived': 4}}} assert _sweep_mode_label(dv) == 'derived-only' + + +# ── D2: diverse entries get a "· alt region" dropdown-label suffix ────────── + +def test_diverse_entry_label_suffix(builder, monkeypatch): + def _fake(*a, **k): + def e(anc, prod, diverse): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': anc, 'bridge_slots': tuple(range(0, 4 * len(anc), 4)), + 'product_score': prod, 'additive_score': 0.5, + 'lqs_circuit': prod, 'rank_in_stratum': 1, 'source': 'derived', + 'diverse': diverse} + return { + 'strata': {2: [dict(e([4, 5], 0.30, False), rank_in_stratum=1), + dict(e([6, 7], 0.28, True), rank_in_stratum=2)]}, + 'k_max_effective': 2, 'min_bridges': 2, 'vf2_truncated': False, + 'n_raw_embeddings': 5, 'n_candidates_scored': 5, + 'per_stratum': {2: {'n_direct': 0, 'n_derived': 2, + 'truncated': False, 'shuffled': False}}, + 'mapping_cap': 2000, + } + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", _fake) + b = builder + b.btn_lucj_run.click() + labels = _labels(b.dd_lucj_layout) + assert any('· alt region' in lab for lab in labels) # the diverse one + assert sum('· alt region' in lab for lab in labels) == 1 # only it From b7d56202f38b545e4993a1898ef9078ea67ed2ee Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 13 Jul 2026 22:44:08 -0400 Subject: [PATCH 19/66] Clean up comments into self-contained documentation --- qpu_mapper/ancilla_sweep.py | 23 +++---- qpu_mapper/auto_lucj.py | 2 +- qpu_mapper/data.py | 4 +- qpu_mapper/props_shim.py | 6 +- qpu_mapper/stability_filter.py | 2 +- qpu_mapper/ui/builder.py | 12 ++-- qpu_mapper/ui/inter_qpu.py | 26 ++++---- qpu_mapper/ui/lucj_panel.py | 100 +++++++++++++++---------------- tests/test_ancilla_sweep.py | 33 +++++----- tests/test_cascade.py | 17 +++--- tests/test_diversity.py | 10 ++-- tests/test_export_layout_io.py | 2 +- tests/test_inter_qpu_handoff.py | 10 ++-- tests/test_props_shim.py | 24 ++++---- tests/test_qpu_scan.py | 12 ++-- tests/test_scan_notices.py | 10 ++-- tests/test_scan_ui.py | 27 +++++---- tests/test_scoring_core.py | 8 +-- tests/test_shuffle_search.py | 10 ++-- tests/test_stability_filter.py | 16 ++--- tests/test_stability_ui.py | 14 ++--- tests/test_sweep_ui.py | 24 ++++---- tests/test_temporal_anchoring.py | 8 +-- tests/test_ui_cleanup.py | 8 +-- 24 files changed, 206 insertions(+), 202 deletions(-) diff --git a/qpu_mapper/ancilla_sweep.py b/qpu_mapper/ancilla_sweep.py index c7deb91..d5e338e 100644 --- a/qpu_mapper/ancilla_sweep.py +++ b/qpu_mapper/ancilla_sweep.py @@ -108,7 +108,7 @@ # per-stratum seed from (backend_name, norb, k). None disables the shuffle # (natural node-index order == pre-shuffle behaviour, byte-compatible). An # explicit int is combined with k so strata still sample differently yet -# reproducibly. See S1 in the SHUFFLED SEARCH ORDER change. +# reproducibly. See the per-stratum shuffled-search-graph construction below. _AUTO_SHUFFLE = object() @@ -249,7 +249,7 @@ def sweep_ancilla_layouts(norb, backend, props, *, qubit ids ride in node data and are recovered order-independently via ``_key_to_phys`` — no relabel leakage. diversity_threshold: when a float in (0, 1), rebalance each stratum's - top_n for REGION diversity (D1). After the displayed-metric + top_n for REGION diversity. After the displayed-metric ranking, the first ceil(top_n/2) slots keep the best entries absolutely; each remaining slot takes the best entry whose Jaccard similarity — ``|A∩B|/|A∪B|`` over the full qubit set (alpha ∪ beta ∪ @@ -313,7 +313,7 @@ def _key_to_phys(k): def _key_to_phys(k): return k - # ---- 1b. Per-stratum shuffled search graph (S1) ----------------------- + # ---- 1b. Per-stratum shuffled search graph ---------------------------- # The template (WHAT to search for) is always built on the natural # `search_graph`, so k_max_effective and every k' template are stable and # seed-independent. Only the TARGET graph handed to VF2 is permuted, which @@ -535,7 +535,7 @@ def _add_variant(edata, k, source): if any(v is None for v in lay): continue edata = _embedding_data(lay, nb_k) - # (K1) CASCADE: this direct k'-embedding seeds its OWN stratum + # CASCADE: this direct k'-embedding seeds its OWN stratum # (source 'vf2') AND every stratum below it via the prefix rule # (source 'derived'). So a region that only a k'-search reaches # — never enumerated at k_max — still populates all lower @@ -550,20 +550,21 @@ def _add_variant(edata, k, source): # Aggregate truncation for the existing banner (k_max OR any direct pass). vf2_truncated = any(m['truncated'] for m in per_stratum.values()) - # ---- 7. Slice each stratum by the DISPLAYED metric (W1) --------------- + # ---- 7. Slice each stratum by the DISPLAYED metric -------------------- # product_score (template scale) is the cheap PRE-FILTER for the pool, but # the final slice must be chosen by the metric the UI shows (lqs_circuit). # The two scales diverge, so slicing to top_n by product_score BEFORE # circuit-scoring can drop the true circuit-best below the line unseen — - # the live "3->49.3% . 2->40.8%" monotonicity violation. + # a monotonicity violation observed on hardware where a stratum's displayed + # best fell as k decreased (e.g. "3->49.3% . 2->40.8%"). # # Fix: circuit-score a WIDENED window = the top W by product_score # (W = max(top_n*5, 25)) PLUS, guaranteed regardless of rank, the # prefix-child of every higher stratum's already-selected winner (the # monotonicity anchors — the cascade already generated them, so they live # in this pool). Then rank the scored window by lqs_circuit (None sinks) - # and slice to top_n. With no circuit scorer the pre-A2 product-sliced - # shape is preserved byte-for-byte. + # and slice to top_n. With no circuit scorer the product-sliced shape is + # preserved byte-for-byte (the historical default, before circuit scoring). strata = {} # higher_winners: (chain_fs, ancillas) of every selected entry in a higher # stratum, so stratum k can pull in each one's k-prefix child as an anchor. @@ -574,7 +575,7 @@ def _add_variant(edata, k, source): key=lambda kv: kv[1]['product_score'], reverse=True) if circuit_score_fn is None: - # Byte-compatible pre-A2 path: product slice, no lqs_circuit. + # Byte-compatible product-only path: product slice, no lqs_circuit. if diversity_threshold is None: entries = [e for _, e in by_product[:top_n]] else: @@ -613,7 +614,7 @@ def _add_variant(edata, k, source): else 0.0, e['product_score']), reverse=True) - # (D1) Diversity quota: reserve later slots for different-region + # Diversity quota: reserve later slots for different-region # layouts (Jaccard <= threshold), applied AFTER the displayed-metric # ranking, BEFORE rank numbering. None → exact top-N slice. if diversity_threshold is None: @@ -637,7 +638,7 @@ def _add_variant(edata, k, source): 'n_candidates_scored': n_candidates_scored, 'excluded_qubits': excluded_sorted, 'per_stratum': per_stratum, - # (K3) The ACTUAL VF2 cap, so the truncation banner can name it + # The ACTUAL VF2 cap, so the truncation banner can name it # ("truncated at 2000 mappings") instead of n_raw_embeddings, and # per_stratum[k]['truncated'] says WHICH strata hit it. 'mapping_cap': cap, diff --git a/qpu_mapper/auto_lucj.py b/qpu_mapper/auto_lucj.py index 568b1a1..f0113cd 100644 --- a/qpu_mapper/auto_lucj.py +++ b/qpu_mapper/auto_lucj.py @@ -777,7 +777,7 @@ def get_multi_circuit_layouts( # ═══════════════════════════════════════════════════════════════════════ -# JOINT RE-OPTIMIZATION (F3) +# JOINT RE-OPTIMIZATION # ═══════════════════════════════════════════════════════════════════════ def reoptimize_after_change( diff --git a/qpu_mapper/data.py b/qpu_mapper/data.py index dda6ed1..261cd5b 100644 --- a/qpu_mapper/data.py +++ b/qpu_mapper/data.py @@ -999,8 +999,8 @@ def auto_load_recent_history(state, days=14, min_cached_threshold=5): 'cache' — cache had ≥ threshold; only cached entries loaded. 'fetch' — cache had < threshold; fetch_calibration_history ran. """ - # Spec: don't touch state if the user has already populated - # cal_history via Multi-day mode before this auto-load fires. + # Don't touch state if the user has already populated cal_history via + # Multi-day mode before this auto-load fires. if state.cal_history_dates: return len(state.cal_history_dates), 'noop' diff --git a/qpu_mapper/props_shim.py b/qpu_mapper/props_shim.py index e826e0e..1c277cd 100644 --- a/qpu_mapper/props_shim.py +++ b/qpu_mapper/props_shim.py @@ -103,7 +103,7 @@ def __init__(self, qubit_props, gate_props, edges, # C1 wrapper's EXACT edge surface — every coupling in the backend's # own map (both directions, as edges_list carries them), paired # positionally. Deduping here would halve the gate factors and inflate - # the product (SYM-1). + # the product. self._edges = [(int(u), int(v)) for (u, v) in edges] self._gate_arr = gate_arr # Deduped map for the direction-insensitive gate_error() the sweep's @@ -194,7 +194,7 @@ def _live_stamp(): return dt.strftime('%H:%M') if hasattr(dt, 'strftime') else str(dt) def _from_state(): - """(V1) The active backend is scored on the SESSION'S CURRENT props — + """The active backend is scored on the SESSION'S CURRENT props — the same qubit_props_data/gate_props_data/edges_list the C1 box reads — so the scan row for the active backend equals the C1 box exactly, live. Returns None if the session hasn't loaded calibration yet.""" @@ -211,7 +211,7 @@ def _from_state(): def get_props(backend): backend_name = getattr(backend, 'name', None) - # (V1) Active backend → live session props (that IS live). + # Active backend → live session props (that IS live). if (backend_name is not None and backend_name == getattr(state, 'active_backend_name', None)): live = _from_state() diff --git a/qpu_mapper/stability_filter.py b/qpu_mapper/stability_filter.py index 68cd907..29afe12 100644 --- a/qpu_mapper/stability_filter.py +++ b/qpu_mapper/stability_filter.py @@ -210,7 +210,7 @@ def _plain(): # today=None keeps the now-anchored latest-window behaviour (live mode). volatility = compute_qubit_volatility(history, window_days, today=today) - # (F2) Quality floor on the CURRENT props (independent of history). + # Quality floor on the CURRENT props (independent of history). floor_qubits = [] if quality_sigma is not None: n_q = _n_qubits_from_history(history) diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index 68360e2..6d50eb0 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -324,7 +324,7 @@ def _run_pipeline(self): lucj_multi_dropdowns=self._lucj_multi_dropdowns, refresh=self._refresh, get_export=self._get_export, update_view=lambda: self._update_view(), chk_line_only=self.chk_line_only, - # Multi-QPU scan (B2/B3/B4). + # Multi-QPU scan. btn_scan_qpus=self.btn_scan_qpus, chk_scan_other_families=self.chk_scan_other_families, btn_scan_clear=self.btn_scan_clear, @@ -333,7 +333,7 @@ def _run_pipeline(self): scan_spawn_bg=default_spawn_bg, scan_marshal=marshal_to_main, inter_qpu_handoff=self._inter_qpu_handoff, - # Stability filter (V1/V2/V3). + # Stability filter. chk_stability_filter=self.chk_stability_filter, rb_stability_window=self.rb_stability_window_auto, ft_stability_threshold=self.ft_stability_threshold, @@ -1227,7 +1227,7 @@ def _build_auto_lucj_widgets(self, W): style={'description_width': '110px'}, tooltip='Sweep all counts from max down to this floor ' '(0 = auto)') - # (K4) How many candidates to keep/show per ancilla count. Wired to the + # How many candidates to keep/show per ancilla count. Wired to the # sweep's top_n through _sweep_kwargs_from_ui, so the scan inherits it. self.lucj_top_n = BoundedIntText( value=3, min=1, max=25, @@ -1235,7 +1235,7 @@ def _build_auto_lucj_widgets(self, W): layout=Layout(width='220px'), style={'description_width': '110px'}, tooltip='candidates shown per ancilla count') - # (S4) Advanced: the VF2 mapping cap. Raise to trade time for + # Advanced: the VF2 mapping cap. Raise to trade time for # exhaustiveness (default matches auto_lucj._MAX_RAW_VF2_MAPPINGS). self.lucj_search_cap = BoundedIntText( value=2000, min=100, max=20000, step=500, @@ -1254,7 +1254,7 @@ def _build_auto_lucj_widgets(self, W): layout=W, tooltip='adds a direct search per k — complete but slower; ' 'off = fast derivation from k_max only') - # (D2) Region diversity in the top-N slice. Default OFF. + # Region diversity in the top-N slice. Default OFF. self.chk_lucj_diverse = Checkbox( value=False, description='Prefer diverse regions', @@ -1283,7 +1283,7 @@ def _build_auto_lucj_widgets(self, W): style={'description_width': '90px'}, tooltip='Volatility score = max/median − 1; higher threshold = ' 'more tolerant (fewer qubits excluded)') - # (F3) Quality floor: also exclude STABLY-terrible qubits — current + # Quality floor: also exclude STABLY-terrible qubits — current # readout outliers the volatility score is blind to. σ from device mean. self.ft_stability_floor = BoundedFloatText( value=3.0, min=0.0, max=20.0, step=0.5, diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index 1c79a35..bd470a2 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -94,9 +94,9 @@ def setup_inter_qpu(ctx): _sidebar2 = [None] # QPU 2 sidebar VBox _zoom2 = [None] # QPU 2 zoom toolbar _dispose2 = [None] # callable that unobserves all QPU 2 widgets - _connect_in_flight = [False] # (O4) race guard: one auto-connect at a time + _connect_in_flight = [False] # race guard: one auto-connect at a time - # (O2) Background runner for the ONE-CLICK auto-connect. The Connect-QPU2 + # Background runner for the ONE-CLICK auto-connect. The Connect-QPU2 # button handler is SYNCHRONOUS + network-touching; the scan pattern # (default_spawn_bg + marshalled on_done/on_error) keeps the kernel # responsive. Injectable via ctx for headless tests. @@ -260,7 +260,7 @@ def refresh_qpu1_label(): toggle.options = options toggle.value = saved_value - # ── B5: remote-candidate handoff (scan → inter-QPU) ───────── + # ── remote-candidate handoff (scan → inter-QPU) ───────── handoff_cell = getattr(ctx, 'handoff_cell', None) def _apply_candidate_to_state(s2, candidate): @@ -293,7 +293,7 @@ def stage_remote_candidate(backend_name, candidate): with contextlib.suppress(Exception): dd_backend_qpu2.value = backend_name _pending_handoff[0] = (backend_name, candidate) - # (C3) Prominent one-liner explaining the half-open state until the + # Prominent one-liner explaining the half-open state until the # user clicks Connect. Replaced by the connect status once connected. staged_html = ( f"
{esc(str(backend_name))}.
") return - # (O4) A connect already in flight → the staging above is enough; + # A connect already in flight → the staging above is enough; # don't launch a second connect. if _connect_in_flight[0]: return diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 8153e00..800477c 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -45,7 +45,7 @@ def _format_best_per_k(strata): def _sweep_mode_label(res): - """(H2) 'direct+derived' when any lower stratum got a direct-VF2 hit, + """'direct+derived' when any lower stratum got a direct-VF2 hit, else 'derived-only'.""" kmax = res.get('k_max_effective') ps = res.get('per_stratum', {}) @@ -55,7 +55,7 @@ def _sweep_mode_label(res): def _format_sweep_status(res): - """One-line sweep summary (M2): 'Sweep: k=6..3 · 214 embeddings · + """One-line sweep summary: 'Sweep: k=6..3 · 214 embeddings · best per k: ...'. All interpolations esc()'d.""" k_range = f"{res['k_max_effective']}..{res['min_bridges']}" emb = f"{res['n_raw_embeddings']:,}" @@ -65,7 +65,7 @@ def _format_sweep_status(res): def _k_cap_phrase(norb, k_effective): - """(N1) 'k capped at E (requested R)' when the geometric request + """'k capped at E (requested R)' when the geometric request ceil(norb/4) exceeds what actually fit; '' otherwise. Pure metadata — replaces the operator's need to read the repeated stderr warning.""" request = (norb + 3) // 4 @@ -75,7 +75,7 @@ def _k_cap_phrase(norb, k_effective): class _ScanNoticeCapture(logging.Handler): - """(N2) Captures WARNING+ records off the 'qpu_mapper' logger during a + """Captures WARNING+ records off the 'qpu_mapper' logger during a scan, tagging each with the current backend context. emit() never raises out — a logging hiccup must not break the scan.""" @@ -238,7 +238,7 @@ def _on_lucj_layout_select(change): f"α: {', '.join(str(q) for q in entry['alpha'])}
" f"β: {', '.join(str(q) for q in entry['beta'])}" ) - # (A2) The LQS shown here is the circuit-level score — the same number + # The LQS shown here is the circuit-level score — the same number # the Estimated Layout-Quality box reports. '(template)' flags the # internal heuristic used only when circuit scoring is unavailable. with contextlib.suppress(Exception): @@ -268,7 +268,7 @@ def _seed_layout_dropdown(entries, dd_opts): if entries: _apply_lucj_layout(entries[0]) - # ── A2: circuit-level LQS for a sweep candidate ────────────── + # ── circuit-level LQS for a sweep candidate ────────────── def _circuit_score(entry): """Score a sweep candidate with the SAME path as the Estimated Layout-Quality box: build a scratch layout from the candidate and @@ -305,7 +305,7 @@ def _annotate_circuit_lqs(res): # ── Temporal anchoring: one epoch per search ───────────────────── def _selected_date_anchor(): - """(F2) The selected calibration's date 'YYYY-MM-DD' when a PAST date + """The selected calibration's date 'YYYY-MM-DD' when a PAST date is active, else None (live). Used to anchor the stability window and the epoch-mixing header note to the user's chosen date.""" if getattr(state, 'time_mode', 'live') == 'live': @@ -314,7 +314,7 @@ def _selected_date_anchor(): return ts[:10] if isinstance(ts, str) and len(ts) >= 10 else None def _local_scoring_props(): - """(F1) Pre-rank on the SAME epoch as the C1 circuit-score — the + """Pre-rank on the SAME epoch as the C1 circuit-score — the selected date's arrays — so product_score and lqs_circuit never mix epochs inside one search. Reuses the scan's CachedPropsShim adapter. Falls back to live initial_props if the arrays aren't loaded / mis-shape @@ -332,11 +332,11 @@ def _local_scoring_props(): except Exception: return state.initial_props - # ── P1: SINGLE SOURCE of sweep params — local AND scan read this ── + # ── SINGLE SOURCE of sweep params — local AND scan read this ── def _sweep_kwargs_from_ui(): """The one place sweep parameters are derived from the UI. Both the local sweep and every scan per-target call pass exactly this, so the - two can never diverge again (the tonight bug).""" + two can never diverge again (a divergence here silently skews rankings).""" min_val = lucj_min_ancilla.value min_bridges = None if (min_val is None or min_val <= 0) else min_val top_val = lucj_top_n.value @@ -346,12 +346,12 @@ def _sweep_kwargs_from_ui(): 'top_n': top_val if (top_val and top_val >= 1) else 3, 'hybrid': chk_deep_search.value, 'mapping_cap': cap_val if (cap_val and cap_val >= 1) else None, - # (D2) 0.8 default when ON; None → exact top-N (byte-compatible). + # 0.8 default when ON; None → exact top-N (byte-compatible). 'diversity_threshold': 0.8 if chk_lucj_diverse.value else None, } # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the - # active backend's reference in the scan table (P2), so the scan never + # active backend's reference in the scan table, so the scan never # re-searches self yet keeps the reference point. _local_best_lqs = [None] @@ -411,13 +411,13 @@ def _generate_legacy(norb, requested_ancillas): def _generate_sweep(norb): from ..ancilla_sweep import sweep_ancilla_layouts - # P1: exact same params the scan uses (min_bridges / top_n / hybrid). + # exact same params the scan uses (min_bridges / top_n / hybrid). kwargs = _sweep_kwargs_from_ui() - # F1: pre-rank on the same epoch as the circuit-score (selected date). + # pre-rank on the same epoch as the circuit-score (selected date). scoring_props = _local_scoring_props() - anchor = _selected_date_anchor() # F2: window/header anchor - # V2: opt-in stability filter (drop-in superset of the plain sweep). + anchor = _selected_date_anchor() # window/header anchor + # opt-in stability filter (drop-in superset of the plain sweep). history = getattr(state, 'cal_history', None) if _stability_filter_active() and history: from ..stability_filter import sweep_with_stability @@ -430,13 +430,13 @@ def _generate_sweep(norb): quality_sigma=_floor_sigma()) _render_stability_banner(res.get('stability'), norb, anchor=anchor) # The frozen stability engine can't take circuit_score_fn — fill - # circuit-level LQS on its survivors here (A2). + # circuit-level LQS on its survivors here. _annotate_circuit_lqs(res) else: res = sweep_ancilla_layouts( norb, state.active_backend, scoring_props, - circuit_score_fn=_circuit_score, # A2: aligned circuit LQS - **kwargs) # P1 single source (incl. hybrid) + circuit_score_fn=_circuit_score, # aligned circuit LQS + **kwargs) # single source (incl. hybrid) if _stability_filter_active(): # Checkbox on but no history dict → skipped note. _render_stability_banner(None, norb) @@ -453,7 +453,7 @@ def _generate_sweep(norb): for entry in strata[k]: pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - alt = " · alt region" if entry.get('diverse') else "" # (D2) + alt = " · alt region" if entry.get('diverse') else "" # region-diversity flag dd_opts.append(( f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" f"{alt}", @@ -468,7 +468,7 @@ def _generate_sweep(norb): _seed_layout_dropdown(flat, dd_opts) - # Truncation banner (U5/K3): visible only when the VF2 cap was hit. + # Truncation banner: visible only when the VF2 cap was hit. # Name the REAL cap (mapping_cap) and WHICH strata truncated — not # k_max's n_raw_embeddings, which is an embedding count, not the cap. if res['vf2_truncated']: @@ -487,7 +487,7 @@ def _generate_sweep(norb): else: lbl_lucj_trunc.value = "" - # One-line summary (M2): per-stratum LQS gradient, NOT a single + # One-line summary: per-stratum LQS gradient, NOT a single # size-biased "best LQS" (product_score always favours fewer bridges). if flat: cap = _k_cap_phrase(norb, res.get('k_max_effective')) @@ -539,7 +539,7 @@ def _on_lucj_generate(b): btn_lucj_run.on_click(_on_lucj_generate) - # ── M1: sweep mode always scores → grey out the score checkbox ──── + # ── sweep mode always scores → grey out the score checkbox ──── def _on_ancilla_mode_change(change=None): # 'Auto' (-1) == sweep mode; the engine always computes LQS there, # so the legacy "Score layouts" toggle is meaningless. @@ -551,7 +551,7 @@ def _on_ancilla_mode_change(change=None): lucj_ancilla_dd.observe(_on_ancilla_mode_change, names='value') _on_ancilla_mode_change() # set initial state (default -1 → disabled) - # ── B2/B3/B4: Multi-QPU scan ───────────────────────────────── + # ── Multi-QPU scan ───────────────────────────────── btn_scan_qpus = ctx.btn_scan_qpus chk_scan_other_families = ctx.chk_scan_other_families btn_scan_clear = ctx.btn_scan_clear @@ -561,7 +561,7 @@ def _on_ancilla_mode_change(change=None): scan_marshal = ctx.scan_marshal inter_qpu_handoff = ctx.inter_qpu_handoff # shared cell → stage hook - # ── Stability filter (V1/V2/V3) ────────────────────────────── + # ── Stability filter ────────────────────────────── chk_stability_filter = ctx.chk_stability_filter rb_stability_window = ctx.rb_stability_window ft_stability_threshold = ctx.ft_stability_threshold @@ -569,7 +569,7 @@ def _on_ancilla_mode_change(change=None): stability_ctrl_box = ctx.stability_ctrl_box def _floor_sigma(): - """(F3) Quality-floor σ from the UI; 0 → None (floor off). Read at + """Quality-floor σ from the UI; 0 → None (floor off). Read at each sweep_with_stability call site (like window/threshold), so the local sweep and the scan share it by construction.""" v = getattr(ft_stability_floor, 'value', None) @@ -591,10 +591,10 @@ def _stability_filter_active(): and not chk_stability_filter.disabled) def _render_stability_banner(stab, norb, anchor=None): - """Render res['stability'] (V2): filtered / relaxed / unavailable. + """Render res['stability']: filtered / relaxed / unavailable. `anchor` (a 'YYYY-MM-DD' selected date) names the window's upper bound - when a past date is active (F2).""" - # F2: "14d before " when a past date anchors the window, else "14d". + when a past date is active.""" + # "14d before " when a past date anchors the window, else "14d". def _window_txt(): wd = esc(str(stab.get('window_days'))) return (f"{wd}d before {esc(anchor)}" if anchor else f"{wd}d") @@ -614,7 +614,7 @@ def _window_txt(): f"(most-volatile still excluded)") else: total = len(stab.get('excluded_final', [])) - m_floor = stab.get('n_floor_excluded', 0) # (F3) outliers + m_floor = stab.get('n_floor_excluded', 0) # outliers n_vol = total - m_floor floor_txt = f" + {esc(str(m_floor))} outlier" if m_floor else "" lbl_lucj_stability.value = ( @@ -667,7 +667,7 @@ def _fn(entry): return _fn def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): - """(A3/S2) Fill each scan entry's lqs_circuit with THAT backend's + """Fill each scan entry's lqs_circuit with THAT backend's circuit-level fidelity, so the scan table/dropdowns display the same scale as the local sweep. Runs on the worker thread (props are cache-first). A per-backend failure leaves lqs_circuit as-is (None → @@ -680,7 +680,7 @@ def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): props = get_props(get_backend(r['name'])) except Exception: continue - # (V2) Surface the calibration provenance the shim used. + # Surface the calibration provenance the shim used. r['vintage'] = getattr(props, 'vintage', None) scorer = _scan_circuit_score(props) for k, entries in sweep.get('strata', {}).items(): @@ -689,7 +689,7 @@ def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): try: e['lqs_circuit'] = scorer(e) except Exception as exc: - # (F3) Annotation failure is data absence — surface + # Annotation failure is data absence — surface # it in the notices with backend + stratum + reason, # never a silent 0.0. e['lqs_circuit'] = None @@ -697,7 +697,7 @@ def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): "k=%d: %s", r['name'], k, exc) def _scan_backends(eligible, norb, get_backend, get_props, use_filter): - """The SINGLE handler-side scan path (U2). The per-backend isolation / + """The SINGLE handler-side scan path. The per-backend isolation / progress / best-LQS ranking loop lives ONCE, in qpu_scan.scan_qpus; we inject a ``sweep_fn`` closure that carries the only handler-specific parts: the SAME params as the local sweep (_sweep_kwargs_from_ui, incl. @@ -713,7 +713,7 @@ def _scan_backends(eligible, norb, get_backend, get_props, use_filter): kwargs = _sweep_kwargs_from_ui() window = rb_stability_window.value threshold = ft_stability_threshold.value - floor_sigma = _floor_sigma() # (F3) scan inherits the floor + floor_sigma = _floor_sigma() # scan inherits the floor def _sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): # min_bridges/top_n arrive from scan_qpus (they equal kwargs); the @@ -734,7 +734,7 @@ def _sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): return res def _progress(name, status, detail=''): - # Preserve the pre-U2 'start' detail (scan_qpus emits it empty). + # Preserve the 'start' detail (scan_qpus emits it empty). if status == 'start' and not detail: detail = 'fetching calibration…' _on_scan_progress(name, status, detail) @@ -756,7 +756,7 @@ def _progress(name, status, detail=''): _STATUS_ICON = {'start': '⏳', 'ok': '✓', 'skipped': '·', 'error': '✗'} def _clear_scan_results(): - # (C2) Full reset — table, per-QPU dropdowns, notices, progress line, + # Full reset — table, per-QPU dropdowns, notices, progress line, # and the scan button. No ghost dropdown state survives. scan_results_box.children = [] lbl_scan_progress.value = "" @@ -798,7 +798,7 @@ def _entry_label(entry): k = len(entry['ancillas']) pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - alt = " · alt region" if entry.get('diverse') else "" # (D2) + alt = " · alt region" if entry.get('diverse') else "" # region-diversity flag return f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}{alt}" def _render_targets(targets): @@ -826,7 +826,7 @@ def _stage_handoff(backend_name, candidate): hook(backend_name, candidate) def _vintage_cell(vintage): - """(L2) Calibration provenance. Scan scoring is always LIVE now, so + """Calibration provenance. Scan scoring is always LIVE now, so every remote row is 'live · ' by construction. The old cached-snapshot stale-badge path (utc parse + >24h compare) is gone — the scan never scores from a cached snapshot.""" @@ -846,7 +846,7 @@ def _render_results(scan_result): "stability" "calib") body = [] - # (P2) Active backend reference row — greyed, quotes the LOCAL number, + # Active backend reference row — greyed, quotes the LOCAL number, # never re-searched. Keeps the cross-QPU reference point at zero cost. active = _scan.get('active') if active: @@ -886,10 +886,10 @@ def _render_results(scan_result): f"" f"{vcell}") else: - # (F3) Summary best-LQS = MAX circuit LQS over ALL entries, + # Summary best-LQS = MAX circuit LQS over ALL entries, # ignoring None (annotation failed) and NOT just the k_max # stratum #1 — quoting k_max quoted its 0.0 dead-edge wall - # while lower strata were fine (SYM-2). Fall back to the + # while lower strata were fine. Fall back to the # product heuristic (flagged) only when NOTHING was scored. lqs_vals = [e['lqs_circuit'] for _entries in r['sweep']['strata'].values() @@ -918,7 +918,7 @@ def _render_results(scan_result): f"{vcell}") children = [HTML(head + "".join(body) + "")] - # F3: when a PAST date is active locally, the local backend was scored + # when a PAST date is active locally, the local backend was scored # on that date but remote backends are scored LIVE — say so, no silent # mixing. _anchor = _selected_date_anchor() @@ -972,7 +972,7 @@ def _cb(change): scan_results_box.children = children def _append_notices(notices): - # (N2) Collapsible "⚠ notices (N)" under the results table: + # Collapsible "⚠ notices (N)" under the results table: # deduplicated messages (message → ×count), grouped by backend # context. Hidden when empty. if not notices: @@ -1024,12 +1024,12 @@ def _on_scan_click(b): except Exception: family = None - _clear_scan_results() # (C2) drop any stale results + _clear_scan_results() # drop any stale results targets = list_scan_targets( state, norb, same_family_as=family, include_other_families=chk_scan_other_families.value) - # (P2) Never re-search the active backend — mark it skipped and quote + # Never re-search the active backend — mark it skipped and quote # the local result instead. No sweep, no fetch for it. active_name = getattr(state, 'active_backend_name', None) _scan['active'] = None @@ -1056,7 +1056,7 @@ def _on_scan_click(b): and chk_scan_stability.value) def _work(): - # (N2/N3) Capture WARNING+ off 'qpu_mapper' for the scan's + # Capture WARNING+ off 'qpu_mapper' for the scan's # duration and stop them leaking under the cell (propagate=False). # Attach in try, restore BOTH in finally (done + error paths). logger = logging.getLogger('qpu_mapper') @@ -1068,10 +1068,10 @@ def _work(): except Exception: pass try: - # (P1) One scan path, one param source — forwards hybrid. + # One scan path, one param source — forwards hybrid. result = _scan_backends(eligible, norb, get_backend, get_props, use_scan_filter) - # (A3/S2) Circuit-level LQS per backend — one scale everywhere. + # Circuit-level LQS per backend — one scale everywhere. _annotate_scan_circuit_lqs(result, get_backend, get_props) return (result, list(handler.records)) finally: @@ -1274,7 +1274,7 @@ def _on_change(change): btn_lucj_multi.on_click(_on_lucj_multi) - # ── Re-optimization (F3) ───────────────────────────────────── + # ── Re-optimization ───────────────────────────────────── def _reoptimize_downstream(changed_idx): try: from ..auto_lucj import reoptimize_after_change diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index a982b2b..252527d 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -119,7 +119,7 @@ def props(): return FakeProps() -# ── t1: shape ────────────────────────────────────────────────────────────── +# ── shape ────────────────────────────────────────────────────────────── def test_shape(backend, props): res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) @@ -143,12 +143,13 @@ def test_shape(backend, props): range(1, len(entries) + 1)) -# ── t2: regression — the good-region k-1 layout is derived for free ───────── +# ── regression — the good-region k-1 layout is derived for free ───────── def test_kminus1_variant_present(backend, props): - """The user's observation: an independent per-k search misses the k-1 - layout that lives inside the best k-max embedding. With subtraction it is - always in the k-1 pool on the same chain qubits.""" + """Regression: an independent per-k search can miss the k-1 layout that + lives inside the best k-max embedding. Deriving lower-k by bridge + subtraction guarantees it is always in the k-1 pool on the same chain + qubits (guards the geographic-prefix miss).""" res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) top = res['strata'][2][0] # best intact k=2 layout assert top['source'] == 'vf2' @@ -209,10 +210,10 @@ def test_prefix_legacy_equivalence(backend, props): f"bridges of any parent embedding") -# ── A2: circuit_score_fn on the sliced survivors only ────────────────────── +# ── circuit_score_fn on the sliced survivors only ────────────────────── def test_circuit_score_fn_scores_widened_window(backend, props): - """(W1) The scorer runs on a WIDENED window — top W by product_score plus + """The scorer runs on a WIDENED window — top W by product_score plus the monotonicity anchors — not merely the sliced top_n, so the displayed metric's best can't hide below the product_score line. Every survivor still carries lqs_circuit, and the window is bounded (not the whole raw pool).""" @@ -234,7 +235,7 @@ def scorer(entry): def test_circuit_score_error_sinks_below_slice_not_aborts(backend, props): - """(W1) A scorer that raises leaves that candidate lqs_circuit=None; None + """A scorer that raises leaves that candidate lqs_circuit=None; None sinks below the displayed-metric slice, so the sweep completes and its survivors are exactly the successfully-scored candidates.""" raised = [] @@ -256,15 +257,15 @@ def scorer(entry): def test_no_circuit_score_fn_is_byte_compatible(backend, props): - """(A2 default guarantee) Without the scorer, no lqs_circuit key appears — - the dict shape is unchanged from pre-A2.""" + """Default guarantee: without the circuit scorer, no lqs_circuit key + appears — the result dict keeps its original (product-only) shape.""" res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) for entries in res['strata'].values(): for e in entries: assert 'lqs_circuit' not in e -# ── t3: good region wins every stratum ────────────────────────────────────── +# ── good region wins every stratum ────────────────────────────────────── def test_good_region_wins(backend, props): res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=3) @@ -275,7 +276,7 @@ def test_good_region_wins(backend, props): f"stratum k={k} winner {sorted(used)} leaks outside good region") -# ── t4: size-bias guard (within-stratum agreement, across-stratum factor) ─── +# ── size-bias guard (within-stratum agreement, across-stratum factor) ─── def test_size_bias_product_vs_additive(backend, props): res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=1000) @@ -306,7 +307,7 @@ def test_size_bias_product_vs_additive(backend, props): assert ratio == pytest.approx(1.0 / per_ancilla, abs=1e-9) -# ── t5: dedupe ────────────────────────────────────────────────────────────── +# ── dedupe ────────────────────────────────────────────────────────────── def test_dedupe(backend, props): """Alpha/beta-swap embeddings collapse to a single entry per stratum.""" @@ -322,7 +323,7 @@ def test_dedupe(backend, props): assert res['n_raw_embeddings'] > len(res['strata'][2]) -# ── t6: validation ────────────────────────────────────────────────────────── +# ── validation ────────────────────────────────────────────────────────── def test_validation(backend, props): with pytest.raises(ValueError): @@ -336,7 +337,7 @@ def test_validation(backend, props): assert all(e['source'] == 'vf2' for e in res['strata'][2]) -# ── t7: truncation ────────────────────────────────────────────────────────── +# ── truncation ────────────────────────────────────────────────────────── def test_truncation(backend, props): res = sweep_ancilla_layouts(8, backend, props, min_bridges=1, mapping_cap=1) @@ -351,7 +352,7 @@ def test_truncation(backend, props): assert len(e['ancillas']) == k -# ── Hybrid mode (H1) ──────────────────────────────────────────────────────── +# ── Hybrid mode ──────────────────────────────────────────────────────── def _regression_backend(): """A graph where the k_max (2-bridge) template ONLY fits a bad-qubit diff --git a/tests/test_cascade.py b/tests/test_cascade.py index 047a6ae..013fab9 100644 --- a/tests/test_cascade.py +++ b/tests/test_cascade.py @@ -1,4 +1,4 @@ -"""K2 — the cascade invariant (every direct stratum seeds all lower strata). +"""The cascade invariant (every direct stratum seeds all lower strata). Reproduces the live failure shape offline, deterministically, with a real VF2 run on a tiny two-region host: @@ -123,12 +123,13 @@ def test_cascade_delivers_prefix_a_truncated_direct_search_missed(): def test_prefix_child_scores_at_least_its_direct_parent(): res = _run() k2, k1 = _best_good(res, 2), _best_good(res, 1) - # The user's live proof: 67.8% child from a 67.2% parent — dropping one - # bridge's error factors can only raise the product. + # Observed on hardware: a 3-bridge prefix scoring 67.8% from a 4-bridge + # parent at 67.2% — dropping a bridge's error factors can only raise the + # product, so a prefix child is never worse than its direct parent. assert k1['product_score'] >= k2['product_score'] - 1e-12 -# ── K3: the actual cap is surfaced for an honest truncation banner ────────── +# ── the actual cap is surfaced for an honest truncation banner ────────── def test_result_exposes_mapping_cap_for_the_banner(): res = _run() @@ -138,7 +139,7 @@ def test_result_exposes_mapping_cap_for_the_banner(): assert res['per_stratum'][2]['truncated'] is False -# ── W2: monotonicity on the DISPLAYED metric (product ≠ circuit scale) ─────── +# ── monotonicity on the DISPLAYED metric (product ≠ circuit scale) ─────── # # The live bug: strata are sliced to top_n by product_score BEFORE the UI's # lqs_circuit is computed. Where the scales diverge, the true circuit-best @@ -152,7 +153,7 @@ def test_result_exposes_mapping_cap_for_the_banner(): # props error 0.02 → LOW product_score, but the canned circuit scorer rates # G's qubits ~1.0 and D's ~0.5 → G is the DISPLAYED-metric winner. # The k=3 winner is in G; its k=2 prefix (the monotonicity anchor) has product -# BELOW every D decoy, so product-only slicing drops it — W1 must keep it in the +# BELOW every D decoy, so product-only slicing drops it — the widened-window slice must keep it in the # scoring window and surface it once ranked by lqs_circuit. _WG = set(range(100, 127)) # region G ids @@ -225,7 +226,7 @@ def test_slice_contains_higher_winners_prefix_anchor(): k3 = res['strata'][3][0] assert _w2_region(k3) == 'G' chain, anc2 = frozenset(k3['layout']), frozenset(k3['ancillas'][:2]) - # The k=3 winner's k=2 prefix survives into the k=2 slice (W1 anchor), + # The k=3 winner's k=2 prefix survives into the k=2 slice (anchor), # and it is the displayed winner there (circuit >= its k=3 parent). k2_top = res['strata'][2][0] assert frozenset(k2_top['layout']) == chain @@ -236,7 +237,7 @@ def test_slice_contains_higher_winners_prefix_anchor(): def test_product_only_slice_would_have_hidden_the_anchor(): # The divergence is real: without the circuit scorer, product-only slicing # fills the k=2 top_n with the low-error D decoys — the G anchor is nowhere - # in the displayed slice. This is exactly what W1 rescues. + # in the displayed slice. This is exactly what the widened window rescues. res = _w2_run() # no circuit_score_fn regions = [_w2_region(e) for e in res['strata'][2]] assert regions == ['D', 'D', 'D'] diff --git a/tests/test_diversity.py b/tests/test_diversity.py index 571e222..2517b80 100644 --- a/tests/test_diversity.py +++ b/tests/test_diversity.py @@ -1,4 +1,4 @@ -"""D3 — quota-balanced diverse top-N slicing. +"""Quota-balanced diverse top-N slicing. Unit tests for the ranking-agnostic selector `_select_with_diversity` (the quota math) plus an engine byte-compat pin for diversity_threshold=None. @@ -27,7 +27,7 @@ def test_jaccard_basics(): assert _jaccard(frozenset({1, 2, 3}), frozenset({1, 2, 4})) == 0.5 -# ── t1: quota picks a different-region entry for the reserved slot ────────── +# ── quota picks a different-region entry for the reserved slot ────────── def test_quota_reserves_slot_for_diverse_region(): e1 = _mk(range(10)) # {0..9} @@ -42,7 +42,7 @@ def test_quota_reserves_slot_for_diverse_region(): assert e1['diverse'] is False and e2['diverse'] is False -# ── t2: all similar → fallback to plain top-3, nothing marked diverse ─────── +# ── all similar → fallback to plain top-3, nothing marked diverse ─────── def test_all_similar_falls_back_to_plain(): es = [_mk(list(range(9)) + [10 + i]) for i in range(5)] # all ≈ {0..8}+1 @@ -51,7 +51,7 @@ def test_all_similar_falls_back_to_plain(): assert all(e['diverse'] is False for e in out) # no genuine diversity pick -# ── t5: threshold→0.99 makes ~everything "dissimilar" → plain slicing ─────── +# ── threshold→0.99 makes ~everything "dissimilar" → plain slicing ─────── def test_high_threshold_behaves_like_plain_slice(): e1 = _mk(range(10)) @@ -70,7 +70,7 @@ def test_never_returns_fewer_than_pool(): assert _select_with_diversity([], top_n=3, threshold=0.8) == [] -# ── t3: diversity_threshold=None is byte-compatible (no 'diverse' key) ────── +# ── diversity_threshold=None is byte-compatible (no 'diverse' key) ────── def _make_backend(): edges = [] diff --git a/tests/test_export_layout_io.py b/tests/test_export_layout_io.py index 1be027e..fe55acf 100644 --- a/tests/test_export_layout_io.py +++ b/tests/test_export_layout_io.py @@ -59,7 +59,7 @@ def test_import_json_size_cap(make_state, make_slot, monkeypatch): import_json_layout(st, big, "general") -# ── M1 hostile-partition regression tests ──────────────────────────── +# ── hostile-partition regression tests ──────────────────────────── # A partition read from an untrusted layout file must never crash the # import nor silently produce a wrong (negative-slice) split. Every # malformed shape falls back to the documented midpoint behaviour. diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py index 29149e4..4be16a1 100644 --- a/tests/test_inter_qpu_handoff.py +++ b/tests/test_inter_qpu_handoff.py @@ -1,4 +1,4 @@ -"""O5 — one-click inter-QPU handoff: selecting a remote scan candidate stages +"""One-click inter-QPU handoff: selecting a remote scan candidate stages AND auto-connects QPU 2, with graceful fallback, race guards, and a same-backend shortcut. Headless: the network-touching connect deps are stubbed. """ @@ -97,7 +97,7 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): _CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} -# ── t1: selection triggers connect once; staged→connecting→connected ──────── +# ── selection triggers connect once; staged→connecting→connected ──────── def test_selection_auto_connects_once(monkeypatch): from qpu_mapper.ui.inter_qpu import setup_inter_qpu @@ -116,7 +116,7 @@ def test_selection_auto_connects_once(monkeypatch): assert ctx.btn_connect_qpu2.disabled is False # trigger re-enabled -# ── t2: connect raising → staged fallback + error, trigger re-enabled ─────── +# ── connect raising → staged fallback + error, trigger re-enabled ─────── def test_connect_failure_falls_back_to_staged(monkeypatch): from qpu_mapper.ui.inter_qpu import setup_inter_qpu @@ -136,7 +136,7 @@ def test_connect_failure_falls_back_to_staged(monkeypatch): assert ctx.dd_backend_qpu2.value == 'ibm_k' -# ── t3: in-flight guard — a second selection does not double-connect ──────── +# ── in-flight guard — a second selection does not double-connect ──────── def test_in_flight_guard_no_double_connect(monkeypatch): from qpu_mapper.ui.inter_qpu import setup_inter_qpu @@ -161,7 +161,7 @@ def _manual_spawn(fn, on_done=None, on_error=None): assert calls == ['ibm_k'] -# ── t4: same backend already connected → apply + repaint, no reconnect ────── +# ── same backend already connected → apply + repaint, no reconnect ────── def test_same_backend_applies_without_reconnect(monkeypatch): from qpu_mapper.ui.inter_qpu import setup_inter_qpu diff --git a/tests/test_props_shim.py b/tests/test_props_shim.py index e6f40bf..7b22230 100644 --- a/tests/test_props_shim.py +++ b/tests/test_props_shim.py @@ -28,7 +28,7 @@ def _fixtures(): return qubit_props, gate_props, edges -# ── t1: the crux ──────────────────────────────────────────────────────────── +# ── the crux ──────────────────────────────────────────────────────────── def test_readout_error_by_qubit(): qp, gp, edges = _fixtures() @@ -79,7 +79,7 @@ def test_custom_gate_key(): assert shim.gate_error('ecr', (0, 1)) == pytest.approx(0.005) -# ── L1/t1/t3/t5: remote scoring is LIVE — never a cache read ──────────────── +# ── remote scoring is LIVE — never a cache read ──────────────── def _fake_remote_backend(name='ibm_remote', n=4): edges = [(0, 1), (1, 2), (2, 3)] @@ -116,14 +116,14 @@ def test_remote_scoring_is_live_never_cache_read(monkeypatch): state = SimpleNamespace(active_backend_name='current_other') props = make_scan_get_props(state, now=datetime(2026, 7, 12, 9, 30))(backend) - assert fetched == [1] # t1: LIVE fetch happened - assert reads == [] # t1: ZERO cache-read for scoring - assert saves # t3: warming save still happened - assert props.vintage == 'live · 09:30' # t5: live · + assert fetched == [1] # LIVE fetch happened + assert reads == [] # ZERO cache-read for scoring + assert saves # warming save still happened + assert props.vintage == 'live · 09:30' # live · assert props.readout_error(0) == pytest.approx(0.02) -# ── V1: active backend scored on LIVE state props (cache NOT consulted) ────── +# ── active backend scored on LIVE state props (cache NOT consulted) ────── def test_active_backend_uses_state_props_not_cache(monkeypatch): qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04])} @@ -163,7 +163,7 @@ def test_active_backend_uses_state_props_not_cache(monkeypatch): assert props.score_layout([0, 1, 2, 3])['fidelity'] == pytest.approx(local) -# ── L1/t2: a fetch failure raises (no cached fallback) ────────────────────── +# ── a fetch failure raises (no cached fallback) ────────────────────── def test_remote_fetch_failure_raises_no_cache_fallback(monkeypatch): from qpu_mapper import data @@ -181,7 +181,7 @@ def test_remote_fetch_failure_raises_no_cache_fallback(monkeypatch): make_scan_get_props(state)(backend) # no silent cached fallback -# ── D2 t1: the shim scores against ITS OWN edges, not the current state ───── +# ── the shim scores against ITS OWN edges, not the current state ───── def test_shim_scores_against_own_edges(): edges = [(0, 1), (1, 2), (2, 3)] @@ -198,7 +198,7 @@ def test_shim_scores_against_own_edges(): # Each shim used its OWN per-edge errors, not a shared/state edge list. -# ── D2 t2: the hard invariants reject a mispaired snapshot ────────────────── +# ── the hard invariants reject a mispaired snapshot ────────────────── def test_gate_length_mismatch_raises(): with pytest.raises(ValueError): @@ -213,7 +213,7 @@ def test_qubit_length_mismatch_raises(): {'cz_error': [0.001]}, [(0, 1)], n_qubits=4) -# ── D2 t3: end-to-end pin — shim score == core hand-built from same snapshot ─ +# ── end-to-end pin — shim score == core hand-built from same snapshot ─ def test_shim_score_matches_core_handbuilt(): from qpu_mapper.export.scoring import estimate_fidelity_core @@ -270,7 +270,7 @@ def test_shim_edges_are_its_own(): shim = CachedPropsShim({'readout_error': [0.0] * 8}, {'cz_error': [0.1, 0.1, 0.2, 0.2]}, edges, n_qubits=8) assert shim._edges == [(5, 6), (6, 5), (6, 7), (7, 6)] # X's edges verbatim - # A mismatched-length snapshot for a different topology → ValueError (F2). + # A mismatched-length snapshot for a different topology → ValueError. with pytest.raises(ValueError): CachedPropsShim({'readout_error': [0.0] * 8}, {'cz_error': [0.1, 0.1]}, edges, n_qubits=8) diff --git a/tests/test_qpu_scan.py b/tests/test_qpu_scan.py index e3b2506..9f86f61 100644 --- a/tests/test_qpu_scan.py +++ b/tests/test_qpu_scan.py @@ -41,7 +41,7 @@ def _entry(prod, k): } -# ── t1: list_scan_targets — flags and reasons ─────────────────────────────── +# ── list_scan_targets — flags and reasons ─────────────────────────────── def test_list_scan_targets_flags_and_reasons(): service = SimpleNamespace(backends=lambda: [ @@ -78,7 +78,7 @@ def test_list_scan_targets_flags_and_reasons(): assert not widened['ibm_d']['eligible'] # still too small -# ── t2: scan happy path — ranking + progress order ────────────────────────── +# ── scan happy path — ranking + progress order ────────────────────────── def test_scan_happy_path_sorted_and_progress(monkeypatch): scores = {'ibm_a': 0.30, 'ibm_b': 0.50} @@ -109,7 +109,7 @@ def fake_sweep(norb, backend, props, **kw): ] -# ── t3: isolation — one backend failing doesn't kill the scan ─────────────── +# ── isolation — one backend failing doesn't kill the scan ─────────────── def test_scan_isolation_on_props_failure(monkeypatch): monkeypatch.setattr( @@ -139,7 +139,7 @@ def get_props(backend): assert out['results'][-1]['name'] == 'ibm_a' -# ── t4: best_lqs / best_k extraction ──────────────────────────────────────── +# ── best_lqs / best_k extraction ──────────────────────────────────────── def test_best_lqs_extraction(monkeypatch): # Max product_score is the k=1 entry (0.90); k=3 top is 0.20. @@ -162,7 +162,7 @@ def test_best_lqs_extraction(monkeypatch): assert r['best_k'] == 1 -# ── t5: empty eligible set ────────────────────────────────────────────────── +# ── empty eligible set ────────────────────────────────────────────────── def test_scan_empty_targets(): out = scan_qpus([], 4, get_backend=lambda n: None, get_props=lambda b: None) @@ -186,7 +186,7 @@ def test_scan_skips_ineligible_targets(monkeypatch): assert out['results'][0]['sweep'] is None -# ── U1/U3: sweep_fn injection hook — the ONE loop, a pluggable sweep ──────── +# ── sweep_fn injection hook — the ONE loop, a pluggable sweep ──────── def test_sweep_fn_injected_per_target_with_isolation(): """t-new-1: sweep_fn is called per eligible target with the forwarded diff --git a/tests/test_scan_notices.py b/tests/test_scan_notices.py index eb206a3..85a7134 100644 --- a/tests/test_scan_notices.py +++ b/tests/test_scan_notices.py @@ -1,4 +1,4 @@ -"""Headless tests for in-UI scan notices (N1 cap note, N2 capture, N3 no-leak). +"""Headless tests for in-UI scan notices (cap note, capture, no-leak). Offline: data layer stubbed, scan monkeypatched, spawn+marshal synchronous. """ @@ -82,7 +82,7 @@ def _all_html(box): return " ".join(c.value for c in box.children if isinstance(c, HTML)) -# ── t1: k-capped row note from metadata ───────────────────────────────────── +# ── k-capped row note from metadata ───────────────────────────────────── def test_k_capped_row_note(monkeypatch): b = _build(monkeypatch) @@ -104,7 +104,7 @@ def test_k_not_capped_no_note(monkeypatch): assert 'k capped' not in _all_html(b.scan_results_box) -# ── t2: warning capture → grouped, deduplicated notices ───────────────────── +# ── warning capture → grouped, deduplicated notices ───────────────────── def test_notices_capture_and_dedup(monkeypatch): b = _build(monkeypatch) @@ -129,7 +129,7 @@ def sweep_warns(norb, backend, props, **kw): assert 'ibm_a' in html # grouped under the backend -# ── t3: finally-restoration (done AND error paths) ────────────────────────── +# ── finally-restoration (done AND error paths) ────────────────────────── def test_logger_restored_after_scan(monkeypatch): b = _build(monkeypatch) @@ -150,7 +150,7 @@ def test_logger_restored_after_scan(monkeypatch): assert lg.propagate == p0 -# ── t4: empty notices → no section ────────────────────────────────────────── +# ── empty notices → no section ────────────────────────────────────────── def test_no_notices_section_when_empty(monkeypatch): b = _build(monkeypatch) diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index d400774..b9ddf30 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -191,7 +191,7 @@ def test_scan_handoff_on_select(monkeypatch): assert cand['ancillas'] == [4, 5] # flat[0] = k=2 entry -# ── M1 — sweep mode greys the score checkbox ──────────────────────────────── +# ── sweep mode greys the score checkbox ──────────────────────────────── def test_m1_score_checkbox_toggle(monkeypatch): b = _build(monkeypatch) @@ -203,7 +203,7 @@ def test_m1_score_checkbox_toggle(monkeypatch): assert b.lucj_chk_score.disabled is True -# ── M2 — per-stratum status line format ───────────────────────────────────── +# ── per-stratum status line format ───────────────────────────────────── def test_m2_status_line_format(): res = _sweep(0.40, 0.30) @@ -214,7 +214,7 @@ def test_m2_status_line_format(): assert line == "Sweep: k=2..1 · 214 embeddings · best per k: 2→30.0% · 1→40.0%" -# ── A3: circuit-LQS annotation (success → number, failure → template) ─────── +# ── circuit-LQS annotation (success → number, failure → template) ─────── def test_scan_circuit_lqs_annotated(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -232,7 +232,7 @@ def test_scan_template_suffix_only_on_failure(monkeypatch): assert '(template)' in b.scan_results_box.children[0].value -# ── L2/t5: vintage renders 'live · ' (no stale badge) ─────────── +# ── vintage renders 'live · ' (no stale badge) ─────────── def test_scan_live_vintage(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -245,7 +245,7 @@ def test_scan_live_vintage(monkeypatch): assert 'stale calib' not in table # stale-badge path removed -# ── L1/t2: a fetch failure → honest error row, others complete ────────────── +# ── a fetch failure → honest error row, others complete ────────────── def test_scan_fetch_failure_error_row(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -269,7 +269,7 @@ def gp(backend): assert 'live · 09:30' in table # ibm_b completed -# ── L4/t4: stability filter still reads the cache for HISTORY ──────────────── +# ── stability filter still reads the cache for HISTORY ──────────────── def test_stability_history_reads_cache(monkeypatch): from qpu_mapper.state import SessionState @@ -300,7 +300,8 @@ def test_stability_history_reads_cache(monkeypatch): assert loads # cache loader used for HISTORY -# ── P1: local and scan pass IDENTICAL sweep params (the tonight bug) ──────── +# ── Regression: local sweep and scan must receive IDENTICAL sweep params ──── +# (any divergence silently skews cross-QPU rankings against the local one). def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -315,9 +316,9 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.chk_deep_search.value = False # a non-default value b.lucj_min_ancilla.value = 2 - b.lucj_top_n.value = 7 # (K4) non-default top_n - b.lucj_search_cap.value = 5000 # (S4) non-default cap - b.chk_lucj_diverse.value = True # (D2) non-default diversity + b.lucj_top_n.value = 7 # non-default top_n + b.lucj_search_cap.value = 5000 # non-default cap + b.chk_lucj_diverse.value = True # non-default diversity b.btn_lucj_run.click() # local sweep local_kw = calls[-1] @@ -328,13 +329,13 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): keys = ('min_bridges', 'top_n', 'hybrid', 'mapping_cap', 'diversity_threshold') assert {k: local_kw.get(k) for k in keys} == {k: scan_kw.get(k) for k in keys} assert scan_kw['hybrid'] is False # honored, not the engine default - # (K4/S4/D2) Show-top, Search-cap, diversity reach BOTH paths — parity. + # Show-top, Search-cap, diversity reach BOTH paths — parity. assert local_kw['top_n'] == 7 and scan_kw['top_n'] == 7 assert local_kw['mapping_cap'] == 5000 and scan_kw['mapping_cap'] == 5000 assert local_kw['diversity_threshold'] == 0.8 and scan_kw['diversity_threshold'] == 0.8 -# ── P2: active backend skipped-with-reference (never re-searched) ─────────── +# ── active backend skipped-with-reference (never re-searched) ─────────── def test_active_backend_skipped_with_reference(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) @@ -356,7 +357,7 @@ def test_active_backend_skipped_with_reference(monkeypatch): assert 'run Auto above' in table # no local sweep yet → hint -# ── P3: scan honors the hybrid checkbox ───────────────────────────────────── +# ── scan honors the hybrid checkbox ───────────────────────────────────── def test_scan_honors_hybrid_checkbox(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) diff --git a/tests/test_scoring_core.py b/tests/test_scoring_core.py index 7982c6a..ea87c69 100644 --- a/tests/test_scoring_core.py +++ b/tests/test_scoring_core.py @@ -1,4 +1,4 @@ -"""A3 tests — one scorer everywhere (estimate_fidelity_core). +"""One scorer everywhere (estimate_fidelity_core). Pure/offline. Pins C1 behaviour across the extract, checks the shim's per-backend scorer, and proves scan == local on identical calibration. @@ -14,7 +14,7 @@ from qpu_mapper.props_shim import CachedPropsShim -# ── t1: C1 pin — behaviour unchanged across the refactor-extract ──────────── +# ── C1 pin — behaviour unchanged across the refactor-extract ──────────── def test_c1_pin_unchanged(): qubit_ids = ['0', '1', '2', '3'] @@ -47,7 +47,7 @@ def test_c1_pin_unchanged(): assert core == res -# ── t2: per-backend shim scorer == hand-computed product ──────────────────── +# ── per-backend shim scorer == hand-computed product ──────────────────── def test_shim_score_hand_computed(): qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04])} @@ -63,7 +63,7 @@ def test_shim_score_hand_computed(): assert shim.score_layout([]) is None # empty → None -# ── t3: scan row == local number on the SAME calibration (the screenshot) ── +# ── scan row == local number on the SAME calibration (the screenshot) ── def test_scan_equals_local_same_backend(): qp = {'readout_error': np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06])} diff --git a/tests/test_shuffle_search.py b/tests/test_shuffle_search.py index a53f1a5..40f1c07 100644 --- a/tests/test_shuffle_search.py +++ b/tests/test_shuffle_search.py @@ -1,4 +1,4 @@ -"""S3 — shuffled VF2 search order kills the geographic-prefix truncation bias. +"""Shuffled VF2 search order kills the geographic-prefix truncation bias. Deterministic, offline, real VF2. Two identical blocks on one chip: * block A (ids 0..23) — NOISY (readout/gate error 0.06) @@ -69,7 +69,7 @@ def _qubits(e): return set(e['alpha']) | set(e['beta']) | set(e['ancillas']) -# ── t1: natural order misses the clean region; the shuffle finds it ───────── +# ── natural order misses the clean region; the shuffle finds it ───────── def test_shuffle_reaches_a_region_natural_order_truncates_past(): nat = _sweep(None) @@ -88,7 +88,7 @@ def test_shuffle_reaches_a_region_natural_order_truncates_past(): assert shuf_best['product_score'] > nat_best['product_score'] + 1e-6 -# ── t2: seed=None is the pinned natural-order (byte-compat) path ──────────── +# ── seed=None is the pinned natural-order (byte-compat) path ──────────── def test_seed_none_is_natural_order_and_deterministic(): a = _sweep(None) @@ -104,7 +104,7 @@ def test_seed_none_is_natural_order_and_deterministic(): assert _qubits(_best(a, 1)).isdisjoint(CLEAN) -# ── t3: same seed → identical results (reproducibility) ───────────────────── +# ── same seed → identical results (reproducibility) ───────────────────── def test_same_seed_is_reproducible(): a = _sweep(SEED) @@ -117,7 +117,7 @@ def test_same_seed_is_reproducible(): assert [e['ancillas'] for e in ea] == [e['ancillas'] for e in eb] -# ── t4: shuffled results still name REAL chip ids (no relabel leakage) ────── +# ── shuffled results still name REAL chip ids (no relabel leakage) ────── def test_shuffle_recovers_physical_ids(): shuf = _sweep(SEED) diff --git a/tests/test_stability_filter.py b/tests/test_stability_filter.py index f2a3402..3c3fe99 100644 --- a/tests/test_stability_filter.py +++ b/tests/test_stability_filter.py @@ -76,7 +76,7 @@ def _all_qubits(res): return used -# ── t1: volatility scoring ────────────────────────────────────────────────── +# ── volatility scoring ────────────────────────────────────────────────── def test_volatility_orders_volatile_above_stable(): # q3 spikes hard, q10 mildly, q5 flat. @@ -86,7 +86,7 @@ def test_volatility_orders_volatile_above_stable(): assert vol[5] == 0.0 # flat series → no volatility -# ── t2: select_excluded ───────────────────────────────────────────────────── +# ── select_excluded ───────────────────────────────────────────────────── def test_select_excluded_threshold_and_order(): vol = {3: 5.0, 2: 4.5, 10: 2.0, 5: 0.0, 7: 0.8} @@ -95,7 +95,7 @@ def test_select_excluded_threshold_and_order(): assert 5 not in excluded and 7 not in excluded -# ── t3: filtered sweep never uses excluded qubits (A1 correctness) ────────── +# ── filtered sweep never uses excluded qubits (correctness) ────────── def test_filtered_sweep_excludes_qubits(): backend, props = _make_backend(), _Props() @@ -107,7 +107,7 @@ def test_filtered_sweep_excludes_qubits(): assert res['strata'] # still found layouts (block B) -# ── t4: RELAX VALVE (the crux) ────────────────────────────────────────────── +# ── RELAX VALVE (the crux) ────────────────────────────────────────────── def test_relax_valve_readmits_least_volatile(): backend, props = _make_backend(), _Props() @@ -131,7 +131,7 @@ def test_relax_valve_readmits_least_volatile(): assert used.isdisjoint(set(st['excluded_final'])) -# ── t5: no history → plain sweep, stability unavailable ───────────────────── +# ── no history → plain sweep, stability unavailable ───────────────────── def test_no_history_runs_plain_sweep(): backend, props = _make_backend(), _Props() @@ -141,7 +141,7 @@ def test_no_history_runs_plain_sweep(): assert res['strata'] -# ── t6: A1 non-regression — exclude_qubits=None path ──────────────────────── +# ── non-regression — exclude_qubits=None path ──────────────────────── def test_a1_default_is_unfiltered(): backend, props = _make_backend(), _Props() @@ -154,7 +154,7 @@ def test_a1_default_is_unfiltered(): assert list(base['strata'].keys()) == list(explicit_none['strata'].keys()) -# ── t7: metadata — sorted excluded_final, vf2_truncated propagated ────────── +# ── metadata — sorted excluded_final, vf2_truncated propagated ────────── def test_metadata_and_truncation_propagation(): backend, props = _make_backend(), _Props() @@ -170,7 +170,7 @@ def test_metadata_and_truncation_propagation(): assert res['excluded_qubits'] == sorted(res['excluded_qubits']) -# ── F1/F2: quality floor — stably-terrible qubits volatility is blind to ──── +# ── quality floor — stably-terrible qubits volatility is blind to ──── class _OutlierProps: """Current props where qubit 24 is a stable device outlier (~73× the diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index 6415aaf..b43c4f9 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -81,7 +81,7 @@ def _build(monkeypatch, *, history=False, spawn=_sync_spawn, return b -# ── t1: availability gating ───────────────────────────────────────────────── +# ── availability gating ───────────────────────────────────────────────── def test_checkbox_disabled_without_history(monkeypatch): b = _build(monkeypatch, history=False) @@ -95,7 +95,7 @@ def test_checkbox_enabled_with_history(monkeypatch): assert b.chk_stability_filter.tooltip # non-empty -# ── t2: filter ON routes to sweep_with_stability with the controls' args ──── +# ── filter ON routes to sweep_with_stability with the controls' args ──── def test_filter_on_calls_sweep_with_stability(monkeypatch): b = _build(monkeypatch, history=True) @@ -121,7 +121,7 @@ def fake_sws(norb, backend, props, hist, **kw): assert plain == [] # plain NOT called -# ── t3: the three banner states ───────────────────────────────────────────── +# ── the three banner states ───────────────────────────────────────────── def test_banner_states(monkeypatch): b = _build(monkeypatch, history=True) @@ -147,7 +147,7 @@ def test_banner_states(monkeypatch): assert 'filter skipped' in b.lbl_lucj_stability.value -# ── t4: scan rows carry stability badges ──────────────────────────────────── +# ── scan rows carry stability badges ──────────────────────────────────── def test_scan_stability_badges(monkeypatch): b = _build(monkeypatch, history=True) @@ -180,7 +180,7 @@ def test_scan_stability_badges(monkeypatch): assert 'n/a (no cached history)' in table # fresh → n/a -# ── t5: filter OFF keeps the plain sweep path ─────────────────────────────── +# ── filter OFF keeps the plain sweep path ─────────────────────────────── def test_filter_off_uses_plain_sweep(monkeypatch): b = _build(monkeypatch, history=True) @@ -199,7 +199,7 @@ def test_filter_off_uses_plain_sweep(monkeypatch): assert b.lbl_lucj_stability.value == "" # no banner -# ── F3: banner counts N volatile + M outlier from the metadata ────────────── +# ── banner counts N volatile + M outlier from the metadata ────────────── def test_banner_counts_volatile_and_outlier(monkeypatch): b = _build(monkeypatch, history=True) @@ -230,7 +230,7 @@ def test_banner_no_outlier_suffix_when_floor_empty(monkeypatch): assert 'filtered 2 volatile qubits' in v and 'outlier' not in v -# ── t5: _scan_filtered per-backend isolation + both badge paths ───────────── +# ── _scan_filtered per-backend isolation + both badge paths ───────────── def test_scan_filtered_per_backend_isolation(monkeypatch): b = _build(monkeypatch, history=True) diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index d5f148c..ed26445 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -59,7 +59,7 @@ def entry(anc, prod, add, src): 'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], 'ancillas': anc, 'bridge_slots': tuple(range(0, 4 * len(anc), 4)), 'product_score': prod, 'additive_score': add, - # A2: engine now attaches circuit-level LQS; equal to product here + # engine now attaches circuit-level LQS; equal to product here # so the rendered percentage is unchanged in these UI assertions. 'lqs_circuit': prod, 'rank_in_stratum': 1, 'source': src, @@ -73,7 +73,7 @@ def entry(anc, prod, add, src): 'k_max_effective': 3, 'min_bridges': 1, 'vf2_truncated': vf2_truncated, 'n_raw_embeddings': 214, 'n_candidates_scored': 1891, - # (K3) real engine metadata: which strata hit the cap, and the cap. + # real engine metadata: which strata hit the cap, and the cap. 'per_stratum': { 3: {'n_direct': 5, 'n_derived': 0, 'truncated': vf2_truncated}, 2: {'n_direct': 0, 'n_derived': 5, 'truncated': False}, @@ -83,7 +83,7 @@ def entry(anc, prod, add, src): } -# ── A2 t2: label/status formatters prefer circuit-level LQS ───────────────── +# ── label/status formatters prefer circuit-level LQS ───────────────── def test_formatters_use_lqs_circuit(): from qpu_mapper.ui.lucj_panel import _entry_lqs_pct, _format_best_per_k @@ -102,7 +102,7 @@ def test_formatters_use_lqs_circuit(): assert _format_best_per_k({1: [{'product_score': 0.4}]}) == '1→40.0%' -# ── t1: sweep mode default → stratified dropdown, exact label format ──────── +# ── sweep mode default → stratified dropdown, exact label format ──────── def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): calls = [] @@ -124,7 +124,7 @@ def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): assert [opt[1] for opt in b.dd_lucj_layout.options] == [0, 1, 2] -# ── K4: the "Show top" field controls entries-per-stratum in the dropdown ─── +# ── the "Show top" field controls entries-per-stratum in the dropdown ─── def _fake_sweep_topn(*a, **k): """Echo the requested top_n: k_max=3, each stratum gets top_n entries.""" @@ -160,7 +160,7 @@ def test_top_n_field_controls_dropdown_entries(builder, monkeypatch): assert len(labels) == 21 # 3 strata × 7 -# ── t2: legacy mode → single-search path, sweep NOT called ────────────────── +# ── legacy mode → single-search path, sweep NOT called ────────────────── def test_legacy_mode_skips_sweep(builder, monkeypatch): sweep_calls, legacy_calls = [], [] @@ -184,7 +184,7 @@ def fake_legacy(*a, **k): assert legacy_calls[0][1]['requested_bridges'] == 2 -# ── t3: apply a k=2 derived entry → chains + its 2 ancillas placed ────────── +# ── apply a k=2 derived entry → chains + its 2 ancillas placed ────────── def test_apply_derived_candidate_places_chains_and_ancillas(builder, monkeypatch): monkeypatch.setattr( @@ -209,7 +209,7 @@ def test_apply_derived_candidate_places_chains_and_ancillas(builder, monkeypatch assert q in d['styles'] -# ── t4: truncation banner visibility ──────────────────────────────────────── +# ── truncation banner visibility ──────────────────────────────────────── def test_truncation_banner(builder, monkeypatch): monkeypatch.setattr( @@ -217,7 +217,7 @@ def test_truncation_banner(builder, monkeypatch): lambda *a, **k: _fake_sweep_result(vf2_truncated=True)) b = builder b.btn_lucj_run.click() - # (K3) names the REAL cap and the truncated stratum — not n_raw_embeddings. + # names the REAL cap and the truncated stratum — not n_raw_embeddings. assert "truncated at 2,000 mappings for k=3" in b.lbl_lucj_trunc.value assert "214" not in b.lbl_lucj_trunc.value # old embedding-count gone assert b.lbl_lucj_trunc.value != "" @@ -230,7 +230,7 @@ def test_truncation_banner(builder, monkeypatch): assert b.lbl_lucj_trunc.value == "" -# ── t5: engine ValueError surfaces as a friendly status, no traceback ─────── +# ── engine ValueError surfaces as a friendly status, no traceback ─────── def test_min_bridges_validation_surfaces_as_status(builder, monkeypatch): def boom(*a, **k): @@ -249,7 +249,7 @@ def boom(*a, **k): assert b.btn_lucj_run.disabled is False -# ── H2: the deep-search checkbox wires hybrid= and the M2 mode label ──────── +# ── the deep-search checkbox wires hybrid= and the per-stratum mode label ──────── def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): calls = [] @@ -279,7 +279,7 @@ def test_sweep_mode_label(): assert _sweep_mode_label(dv) == 'derived-only' -# ── D2: diverse entries get a "· alt region" dropdown-label suffix ────────── +# ── diverse entries get a "· alt region" dropdown-label suffix ────────── def test_diverse_entry_label_suffix(builder, monkeypatch): def _fake(*a, **k): diff --git a/tests/test_temporal_anchoring.py b/tests/test_temporal_anchoring.py index e4e4501..cf8b2ff 100644 --- a/tests/test_temporal_anchoring.py +++ b/tests/test_temporal_anchoring.py @@ -1,4 +1,4 @@ -"""Temporal-anchoring audit fixes (F1/F2/F3): the SELECTED calibration date +"""Temporal-anchoring audit fixes: the SELECTED calibration date must govern all scoring in one search. * t1 — epoch consistency: when a past date is active, the sweep's pre-rank @@ -18,7 +18,7 @@ ) -# ── t2: the volatility window anchors to the selected date (engine) ───────── +# ── the volatility window anchors to the selected date (engine) ───────── def _divergent_history(n_qubits=48): """30 daily snapshots. q3 spikes EARLY (07-05, inside [.. ,07-14]); q5 @@ -164,7 +164,7 @@ def _build(monkeypatch, *, past_date=None): return b, state -# ── t1: pre-rank props == circuit-score arrays (one epoch) ────────────────── +# ── pre-rank props == circuit-score arrays (one epoch) ────────────────── def test_prerank_uses_selected_date_not_live_props(monkeypatch): b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') @@ -183,7 +183,7 @@ def test_prerank_uses_selected_date_not_live_props(monkeypatch): assert pr.readout_error(7) == state.qubit_props_data['readout_error'][7] -# ── t3: the scan header names the epoch mix on a past date ────────────────── +# ── the scan header names the epoch mix on a past date ────────────────── def test_scan_header_notes_epoch_mix_on_past_date(monkeypatch): b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py index dfdbec0..8f8d072 100644 --- a/tests/test_ui_cleanup.py +++ b/tests/test_ui_cleanup.py @@ -66,7 +66,7 @@ def _build(monkeypatch): return b -# ── t1: local block renders ABOVE the scan block ──────────────────────────── +# ── local block renders ABOVE the scan block ──────────────────────────── def test_local_block_above_scan(monkeypatch): b = _build(monkeypatch) @@ -80,7 +80,7 @@ def test_local_block_above_scan(monkeypatch): assert any('📍 This backend (ibm_here)' in h for h in headers) -# ── t2: clear resets everything and re-arms the button ────────────────────── +# ── clear resets everything and re-arms the button ────────────────────── def test_clear_scan_results(monkeypatch): b = _build(monkeypatch) @@ -122,7 +122,7 @@ def test_new_scan_auto_clears(monkeypatch): assert list(b.scan_results_box.children) != first + first -# ── t3: staged banner appears on stage, cleared on connect ────────────────── +# ── staged banner appears on stage, cleared on connect ────────────────── class _Stub: def __init__(self, **attrs): @@ -181,7 +181,7 @@ def test_staged_banner_then_cleared_on_connect(): assert 'staged' not in ctx.lbl_qpu2_status.value -# ── t4: label disambiguation in the detail + dropdown ─────────────────────── +# ── label disambiguation in the detail + dropdown ─────────────────────── def test_label_disambiguation(monkeypatch): b = _build(monkeypatch) From 52fcc54597e4a2ed1305241c88c194493dce5b7b Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 14 Jul 2026 18:37:44 -0400 Subject: [PATCH 20/66] Quality floor always on across sweep paths; batch scan on all QPUs --- qpu_mapper/multi_sweep.py | 241 ++++++++++++++++ qpu_mapper/ui/builder.py | 46 ++- qpu_mapper/ui/inter_qpu.py | 18 +- qpu_mapper/ui/lucj_panel.py | 489 ++++++++++++++++++++++++++++++-- tests/test_floor_batch_ui.py | 238 ++++++++++++++++ tests/test_inter_qpu_handoff.py | 35 +++ tests/test_multi_sweep.py | 195 +++++++++++++ tests/test_multi_sweep_ui.py | 254 +++++++++++++++++ 8 files changed, 1482 insertions(+), 34 deletions(-) create mode 100644 qpu_mapper/multi_sweep.py create mode 100644 tests/test_floor_batch_ui.py create mode 100644 tests/test_multi_sweep.py create mode 100644 tests/test_multi_sweep_ui.py diff --git a/qpu_mapper/multi_sweep.py b/qpu_mapper/multi_sweep.py new file mode 100644 index 0000000..923d1b1 --- /dev/null +++ b/qpu_mapper/multi_sweep.py @@ -0,0 +1,241 @@ +""" +multi_sweep.py — Sequential greedy orchestrator for placing SEVERAL LUCJ +circuits on one QPU, each via the single-circuit ancilla sweep. + +Placement is greedy and sequential, mirroring the legacy multi-circuit path +(``auto_lucj.get_multi_circuit_layouts``): circuit i is swept on the qubits +still free after circuits 0..i-1 have claimed their chosen layout's qubits +PLUS a coupling-graph buffer around each. The buffer semantics are inherited +verbatim from ``auto_lucj._exclude_with_buffer`` — "buffer_qubits=1" excludes +every 1-hop coupling neighbour of a placed qubit — so "Buffer qubits: N" means +exactly what it means in the legacy tool. + +Nothing here edits the frozen engines: the single-circuit search is +``ancilla_sweep.sweep_ancilla_layouts`` and the buffer/exclusion math is +``auto_lucj._exclude_with_buffer`` / ``_make_backend_cmap_pygraph``, both +imported read-only. + +Fit failures never raise: if circuit i cannot be placed on what remains, the +run stops there and returns the partial result with ``failed_at=i`` (the UI +decides how to message it). +""" + +import logging + +from .ancilla_sweep import sweep_ancilla_layouts, _AUTO_SHUFFLE +from .auto_lucj import _exclude_with_buffer, _make_backend_cmap_pygraph + +_log = logging.getLogger(__name__) + +AUTO = _AUTO_SHUFFLE # re-export the shuffle sentinel for callers/tests + + +def _per_circuit(value, i): + """Resolve a knob that may be a global scalar or a per-circuit list.""" + if isinstance(value, (list, tuple)): + return value[i] if i < len(value) else None + return value + + +def _entry_qubits(entry): + """Full physical footprint of a chosen entry: alpha ∪ beta ∪ ancillas.""" + return list(entry['alpha']) + list(entry['beta']) + list(entry['ancillas']) + + +def _best_entry(res, has_scorer): + """The circuit's chosen layout = the entry with the highest DISPLAYED + metric across all strata (lqs_circuit when a circuit scorer is wired, else + product_score). Falls back to product_score if every lqs_circuit is None + (scoring failed for the whole sweep). Returns None if there are no + entries at all.""" + def _scan(key): + best, best_v = None, None + for entries in res.get('strata', {}).values(): + for e in entries: + v = key(e) + if v is None: + continue + if best is None or v > best_v: + best, best_v = e, v + return best + + if has_scorer: + best = _scan(lambda e: e.get('lqs_circuit')) + if best is not None: + return best + return _scan(lambda e: e['product_score']) + + +def _circuit_record(i, norb_i, res_i, chosen): + """Per-circuit result: the chosen layout PLUS the full strata (kept so a + future override UX can substitute a different candidate) and metadata.""" + return { + 'circuit_idx': i, + 'norb': norb_i, + 'chosen': chosen, + 'strata': res_i['strata'], + 'k_max_effective': res_i['k_max_effective'], + 'min_bridges': res_i['min_bridges'], + 'vf2_truncated': res_i['vf2_truncated'], + 'per_stratum': res_i['per_stratum'], + 'mapping_cap': res_i.get('mapping_cap'), + 'excluded_qubits': res_i['excluded_qubits'], + } + + +def _orchestrate(ctx, prefix=None): + """Core sequential greedy pass. + + ``prefix`` (for :func:`replan_from`) is a list of ``(circuit_record, + chosen_entry)`` for the first len(prefix) circuits whose selection is + FIXED: they are not re-swept, but their chosen qubits still shape the + exclusion set for everything after them. All later circuits are swept. + """ + prefix = prefix or [] + norbs = ctx['norbs'] + buffer_qubits = ctx['buffer_qubits'] + has_scorer = ctx['circuit_score_fn'] is not None + + # Physical-id-tagged coupling graph, used ONLY for buffer expansion; the + # sweep prunes its own graph from `exclude_qubits`. + remaining = _make_backend_cmap_pygraph(backend=ctx['backend']) + for idx in remaining.node_indices(): + remaining[idx] = idx + + stability = set(int(q) for q in (ctx['exclude_qubits'] or [])) + if stability: + # buffer=0 → remove exactly the stability qubits (no expansion). + remaining, _ = _exclude_with_buffer(remaining, stability, 0) + excluded = set(stability) + + circuits, placed, buffers = [], [], [] + failed_at = None + + for i, norb_i in enumerate(norbs): + if i < len(prefix): + rec, chosen = prefix[i] + rec = dict(rec) + rec['chosen'] = chosen + else: + try: + res_i = sweep_ancilla_layouts( + norb_i, ctx['backend'], ctx['props'], + exclude_qubits=(excluded or None), + min_bridges=_per_circuit(ctx['min_bridges'], i), + top_n=ctx['top_n'], mapping_cap=ctx['mapping_cap'], + hybrid=ctx['hybrid'], + diversity_threshold=ctx['diversity_threshold'], + circuit_score_fn=ctx['circuit_score_fn'], + shuffle_seed=ctx['shuffle_seed']) + except Exception as exc: + # A fit failure (or any sweep error) stops the run honestly. + _log.info("Multi-sweep: circuit %d (norb=%d) did not fit: %s", + i, norb_i, exc) + failed_at = i + break + chosen = _best_entry(res_i, has_scorer) + if chosen is None: + failed_at = i + break + rec = _circuit_record(i, norb_i, res_i, chosen) + + circuits.append(rec) + chosen_full = _entry_qubits(chosen) + placed.extend(chosen_full) + remaining, new_excl = _exclude_with_buffer( + remaining, set(chosen_full), buffer_qubits) + buffers.extend(sorted(new_excl - set(chosen_full))) + excluded |= new_excl + + chosen_list = [c['chosen'] for c in circuits] + total_product = None + if chosen_list: + total_product = 1.0 + for c in chosen_list: + total_product *= c['product_score'] + total_lqs = None + if chosen_list and all(c.get('lqs_circuit') is not None for c in chosen_list): + total_lqs = 1.0 + for c in chosen_list: + total_lqs *= c['lqs_circuit'] + + return { + 'circuits': circuits, + 'total_product': total_product, + 'total_lqs_circuit': total_lqs, + 'placed_qubits': placed, + 'buffer_qubits_used': buffers, + 'failed_at': failed_at, + '_context': ctx, + } + + +def sweep_multi_circuits(norbs, backend, props, *, + min_bridges=None, top_n=3, buffer_qubits=1, + exclude_qubits=None, mapping_cap=None, hybrid=True, + diversity_threshold=None, circuit_score_fn=None, + shuffle_seed=AUTO): + """Place ``len(norbs)`` LUCJ circuits on one backend, greedily and in order. + + For each circuit i the search space is the chip minus: the stability + pre-exclusions (``exclude_qubits``), every qubit already claimed by + circuits 0..i-1, AND their ``buffer_qubits``-hop coupling neighbourhood + (``auto_lucj._exclude_with_buffer`` semantics). The circuit's chosen layout + is the best entry by the displayed metric (``lqs_circuit`` when + ``circuit_score_fn`` is wired, else ``product_score``). + + Args: + norbs: list of spatial-orbital counts, one per circuit. + backend, props: as for :func:`ancilla_sweep.sweep_ancilla_layouts`. + min_bridges: global floor, OR a per-circuit list (indexed by circuit). + top_n, mapping_cap, hybrid, diversity_threshold, circuit_score_fn, + shuffle_seed: forwarded unchanged to each single-circuit sweep. + buffer_qubits: idle coupling-graph hops kept clear between circuits. + exclude_qubits: physical ids barred from EVERY circuit (e.g. stability + volatility/quality-floor pre-exclusions). + + Returns a dict:: + + { + 'circuits': [ {circuit_idx, norb, chosen, strata, k_max_effective, + min_bridges, vf2_truncated, per_stratum, mapping_cap, + excluded_qubits} ... ], # one per PLACED circuit + 'total_product': prod(chosen_i.product_score) or None, + 'total_lqs_circuit': prod(chosen_i.lqs_circuit) or None if any missing, + 'placed_qubits': [...], # all chosen qubits, in placement order + 'buffer_qubits_used': [...], # buffer qubits kept clear + 'failed_at': None | int, # circuit i could not fit → stopped + '_context': {...}, # inputs, for replan_from() + } + + A circuit that cannot fit stops the run: earlier circuits are returned and + ``failed_at`` is that index. This never raises for a fit failure. + """ + ctx = { + 'norbs': list(norbs), 'backend': backend, 'props': props, + 'min_bridges': min_bridges, 'top_n': top_n, + 'buffer_qubits': buffer_qubits, 'exclude_qubits': exclude_qubits, + 'mapping_cap': mapping_cap, 'hybrid': hybrid, + 'diversity_threshold': diversity_threshold, + 'circuit_score_fn': circuit_score_fn, 'shuffle_seed': shuffle_seed, + } + return _orchestrate(ctx) + + +def replan_from(result, index, new_choice): + """Override hook (mirrors ``auto_lucj.reoptimize_after_change``). + + Keep circuits ``< index`` with their current chosen layout, substitute + ``new_choice`` (one of circuit ``index``'s strata entries) at ``index``, + and re-sweep every circuit ``> index`` — their regions freed / re-excluded + to match the new fixed prefix. Pure: reads ``result`` (and the ``_context`` + it carries), returns a fresh result dict of the same shape. + """ + ctx = result['_context'] + circuits = result['circuits'] + if not (0 <= index < len(circuits)): + raise IndexError(f"replan index {index} out of range " + f"(have {len(circuits)} placed circuits)") + prefix = [(circuits[i], circuits[i]['chosen']) for i in range(index)] + prefix.append((circuits[index], new_choice)) + return _orchestrate(ctx, prefix=prefix) diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index 6d50eb0..d0c5e30 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -314,7 +314,11 @@ def _run_pipeline(self): lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, lucj_multi_ancillas=self.lucj_multi_ancillas, - btn_lucj_multi=self.btn_lucj_multi, lbl_lucj_multi=self.lbl_lucj_multi, + btn_lucj_multi=self.btn_lucj_multi, + btn_lucj_multi_sweep=self.btn_lucj_multi_sweep, + btn_scan_batch=self.btn_scan_batch, + scan_batch_box=self.scan_batch_box, + lbl_lucj_multi=self.lbl_lucj_multi, lucj_multi_detail_box=self.lucj_multi_detail_box, num_circuits=self.num_circuits, intra_qpu_mode=self.intra_qpu_mode, dd_mode=self.dd_mode, lucj_all_layouts=self._lucj_all_layouts, @@ -1283,19 +1287,20 @@ def _build_auto_lucj_widgets(self, W): style={'description_width': '90px'}, tooltip='Volatility score = max/median − 1; higher threshold = ' 'more tolerant (fewer qubits excluded)') - # Quality floor: also exclude STABLY-terrible qubits — current - # readout outliers the volatility score is blind to. σ from device mean. + # Quality floor: always-on factory guard — exclude qubits whose CURRENT + # readout error is a device outlier (> σ above the mean), from EVERY + # search path (single / multi / scan), independent of the volatility + # filter. Defined here but mounted in the always-visible Auto section. self.ft_stability_floor = BoundedFloatText( value=3.0, min=0.0, max=20.0, step=0.5, description='Quality floor:', layout=Layout(width='230px'), - style={'description_width': '90px'}, - tooltip='Exclude qubits whose CURRENT readout error is more than ' - 'this many σ above the device mean (0 = off). Catches ' - 'consistently-bad qubits, not just volatile ones.') - # Window + threshold + floor row, revealed only when the filter is on. + style={'description_width': '110px'}, + tooltip='Always on: exclude qubits whose CURRENT readout error is ' + 'more than this many σ above the device mean (0 = off). ' + 'Applies to single, multi and scan searches.') + # Window + threshold row, revealed only when the volatility filter is on. self.stability_ctrl_box = VBox( - [self.rb_stability_window_auto, self.ft_stability_threshold, - self.ft_stability_floor]) + [self.rb_stability_window_auto, self.ft_stability_threshold]) self.stability_ctrl_box.layout.display = 'none' self.lbl_lucj_stability = HTML("") # Scan sub-option: filter each scanned backend with CACHED history only. @@ -1346,7 +1351,10 @@ def _build_auto_lucj_widgets(self, W): self.lucj_multi_ancillas = Text( value='', description='ancilla per circuit:', placeholder='blank = use Ancilla above; or e.g. 2, 2 (-1 = auto)', - layout=W, style={'description_width': 'initial'}) + layout=W, style={'description_width': 'initial'}, + tooltip='Legacy Generate: exact bridge count per circuit. ' + 'Sweep (🧺): per-circuit min ancillas (floor); ' + 'blank = engine default.') # Buffer qubits: tiny range 0-5, numeric input is more direct. self.lucj_buffer_slider = BoundedIntText( value=1, min=0, max=5, @@ -1356,6 +1364,18 @@ def _build_auto_lucj_widgets(self, W): self.btn_lucj_multi = Button( description='🤖 Generate Multi-Circuit', button_style='success', layout=W) + # Sweep-based multi-circuit: greedy auto-best per circuit with a + # per-circuit override dropdown (uses the ancilla sweep + buffer). + self.btn_lucj_multi_sweep = Button( + description='🧺 Generate Multi-Circuit (sweep)', + button_style='info', layout=W) + # Batch scan: run the whole multi-circuit batch on every compatible QPU. + self.btn_scan_batch = Button( + description='🌐 Scan batch on all QPUs', + button_style='info', layout=W, + tooltip='Place the full multi-circuit batch on every eligible ' + 'backend and rank by batch fidelity') + self.scan_batch_box = VBox([]) self.lbl_lucj_multi = HTML("") # Populated dynamically with per-circuit dropdowns when the # user clicks btn_lucj_multi. @@ -1740,6 +1760,7 @@ def _build_auto_lucj_view(self): self.lucj_chk_score, self.chk_deep_search, self.chk_lucj_diverse, + self.ft_stability_floor, self.chk_stability_filter, self.stability_ctrl_box, self.lbl_lucj_stability, @@ -1772,8 +1793,11 @@ def _build_auto_lucj_view(self): self.lucj_multi_ancillas, self.lucj_buffer_slider, self.btn_lucj_multi, + self.btn_lucj_multi_sweep, + self.btn_scan_batch, self.lbl_lucj_multi, self.lucj_multi_detail_box, + self.scan_batch_box, ], layout=Layout(padding='6px')) def _build_export_view(self): diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index bd470a2..40d37ce 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -263,12 +263,7 @@ def refresh_qpu1_label(): # ── remote-candidate handoff (scan → inter-QPU) ───────── handoff_cell = getattr(ctx, 'handoff_cell', None) - def _apply_candidate_to_state(s2, candidate): - """Pre-load a scan-selected candidate onto QPU-2's layout state so - the secondary map renders it from its first paint. Called BEFORE - build_mapper_ui(s2), so no qubit-id filtering is possible yet — the - candidate's qubits are valid ids for that backend by construction.""" - d = s2.layouts_data[0] + def _apply_one_to_slot(d, candidate): d['alpha'] = []; d['beta'] = []; d['other'] = [] d['qubits'] = []; d['ancilla'] = []; d['styles'] = {} defs = d['defaults'] @@ -284,6 +279,17 @@ def _apply_candidate_to_state(s2, candidate): d['styles'][q] = {'fill': fills[role], 'line': line, 'width': 2, 'text_color': '#000000'} + def _apply_candidate_to_state(s2, candidate): + """Pre-load scan-selected candidate(s) onto QPU-2's layout state so the + secondary map renders from its first paint. A single candidate lands on + C1; a LIST (a multi-circuit batch) lands on C1..Cn, one per slot — the + list form is what the batch-scan handoff sends.""" + cands = candidate if isinstance(candidate, (list, tuple)) else [candidate] + for i, cand in enumerate(cands): + d = s2.layouts_data.get(i) + if d is not None: + _apply_one_to_slot(d, cand) + def stage_remote_candidate(backend_name, candidate): """Scan-side entry point: reveal the inter-QPU panel, prefill the QPU-2 backend dropdown, and stage the candidate so it renders as diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 800477c..032cb95 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -7,7 +7,7 @@ import contextlib import logging -from ipywidgets import Dropdown, HTML +from ipywidgets import Button, Dropdown, HTML from ..constants import hex_to_rgba from ..html_safe import esc @@ -117,6 +117,9 @@ def setup_lucj_callbacks(ctx): lucj_multi_ancillas = ctx.lucj_multi_ancillas lucj_buffer_slider = ctx.lucj_buffer_slider btn_lucj_multi = ctx.btn_lucj_multi + btn_lucj_multi_sweep = ctx.btn_lucj_multi_sweep + btn_scan_batch = ctx.btn_scan_batch + scan_batch_box = ctx.scan_batch_box lbl_lucj_multi = ctx.lbl_lucj_multi lucj_multi_detail_box = ctx.lucj_multi_detail_box @@ -159,6 +162,14 @@ def _apply_multi_candidate(circ_idx, candidate): for q in d['beta']: d['styles'][q] = {'fill': beta_fill, 'line': _line, 'width': _width, 'text_color': _text} + # Sweep entries carry per-circuit ancillas; paint them as the ancilla + # role. Legacy candidates have no 'ancillas' key → nothing changes. + anc_fill = 'none' if line_only else hex_to_rgba(d['defaults']['fill_anc'], 1.0) + d['ancilla'] = [str(q) for q in candidate.get('ancillas', []) + if str(q) in state.qubit_ids] + for q in d['ancilla']: + d['styles'][q] = {'fill': anc_fill, + 'line': _line, 'width': _width, 'text_color': _text} # ── Apply single layout to circuit 0 ───────────────────────── def _apply_lucj_layout(entry): @@ -433,15 +444,29 @@ def _generate_sweep(norb): # circuit-level LQS on its survivors here. _annotate_circuit_lqs(res) else: + # Always-on quality floor for the UNfiltered path: outlier qubits + # are removed up front via exclude_qubits (the filtered path gets + # the same floor through sweep_with_stability's quality_sigma, so + # they never both fire on one search — no double-exclusion). + floor_excl = _floor_exclusions() res = sweep_ancilla_layouts( norb, state.active_backend, scoring_props, circuit_score_fn=_circuit_score, # aligned circuit LQS + exclude_qubits=(floor_excl or None), **kwargs) # single source (incl. hybrid) + parts = [] if _stability_filter_active(): # Checkbox on but no history dict → skipped note. - _render_stability_banner(None, norb) - else: - lbl_lucj_stability.value = "" + parts.append( + "
" + "🛡 no history in range — filter skipped
") + if floor_excl: + parts.append( + f"
🛡 floor excluded {len(floor_excl)} " + f"outlier qubit(s)
") + lbl_lucj_stability.value = "".join(parts) strata = res['strata'] # Flatten k descending, entries in stratum order; the dropdown value @@ -569,11 +594,46 @@ def _on_ancilla_mode_change(change=None): stability_ctrl_box = ctx.stability_ctrl_box def _floor_sigma(): - """Quality-floor σ from the UI; 0 → None (floor off). Read at - each sweep_with_stability call site (like window/threshold), so the - local sweep and the scan share it by construction.""" + """Quality-floor σ from the UI; 0 → None (floor off). Always on: the + floor applies to every search path independent of the volatility + filter (single, multi, scan).""" v = getattr(ft_stability_floor, 'value', None) return v if (v and v > 0) else None + + def _readout_array(props): + """Per-qubit CURRENT readout array from a props object — the shim's own + array when present, else built from readout_error(q).""" + arr = getattr(props, '_readout', None) + if arr is not None: + return arr + n = getattr(props, 'n_qubits', None) or len( + getattr(state, 'qubit_ids', None) or []) + if not n: + return None + out = [] + for q in range(n): + try: + out.append(props.readout_error(q)) + except Exception: + out.append(float('nan')) + return out + + def _floor_exclusions(props=None): + """Physical qubit ids the always-on quality floor removes — the C1 + device-outlier rule promoted to a factory guard. Computed on `props` + (per-backend, for the scan) or the local current props. Empty when + σ=0 or no readout array is available.""" + sigma = _floor_sigma() + if sigma is None: + return set() + from ..stability_filter import select_quality_floor + if props is None: + arr = (getattr(state, 'qubit_props_data', None) or {}).get('readout_error') + else: + arr = _readout_array(props) + if arr is None: + return set() + return set(select_quality_floor(arr, sigma=sigma)) lbl_lucj_stability = ctx.lbl_lucj_stability chk_scan_stability = ctx.chk_scan_stability @@ -643,15 +703,22 @@ def _cached_history_for(backend_name): def _stability_badge(r): stab = r.get('stability') - if not stab: - return "" - if not stab.get('available', False): - return ("stability: n/a " - "(no cached history)") - n = len(stab.get('excluded_final', [])) - extra = " (relaxed)" if stab.get('relaxed') else "" - return (f"🛡 −{esc(str(n))} " - f"qubits{extra}") + floor_m = r.get('floor_excluded', 0) + parts = [] + if stab and stab.get('available', False): + n = len(stab.get('excluded_final', [])) + extra = " (relaxed)" if stab.get('relaxed') else "" + parts.append(f"🛡 −{esc(str(n))} " + f"qubits{extra}") + elif stab and not stab.get('available', False): + parts.append("stability: n/a " + "(no cached history)") + # Always-on floor: shown when it excluded outliers on the UNfiltered + # path (the filtered −N badge above already counts them). + if floor_m: + parts.append(f"🛡 floor " + f"−{esc(str(floor_m))}") + return " ".join(parts) def _scan_circuit_score(props): """Per-backend circuit-level scorer: uses the shim's own arrays via @@ -727,10 +794,15 @@ def _sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): top_n=kwargs['top_n'], mapping_cap=kwargs['mapping_cap'], quality_sigma=floor_sigma) else: - res = sweep_ancilla_layouts(norb, backend, props, **kwargs) + # Always-on quality floor on THIS backend's live props. + floor_excl = _floor_exclusions(props) + res = sweep_ancilla_layouts( + norb, backend, props, + exclude_qubits=(floor_excl or None), **kwargs) res['stability'] = ({'available': False, 'reason': 'no cached history'} if use_filter else None) + res['floor_excluded'] = len(floor_excl) return res def _progress(name, status, detail=''): @@ -750,6 +822,8 @@ def _progress(name, status, detail=''): sweep = r.get('sweep') r['stability'] = (sweep.get('stability') if sweep is not None else ({'available': False} if use_filter else None)) + r['floor_excluded'] = (sweep.get('floor_excluded', 0) + if sweep is not None else 0) return result _scan = {'progress': {}, 'order': []} @@ -1274,6 +1348,387 @@ def _on_change(change): btn_lucj_multi.on_click(_on_lucj_multi) + # ── Multi-Circuit SWEEP (auto-best per circuit + override) ────── + _multi_sweep = {'result': None, 'replan_in_flight': False, 'dropdowns': {}} + + def _parse_multi_norbs(): + raw = lucj_multi_norbs.value.strip() + err = ("❌ {}") + if not raw: + return None, err.format('Enter norb values (e.g. 8, 8)') + try: + norbs = [int(x.strip()) for x in raw.split(',') if x.strip()] + except ValueError: + return None, err.format('Invalid norb values') + if not norbs: + return None, err.format('Enter norb values (e.g. 8, 8)') + return norbs, None + + def _multi_min_bridges(norbs): + """The ancilla-per-circuit field, read as per-circuit min_bridges for + the sweep. Blank → engine default (None). A value <= 0 → default for + that circuit.""" + raw = lucj_multi_ancillas.value.strip() + err = ("❌ {}") + if not raw: + return None, None + try: + vals = [int(x.strip()) for x in raw.split(',') if x.strip()] + except ValueError: + return None, err.format('Invalid ancilla values (integers, e.g. 2, 2)') + if len(vals) != len(norbs): + return None, err.format( + f'Ancilla list has {len(vals)} value(s) but {len(norbs)} ' + f'circuit(s). Match them, or leave blank.') + return [v if v and v >= 1 else None for v in vals], None + + def _multi_stability_exclusions(): + """Hard pre-exclusion set for every circuit: the ALWAYS-ON quality + floor ∪ (volatility exclusions only when the stability checkbox is on). + The union is idempotent — a qubit both volatile and an outlier is + excluded once.""" + excl = set(_floor_exclusions()) # always-on floor + if _stability_filter_active(): + history = getattr(state, 'cal_history', None) + if history: + from ..stability_filter import ( + compute_qubit_volatility, select_excluded) + vol = compute_qubit_volatility( + history, rb_stability_window.value, + today=_selected_date_anchor()) + excl |= set(select_excluded( + vol, threshold=ft_stability_threshold.value)) + return excl or None + + def _apply_multi_sweep(result): + circuits = result.get('circuits', []) + if not circuits: + return + if not intra_qpu_mode.value and len(circuits) > 1: + intra_qpu_mode.value = True + num_circuits.value = len(circuits) + state.push_undo() + for c in circuits: + _apply_multi_candidate(c['circuit_idx'], c['chosen']) + _refresh() + _get_export() + + def _multi_summary_html(result): + parts = [] + for c in result['circuits']: + ch = c['chosen'] + k = len(ch['ancillas']) + pct, is_tmpl = _entry_lqs_pct(ch) + tmpl = ' (template)' if is_tmpl else '' + parts.append(f"C{c['circuit_idx'] + 1}: k={k} · {esc(pct)}{tmpl}") + if result.get('total_lqs_circuit') is not None: + parts.append(f"batch: {result['total_lqs_circuit'] * 100.0:.1f}%") + elif result.get('total_product') is not None: + parts.append(f"batch: {result['total_product'] * 100.0:.1f}% (template)") + return ' | '.join(parts) + + def _multi_failed_banner(result): + i = result.get('failed_at') + if i is None: + return "" + return ( + f"
⚠️ circuit {i + 1} does not fit after " + f"C1..C{i} + buffer — reduce norb or ancillas. The circuits that " + f"fit are placed above.
") + + def _multi_override_disabled(disabled): + for dd in _multi_sweep['dropdowns'].values(): + with contextlib.suppress(Exception): + dd.disabled = disabled + + def _make_multi_override_cb(i, flat): + def _cb(change): + idx = change['new'] + if idx is None or idx >= len(flat): + return + _on_multi_override(i, flat[idx]) + return _cb + + def _build_multi_override_dropdowns(result): + _multi_sweep['dropdowns'] = {} + widgets = [] + for c in result['circuits']: + i = c['circuit_idx'] + flat, opts = [], [] + for k in sorted(c['strata'].keys(), reverse=True): + for e in c['strata'][k]: + opts.append((_entry_label(e), len(flat))) + flat.append(e) + if not opts: + continue + chosen_idx = next((j for j, e in enumerate(flat) + if e is c['chosen']), 0) + dd = Dropdown(options=opts, value=chosen_idx, + description=f'C{i + 1} alternatives:', layout=W, + style={'description_width': 'initial'}) + dd.observe(_make_multi_override_cb(i, flat), names='value') + _multi_sweep['dropdowns'][i] = dd + widgets.append(dd) + if any(m.get('truncated') for m in c.get('per_stratum', {}).values()): + widgets.append(HTML( + f"
" + f"⚠️ C{i + 1}: search truncated — ranking may be " + f"non-exhaustive.
")) + lucj_multi_detail_box.children = widgets + + def _render_multi_sweep_output(result): + summary = _multi_summary_html(result) + lbl_lucj_multi.value = ( + f"
🧺 " + f"{len(result['circuits'])} circuit(s) placed " + f"(buffer={lucj_buffer_slider.value})
{summary}
" + + _multi_failed_banner(result)) + _build_multi_override_dropdowns(result) + + def _on_multi_override(i, choice): + if _multi_sweep['replan_in_flight']: + return # in-flight guard + result = _multi_sweep['result'] + if result is None: + return + _multi_sweep['replan_in_flight'] = True + _multi_override_disabled(True) + + def _work(): + from ..multi_sweep import replan_from + return replan_from(result, i, choice) + + def _done(new_result): + _multi_sweep['result'] = new_result + _apply_multi_sweep(new_result) + _multi_sweep['replan_in_flight'] = False + _render_multi_sweep_output(new_result) # rebuilds dropdowns (enabled) + + def _err(exc): + _multi_sweep['replan_in_flight'] = False + _multi_override_disabled(False) + lbl_lucj_multi.value = ( + f"
❌ replan failed: " + f"{esc(str(exc))}
") + + scan_spawn_bg(_work, on_done=_done, on_error=_err) + + def _on_lucj_multi_sweep(b): + if state.active_backend is None: + lbl_lucj_multi.value = ( + "❌ No backend " + "connected.") + return + if hasattr(state.active_backend, 'coords'): + lbl_lucj_multi.value = ( + "❌ Auto-LUCJ " + "requires a connected IBM backend.") + return + norbs, err = _parse_multi_norbs() + if err: + lbl_lucj_multi.value = err + return + min_bridges_list, err = _multi_min_bridges(norbs) + if err: + lbl_lucj_multi.value = err + return + + btn_lucj_multi_sweep.disabled = True + btn_lucj_multi_sweep.description = '⏳ Sweeping...' + lbl_lucj_multi.value = "" + kwargs = _sweep_kwargs_from_ui() + excl = _multi_stability_exclusions() + scoring_props = _local_scoring_props() + buffer = lucj_buffer_slider.value + + def _reset_btn(): + btn_lucj_multi_sweep.disabled = False + btn_lucj_multi_sweep.description = '🧺 Generate Multi-Circuit (sweep)' + + def _work(): + from ..multi_sweep import sweep_multi_circuits + return sweep_multi_circuits( + norbs, state.active_backend, scoring_props, + min_bridges=min_bridges_list, top_n=kwargs['top_n'], + buffer_qubits=buffer, exclude_qubits=excl, + mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], + diversity_threshold=kwargs['diversity_threshold'], + circuit_score_fn=_circuit_score) + + def _done(result): + _reset_btn() + _multi_sweep['result'] = result + _apply_multi_sweep(result) + _render_multi_sweep_output(result) + with contextlib.suppress(Exception): + ctx.update_view() + + def _err(exc): + _reset_btn() + lbl_lucj_multi.value = ( + f"
❌ Error: {esc(str(exc))}
") + + scan_spawn_bg(_work, on_done=_done, on_error=_err) + + btn_lucj_multi_sweep.on_click(_on_lucj_multi_sweep) + + # ── Batch scan: the whole multi-circuit batch on every QPU ───── + def _batch_backend_exclusions(props, name): + """Per-backend hard exclusions for a batch sweep: always-on floor on + THIS backend's props ∪ volatility (when the scan filter is on and the + backend has cached history).""" + excl = set(_floor_exclusions(props)) + if _stability_filter_active() and chk_scan_stability.value and name: + hist = _cached_history_for(name) + if hist: + from ..stability_filter import ( + compute_qubit_volatility, select_excluded) + vol = compute_qubit_volatility(hist, rb_stability_window.value) + excl |= set(select_excluded( + vol, threshold=ft_stability_threshold.value)) + return excl or None + + def _batch_metric(res): + """(value, is_template) — batch LQS = total_lqs_circuit, else product.""" + m = res.get('total_lqs_circuit') + if m is not None: + return m, False + return (res.get('total_product') or 0.0), True + + def _batch_ks(res): + return ', '.join(f"k={len(c['chosen']['ancillas'])}" + for c in res.get('circuits', [])) + + def _render_batch_results(scan_result): + head = ("" + "" + "" + "" + "" + "") + rows, detail_widgets = [], [] + for r in scan_result['results']: + name = esc(str(r['name'])) + if r.get('error'): + rows.append( + f"") + continue + res = r.get('sweep') or {} + m, is_tmpl = _batch_metric(res) + lqs = f"{m * 100.0:.1f}%{' (template)' if is_tmpl else ''}" + fa = res.get('failed_at') + fit = ('ok' if fa is None + else f"failed_at={fa}") + rows.append( + f"" + f"" + f"" + f"") + # Per-QPU expandable detail + a one-click handoff button. + if res.get('circuits'): + detail_widgets.append(HTML( + f"
" + f"{name} — {esc(_multi_summary_html(res))}
")) + btn = Button(description=f'📡 open {r["name"]} on QPU 2', + layout=W, button_style='') + chosen = [c['chosen'] for c in res['circuits']] + nm = r['name'] + btn.on_click(lambda _b, nm=nm, ch=chosen: _batch_handoff(nm, ch)) + detail_widgets.append(btn) + table = HTML(head + "".join(rows) + "
QPUbatch LQSper-circuit kfit
{name}✗ {esc(str(r['error']))}
{name}{esc(lqs)}{esc(_batch_ks(res))}{fit}
") + scan_batch_box.children = [table] + detail_widgets + + def _batch_handoff(backend_name, chosen_list): + hook = inter_qpu_handoff[0] if inter_qpu_handoff else None + if hook is None: + return + with contextlib.suppress(Exception): + hook(backend_name, chosen_list) # list → batch handoff + + def _on_scan_batch(b): + if state.active_backend is None: + lbl_lucj_multi.value = ( + "❌ No backend " + "connected.") + return + if state.active_service is None: + lbl_lucj_multi.value = ( + "❌ No service " + "connected — cannot scan other QPUs.") + return + norbs, err = _parse_multi_norbs() + if err: + lbl_lucj_multi.value = err + return + min_bridges_list, err = _multi_min_bridges(norbs) + if err: + lbl_lucj_multi.value = err + return + + btn_scan_batch.disabled = True + btn_scan_batch.description = '⏳ Scanning batch...' + scan_batch_box.children = [] + kwargs = _sweep_kwargs_from_ui() + buffer = lucj_buffer_slider.value + + def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): + from ..multi_sweep import sweep_multi_circuits + excl = _batch_backend_exclusions(props, getattr(backend, 'name', None)) + res = sweep_multi_circuits( + norbs, backend, props, buffer_qubits=buffer, + min_bridges=min_bridges_list, top_n=kwargs['top_n'], + mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], + diversity_threshold=kwargs['diversity_threshold'], + circuit_score_fn=_circuit_score, exclude_qubits=excl) + # Give scan_qpus a rankable 'strata' surface: the batch metric. + metric, _ = _batch_metric(res) + res['strata'] = {0: [{'product_score': metric}]} + return res + + def _reset(): + btn_scan_batch.disabled = False + btn_scan_batch.description = '🌐 Scan batch on all QPUs' + + def _work(): + from .. import qpu_scan + from ..qpu_scan import _detect_family + from ..props_shim import make_scan_get_props + try: + family = _detect_family(state.active_backend) + except Exception: + family = None + targets = qpu_scan.list_scan_targets( + state, norbs[0], same_family_as=family, + include_other_families=chk_scan_other_families.value) + get_backend = state.active_service.backend + get_props = make_scan_get_props(state) + return qpu_scan.scan_qpus( + targets, norbs[0], get_backend, get_props, + min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], + sweep_fn=_batch_sweep_fn) + + def _done(result): + _reset() + _render_batch_results(result) + + def _err(exc): + _reset() + lbl_lucj_multi.value = ( + f"
❌ batch scan " + f"failed: {esc(str(exc))}
") + + scan_spawn_bg(_work, on_done=_done, on_error=_err) + + btn_scan_batch.on_click(_on_scan_batch) + # ── Re-optimization ───────────────────────────────────── def _reoptimize_downstream(changed_idx): try: diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py new file mode 100644 index 0000000..b68ba2e --- /dev/null +++ b/tests/test_floor_batch_ui.py @@ -0,0 +1,238 @@ +"""Always-on quality floor (every path) + multi-circuit batch scan (UI). + +Headless: real MapperUIBuilder over a 16-qubit device (the floor needs +> OUTLIER_MIN_SAMPLES qubits to judge); engines monkeypatched. +""" +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Button + + +def _fake_device_16(state, vendor, chip, date, prefetched_props=None): + n = 16 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01] * n), np.array([0.001] * (n - 1))) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _canned(**extra): + e = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.4, + 'additive_score': 0.5, 'lqs_circuit': 0.4, 'rank_in_stratum': 1, + 'source': 'derived'} + res = {'strata': {1: [e]}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 5, + 'n_candidates_scored': 5, 'excluded_qubits': [], + 'per_stratum': {1: {'n_direct': 0, 'n_derived': 1, + 'truncated': False, 'shuffled': False}}, + 'mapping_cap': 2000} + res.update(extra) + return res + + +def _build(monkeypatch, spawn=_sync_spawn): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_16) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = ["ibm_a", "ibm_b"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + # current readout with one outlier at qubit 5 (16 samples → floor can judge). + ro = np.array([0.01] * 16) + ro[5] = 0.5 + state.qubit_props_data = {'readout_error': ro} + state.gate_props_data = {'cz_error': np.array([0.001] * 15)} + return b, state + + +# ── unfiltered single sweep excludes the outlier by default ────────── + +def test_floor_excludes_outlier_by_default(monkeypatch): + b, state = _build(monkeypatch) + cap = {} + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **k: cap.update(k) or _canned()) + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() + assert 5 in (cap.get('exclude_qubits') or set()) # floor removed q5 + assert 'floor excluded 1 outlier' in b.lbl_lucj_stability.value + + +# ── σ=0 → floor off ────────────────────────────────────────────────── + +def test_floor_off_at_sigma_zero(monkeypatch): + b, state = _build(monkeypatch) + cap = {} + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **k: cap.update(k) or _canned()) + b.ft_stability_floor.value = 0 # off + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + assert cap.get('exclude_qubits') is None + assert 'floor excluded' not in b.lbl_lucj_stability.value + + +# ── filter ON + floor → floor via quality_sigma, not double-excluded ─ + +def test_floor_and_filter_no_double(monkeypatch): + b, state = _build(monkeypatch, spawn=_sync_spawn) + state.cal_history = {'2026-07-01': {'qubit_props': {'readout_error': [0.01] * 16}, + 'gate_props': {}}} + sws = {} + monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + lambda *a, **k: sws.update(k) or _canned( + stability={'available': True, 'relaxed': False, + 'excluded_final': [5], 'window_days': 14, + 'n_floor_excluded': 1, 'floor_qubits': [5]})) + plain = [] + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: plain.append(k) or _canned()) + b.chk_stability_filter.disabled = False # history available + b.chk_stability_filter.value = True + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + # Filtered path used; the floor arrives through quality_sigma (not a second + # exclude_qubits pass), so the plain sweep is not called. + assert sws.get('quality_sigma') == 3.0 + assert plain == [] + + +# ── scan floor is per-backend (outlier only in one) ────────────────── + +def test_scan_floor_per_backend(monkeypatch): + b, state = _build(monkeypatch) + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) + # ibm_a props have an outlier at q5; ibm_b is clean. + ro_a = np.array([0.01] * 16); ro_a[5] = 0.5 + props = {'ibm_a': SimpleNamespace(_readout=ro_a, n_qubits=16, vintage='live', + score_layout=lambda q: {'fidelity': 0.5}), + 'ibm_b': SimpleNamespace(_readout=np.array([0.01] * 16), n_qubits=16, + vintage='live', + score_layout=lambda q: {'fidelity': 0.5})} + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: props[backend.name])) + seen = {} + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **k: seen.setdefault(bk.name, k) or _canned()) + b.btn_scan_qpus.click() + assert 5 in (seen['ibm_a'].get('exclude_qubits') or set()) + assert not (seen['ibm_b'].get('exclude_qubits') or set()) + + +# ── legacy single/multi buttons untouched by the floor ─────────────── + +def test_legacy_paths_untouched(monkeypatch): + b, state = _build(monkeypatch) + single = [] + monkeypatch.setattr("qpu_mapper.auto_lucj.get_all_zigzag_layouts", + lambda **k: single.append(k) or ([{'rank': 1, 'score': 0.1, + 'alpha': [0, 1], 'beta': [2, 3]}], 1)) + multi = [] + monkeypatch.setattr("qpu_mapper.auto_lucj.get_multi_circuit_layouts", + lambda **k: multi.append(k) or [ + {'circuit_idx': 0, 'norb': 8, 'num_bridges': 2, + 'all_candidates': [{'layout': [0, 1, 2, 3], + 'alpha': [0, 1], 'beta': [2, 3], + 'score': 0.03, 'rank': 1, + 'layout_full': [0, 1, 2, 3, 4]}]}]) + b.lucj_ancilla_dd.value = 2 # legacy single (not sweep) + b.btn_lucj_run.click() + b.lucj_multi_norbs.value = '8' + b.btn_lucj_multi.click() # legacy multi + assert len(single) == 1 # legacy engines called… + assert len(multi) == 1 + # …and neither legacy engine accepts/forwards a floor exclude set. + assert 'exclude_qubits' not in single[0] + assert 'exclude_qubits' not in multi[0] + + +# ── batch scan ────────────────────────────────────────────────────────── + +def _batch_result_row(name, total_lqs, ks, failed_at=None): + circuits = [{'circuit_idx': j, 'norb': 8, + 'chosen': {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [4 + j], + 'product_score': 0.5, 'lqs_circuit': 0.5}, + 'strata': {1: []}, 'per_stratum': {}} for j in range(ks)] + sweep = {'circuits': circuits, 'total_product': 0.5, 'total_lqs_circuit': total_lqs, + 'placed_qubits': [], 'buffer_qubits_used': [], 'failed_at': failed_at, + '_context': {}, 'strata': {0: [{'product_score': total_lqs}]}} + return {'name': name, 'family': 'Heron', 'sweep': sweep, + 'best_lqs': total_lqs, 'best_k': 0, 'error': None} + + +def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): + b, state = _build(monkeypatch) + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: []) + # scan_qpus returns a ready-ranked batch result (ibm_hi first). + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: {'results': [ + _batch_result_row('ibm_hi', 0.61, 2), + _batch_result_row('ibm_lo', 0.40, 2, failed_at=1)], + 'n_scanned': 2, 'n_failed': 0, 'n_skipped': 0}) + b.lucj_multi_norbs.value = '8, 8' + b.btn_scan_batch.click() + + table = b.scan_batch_box.children[0].value + assert table.index('ibm_hi') < table.index('ibm_lo') # sorted + assert '61.0%' in table and '40.0%' in table + assert 'failed_at=1' in table # labeled, not errored + assert '✗' not in table + + +def test_batch_scan_sweep_fn_gets_multi_knobs(monkeypatch): + b, state = _build(monkeypatch) + from qpu_mapper import qpu_scan as qs + from qpu_mapper import multi_sweep as ms + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: SimpleNamespace( + _readout=np.array([0.01] * 16), n_qubits=16, + vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) + seen = {} + monkeypatch.setattr(ms, 'sweep_multi_circuits', + lambda *a, **k: seen.update(kwargs=k, norbs=a[0]) or { + 'circuits': [], 'total_product': None, + 'total_lqs_circuit': None, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': 0, '_context': {}}) + b.lucj_top_n.value = 7 + b.lucj_search_cap.value = 5000 + b.chk_deep_search.value = False + b.chk_lucj_diverse.value = True + b.lucj_multi_norbs.value = '8, 6' + b.btn_scan_batch.click() + + assert seen['norbs'] == [8, 6] + k = seen['kwargs'] + assert k['top_n'] == 7 and k['mapping_cap'] == 5000 + assert k['hybrid'] is False and k['diversity_threshold'] == 0.8 diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py index 4be16a1..f51fb7e 100644 --- a/tests/test_inter_qpu_handoff.py +++ b/tests/test_inter_qpu_handoff.py @@ -185,3 +185,38 @@ def test_same_backend_applies_without_reconnect(monkeypatch): d = repaints[-1].layouts_data[0] assert d['alpha'] == ['3'] and d['beta'] == ['4'] and d['ancilla'] == ['5'] assert 'Applied to already-connected' in ctx.lbl_qpu2_status.value + + +# ── batch handoff: a LIST of candidates applies to C1..Cn on QPU-2 ────────── + +def test_batch_handoff_applies_all_circuits(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + captured = {} + + def _fake_build(s2, is_secondary=False, return_widgets=False): + captured['s2'] = s2 + s2.qubit_ids = [str(i) for i in range(8)] + s2.edges_list = [(0, 1)] + fig = SimpleNamespace() + fig_box2 = SimpleNamespace(children=[SimpleNamespace(), + SimpleNamespace(), fig]) + full_ui = SimpleNamespace(children=[SimpleNamespace(), fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'chip')) + monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + + ctx, state = _ctx(spawn=_sync_spawn, backend_calls=[]) + setup_inter_qpu(ctx) + batch = [{'alpha': [0], 'beta': [1], 'ancillas': [2]}, + {'alpha': [3], 'beta': [4], 'ancillas': [5]}] + ctx.handoff_cell[0]('ibm_k', batch) # LIST → batch handoff + + s2 = captured['s2'] + assert s2.layouts_data[0]['alpha'] == ['0'] and s2.layouts_data[0]['ancilla'] == ['2'] + assert s2.layouts_data[1]['alpha'] == ['3'] and s2.layouts_data[1]['ancilla'] == ['5'] diff --git a/tests/test_multi_sweep.py b/tests/test_multi_sweep.py new file mode 100644 index 0000000..71b0e92 --- /dev/null +++ b/tests/test_multi_sweep.py @@ -0,0 +1,195 @@ +"""Tests for qpu_mapper.multi_sweep — the sequential multi-circuit orchestrator. + +Offline, deterministic. Two synthetic hosts: + * TWO-BLOCK: two disjoint width-8 ladder blocks (ids 0..23 and 24..47), the + same host used by test_ancilla_sweep — one circuit lands in each block. + * CONNECTED: the two blocks joined by a single coupling edge, so the buffer + expansion actually reaches across the boundary (a real buffer test). +""" +from types import SimpleNamespace + +import rustworkx + +from qpu_mapper.multi_sweep import sweep_multi_circuits, replan_from + + +def _block(base, edges): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges += [(top[j], top[j + 1]), (bot[j], bot[j + 1])] + for j in range(8): + edges += [(top[j], brg[j]), (brg[j], bot[j])] + + +def _make_backend(link=None): + edges = [] + _block(0, edges) + _block(24, edges) + if link: + edges.append(link) + g = rustworkx.PyDiGraph() + for i in range(48): + g.add_node(i) + for u, v in edges: + g.add_edge(u, v, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=g), + operation_names=['cz', 'sx', 'rz', 'x'], name='host') + + +class _Props: + def readout_error(self, q): + return 0.01 + + def gate_error(self, name, edge): + return 0.005 + + +def _qubits(entry): + return set(entry['alpha']) | set(entry['beta']) | set(entry['ancillas']) + + +def _neighbors(backend): + """Undirected adjacency {q: {neighbours}} from the backend coupling graph.""" + adj = {} + for u, v in backend.coupling_map.graph.edge_list(): + adj.setdefault(u, set()).add(v) + adj.setdefault(v, set()).add(u) + return adj + + +# ── two circuits land in their own regions, no overlap, buffer clear ──── + +def test_two_circuits_disjoint_own_regions(): + bk = _make_backend() + res = sweep_multi_circuits([8, 8], bk, _Props(), buffer_qubits=1, + shuffle_seed=None) + assert res['failed_at'] is None and len(res['circuits']) == 2 + c0 = _qubits(res['circuits'][0]['chosen']) + c1 = _qubits(res['circuits'][1]['chosen']) + assert c0.isdisjoint(c1) # no qubit overlap + # Each circuit sits wholly in one block. + assert (max(c0) < 24) != (max(c1) < 24) + # Buffer respected: no circuit-1 qubit is a coupling neighbour of circuit-0. + adj = _neighbors(bk) + closed0 = set(c0) + for q in c0: + closed0|= adj.get(q, set()) + assert c1.isdisjoint(closed0) + + +def test_buffer_reaches_across_a_boundary(): + # Blocks joined at 7—24: the buffer of a circuit using the boundary must + # keep the neighbour clear. Assert the general 1-hop-buffer invariant. + bk = _make_backend(link=(7, 24)) + res = sweep_multi_circuits([8, 8], bk, _Props(), buffer_qubits=1, + shuffle_seed=None) + assert len(res['circuits']) == 2 + c0 = _qubits(res['circuits'][0]['chosen']) + c1 = _qubits(res['circuits'][1]['chosen']) + adj = _neighbors(bk) + for q in c0: + assert c1.isdisjoint(adj.get(q, set())), \ + "a circuit-1 qubit is adjacent to circuit-0 (buffer not applied)" + + +# ── total_product == product of the chosen entries' product_scores ────── + +def test_total_product_is_product_of_chosen(): + res = sweep_multi_circuits([8, 8], _make_backend(), _Props(), + shuffle_seed=None) + expect = 1.0 + for c in res['circuits']: + expect *= c['chosen']['product_score'] + assert abs(res['total_product'] - expect) < 1e-12 + + +# ── later circuit's WHOLE strata avoid the earlier region ∪ buffer ────── + +def test_sequential_exclusion_covers_all_strata(): + bk = _make_backend() + res = sweep_multi_circuits([8, 8], bk, _Props(), buffer_qubits=1, + shuffle_seed=None) + c0 = _qubits(res['circuits'][0]['chosen']) + adj = _neighbors(bk) + forbidden = set(c0) + for q in c0: + forbidden |= adj.get(q, set()) + # EVERY candidate in circuit 1's strata avoids circuit 0's region + buffer. + for entries in res['circuits'][1]['strata'].values(): + for e in entries: + assert _qubits(e).isdisjoint(forbidden) + + +# ── fit failure is honest — failed_at set, partial returned, no raise ─── + +def test_fit_failure_sets_failed_at(): + res = sweep_multi_circuits([8, 8, 8], _make_backend(), _Props(), + shuffle_seed=None) + assert res['failed_at'] == 2 # third circuit cannot fit + assert len(res['circuits']) == 2 # first two placed + assert res['total_product'] is not None # partial product over placed + + +# ── replan_from overrides a circuit and re-sweeps the tail ────────────── + +def test_replan_from_reoptimizes_tail(): + bk = _make_backend() + res = sweep_multi_circuits([8, 8], bk, _Props(), shuffle_seed=None) + c1_before = _qubits(res['circuits'][1]['chosen']) + + # An override for circuit 0 in the OTHER block than it originally chose. + orig0 = _qubits(res['circuits'][0]['chosen']) + orig0_low = max(orig0) < 24 + other = None + for entries in res['circuits'][0]['strata'].values(): + for e in entries: + if (max(_qubits(e)) < 24) != orig0_low: # the other block + other = e + break + if other: + break + assert other is not None, "expected a circuit-0 candidate in the other block" + + res2 = replan_from(res, 0, other) + # Circuit 0 is now the override; circuit 1 re-swept to the freed region. + assert res2['circuits'][0]['chosen'] is other + c0_after = _qubits(res2['circuits'][0]['chosen']) + c1_after = _qubits(res2['circuits'][1]['chosen']) + assert c0_after.isdisjoint(c1_after) + # Circuit 1 moved to the block circuit 0 vacated → different from before. + assert c1_after != c1_before + + +# ── knob forwarding — per-circuit min_bridges + stability exclusions ──── + +def test_min_bridges_list_applies_per_circuit(): + res = sweep_multi_circuits([8, 8], _make_backend(), _Props(), + min_bridges=[1, 2], shuffle_seed=None) + assert min(res['circuits'][0]['strata']) == 1 # floor 1 → k=2,1 + assert min(res['circuits'][1]['strata']) == 2 # floor 2 → k=2 only + + +def test_stability_exclusions_compose(): + # Pre-exclude a chain qubit in block A; it must appear in NO circuit. + res = sweep_multi_circuits([8, 8], _make_backend(), _Props(), + exclude_qubits={0, 1, 2}, shuffle_seed=None) + placed = set(res['placed_qubits']) + assert placed.isdisjoint({0, 1, 2}) + + +# ── determinism — same inputs + seed → identical result ───────────────── + +def test_determinism(): + def run(): + return sweep_multi_circuits([8, 8], _make_backend(), _Props(), + shuffle_seed=7) + a, b = run(), run() + + def sig(r): + return [(_qubits(c['chosen']), round(c['chosen']['product_score'], 12)) + for c in r['circuits']] + assert sig(a) == sig(b) + assert a['placed_qubits'] == b['placed_qubits'] + assert a['buffer_qubits_used'] == b['buffer_qubits_used'] diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py new file mode 100644 index 0000000..fd3f2d7 --- /dev/null +++ b/tests/test_multi_sweep_ui.py @@ -0,0 +1,254 @@ +"""Headless tests for the sweep-based Multi-Circuit UI (auto-best + override). + +Offline: real MapperUIBuilder over a stubbed 8-qubit device; the engine +(multi_sweep.sweep_multi_circuits / replan_from) is monkeypatched with canned +dicts, and the background spawn is injected (sync or a manual queue). +""" +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Dropdown + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _entry(anc, prod, lqs=None, rank=1): + e = {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': list(anc), + 'bridge_slots': tuple(range(0, 4 * len(anc), 4)), + 'product_score': prod, 'additive_score': 0.5, + 'rank_in_stratum': rank, 'source': 'vf2'} + if lqs is not None: + e['lqs_circuit'] = lqs + return e + + +def _circuit(i, chosen, strata, truncated=False): + return {'circuit_idx': i, 'norb': 8, 'chosen': chosen, 'strata': strata, + 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': truncated, + 'per_stratum': {1: {'n_direct': 0, 'n_derived': len(strata.get(1, [])), + 'truncated': truncated, 'shuffled': False}}, + 'mapping_cap': 2000, 'excluded_qubits': []} + + +def _result(failed_at=None): + """2-circuit canned result; circuit 0 has a #2 alternative for override.""" + c0_chosen = _entry([4], 0.60, lqs=0.612, rank=1) + c0_alt = _entry([5], 0.55, lqs=0.500, rank=2) + c1_chosen = _entry([6], 0.58, lqs=0.584, rank=1) + circuits = [_circuit(0, c0_chosen, {1: [c0_chosen, c0_alt]})] + total_lqs = 0.612 + total_prod = 0.60 + if failed_at is None: + circuits.append(_circuit(1, c1_chosen, {1: [c1_chosen]})) + total_lqs = 0.612 * 0.584 + total_prod = 0.60 * 0.58 + return {'circuits': circuits, 'total_product': total_prod, + 'total_lqs_circuit': total_lqs, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': failed_at, + '_context': {'stub': True}}, c0_alt + + +def _build(monkeypatch, spawn=_sync_spawn): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() # no .coords → Auto allowed + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b, state + + +def _patch_engine(monkeypatch, result): + import qpu_mapper.multi_sweep as ms + seen = {} + monkeypatch.setattr(ms, 'sweep_multi_circuits', + lambda *a, **k: seen.update(sweep_kwargs=k, sweep_args=a) or result) + return seen + + +def _dropdowns(box): + return [c for c in box.children if isinstance(c, Dropdown)] + + +# ── happy path — both applied, summary exact, dropdowns collapsed ──────── + +def test_multi_sweep_happy_path(monkeypatch): + b, state = _build(monkeypatch) + result, _ = _result() + _patch_engine(monkeypatch, result) + + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + # Both circuits applied to state (α/β/ancilla painted). + assert state.layouts_data[0]['alpha'] == ['0', '1'] + assert state.layouts_data[0]['ancilla'] == ['4'] + assert state.layouts_data[1]['ancilla'] == ['6'] + # Summary format exact. + v = b.lbl_lucj_multi.value + assert 'C1: k=1 · 61.2%' in v + assert 'C2: k=1 · 58.4%' in v + assert 'batch: 35.7%' in v # 0.612*0.584 = 0.3574 + # One collapsed dropdown per circuit, showing the chosen entry's label. + dds = _dropdowns(b.lucj_multi_detail_box) + assert len(dds) == 2 + assert dds[0].value == 0 # chosen (#1) selected + assert 'k=1 · #1 · LQS 61.2%' in dds[0].options[0][0] + assert 'k=1 · #2 · LQS 50.0%' in dds[0].options[1][0] + assert b.btn_lucj_multi_sweep.disabled is False # re-armed + + +# ── override — replan_from(result, 0, alt) re-applies + updates summary ── + +def test_multi_sweep_override(monkeypatch): + b, state = _build(monkeypatch) + result, c0_alt = _result() + _patch_engine(monkeypatch, result) + import qpu_mapper.multi_sweep as ms + calls = [] + # replan returns a new result where C0 = the alt and C1 re-swept. + new_c0 = _circuit(0, c0_alt, {1: [c0_alt]}) + new_c1 = _circuit(1, _entry([7], 0.57, lqs=0.570), {1: [_entry([7], 0.57, lqs=0.570)]}) + new_result = {'circuits': [new_c0, new_c1], 'total_product': 0.55 * 0.57, + 'total_lqs_circuit': 0.500 * 0.570, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': None, + '_context': {'stub': True}} + monkeypatch.setattr(ms, 'replan_from', + lambda res, i, choice: calls.append((i, choice)) or new_result) + + b.btn_lucj_multi_sweep.click() + dds = _dropdowns(b.lucj_multi_detail_box) + dds[0].value = 1 # pick C0's #2 (the alt) + + assert len(calls) == 1 + assert calls[0][0] == 0 and calls[0][1] is c0_alt # replan_from(result, 0, alt) + # Re-applied: C0 now the alt (ancilla 5), C1 re-swept (ancilla 7). + assert state.layouts_data[0]['ancilla'] == ['5'] + assert state.layouts_data[1]['ancilla'] == ['7'] + assert 'C2: k=1 · 57.0%' in b.lbl_lucj_multi.value # summary refreshed + + +# ── failed_at — banner + partial application ──────────────────────────── + +def test_multi_sweep_failed_at(monkeypatch): + b, state = _build(monkeypatch) + result, _ = _result(failed_at=1) # circuit 2 doesn't fit + _patch_engine(monkeypatch, result) + + b.btn_lucj_multi_sweep.click() + v = b.lbl_lucj_multi.value + assert 'circuit 2 does not fit' in v + assert state.layouts_data[0]['ancilla'] == ['4'] # C1 still applied + assert len(_dropdowns(b.lucj_multi_detail_box)) == 1 # only the placed one + + +# ── in-flight guard — a second override during replan → single call ───── + +def test_multi_sweep_override_in_flight_guard(monkeypatch): + queued = [] + + def qspawn(fn, on_done=None, on_error=None): + queued.append((fn, on_done, on_error)) + + b, state = _build(monkeypatch, spawn=qspawn) + result, _ = _result() + _patch_engine(monkeypatch, result) + import qpu_mapper.multi_sweep as ms + monkeypatch.setattr(ms, 'replan_from', lambda res, i, choice: result) + + b.btn_lucj_multi_sweep.click() + # Drain the initial sweep so the dropdowns exist. + fn, done, _ = queued.pop(0) + done(fn()) + dds = _dropdowns(b.lucj_multi_detail_box) + + dds[0].value = 1 # override → queues a replan + assert len(queued) == 1 + dds[0].value = 0 # second, while in flight + assert len(queued) == 1 # guarded — no second spawn + + +# ── kwargs parity — multi-sweep gets the same knobs as the local sweep ── + +def test_multi_sweep_kwargs_parity(monkeypatch): + b, state = _build(monkeypatch) + result, _ = _result() + seen = _patch_engine(monkeypatch, result) + local = {} + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **k: local.update(k) or result['circuits'][0] + and {'strata': {}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 0, + 'n_candidates_scored': 0, 'excluded_qubits': [], + 'per_stratum': {}, 'mapping_cap': None}) + + b.lucj_top_n.value = 7 + b.lucj_search_cap.value = 5000 + b.chk_deep_search.value = False + b.chk_lucj_diverse.value = True + + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() # local sweep + b.btn_lucj_multi_sweep.click() # multi sweep + + mk = seen['sweep_kwargs'] + for key in ('top_n', 'hybrid', 'mapping_cap', 'diversity_threshold'): + assert mk[key] == local[key], key + assert mk['top_n'] == 7 and mk['mapping_cap'] == 5000 + assert mk['hybrid'] is False and mk['diversity_threshold'] == 0.8 + + +# ── legacy Generate untouched — still calls the old engine ────────────── + +def test_legacy_multi_button_unchanged(monkeypatch): + b, state = _build(monkeypatch) + calls = [] + monkeypatch.setattr("qpu_mapper.auto_lucj.get_multi_circuit_layouts", + lambda **k: calls.append(k) or [ + {'circuit_idx': 0, 'norb': 8, 'num_bridges': 2, + 'all_candidates': [{'layout': [0, 1, 2, 3], + 'alpha': [0, 1], 'beta': [2, 3], + 'score': 0.03, 'rank': 1, + 'layout_full': [0, 1, 2, 3, 4]}]}]) + ms_calls = [] + import qpu_mapper.multi_sweep as ms + monkeypatch.setattr(ms, 'sweep_multi_circuits', + lambda *a, **k: ms_calls.append(1) or _result()[0]) + + b.lucj_multi_norbs.value = '8' + b.btn_lucj_multi.click() # LEGACY button + + assert len(calls) == 1 # old engine called + assert ms_calls == [] # sweep engine NOT called From c93e17ff8c9ff7176e635aba1f1c271d5e497b34 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 14 Jul 2026 22:34:08 -0400 Subject: [PATCH 21/66] UI hardening: scan selector, stable subpanels, notices capture, handoff paint fix --- qpu_mapper/ui/builder.py | 184 +++++++-- qpu_mapper/ui/inter_qpu.py | 22 +- qpu_mapper/ui/lucj_panel.py | 604 +++++++++++++++++------------ tests/test_auto_subpanels.py | 137 +++++++ tests/test_floor_batch_ui.py | 51 ++- tests/test_import_export_ui.py | 107 +++++ tests/test_inter_qpu_handoff.py | 78 ++++ tests/test_scan_notices.py | 14 +- tests/test_scan_targets_line.py | 123 ++++++ tests/test_scan_ui.py | 107 +++-- tests/test_scan_ui_pass.py | 241 ++++++++++++ tests/test_stability_ui.py | 24 +- tests/test_subpanel_persistence.py | 245 ++++++++++++ tests/test_sweep_notices.py | 214 ++++++++++ tests/test_sweep_ui.py | 30 ++ tests/test_ui_cleanup.py | 8 +- 16 files changed, 1844 insertions(+), 345 deletions(-) create mode 100644 tests/test_auto_subpanels.py create mode 100644 tests/test_import_export_ui.py create mode 100644 tests/test_scan_targets_line.py create mode 100644 tests/test_scan_ui_pass.py create mode 100644 tests/test_subpanel_persistence.py create mode 100644 tests/test_sweep_notices.py diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index d0c5e30..34fd7a9 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -310,6 +310,7 @@ def _run_pipeline(self): chk_lucj_diverse=self.chk_lucj_diverse, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, + lbl_lucj_notices=self.lbl_lucj_notices, dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, @@ -319,8 +320,10 @@ def _run_pipeline(self): btn_scan_batch=self.btn_scan_batch, scan_batch_box=self.scan_batch_box, lbl_lucj_multi=self.lbl_lucj_multi, + lbl_lucj_multi_notices=self.lbl_lucj_multi_notices, lucj_multi_detail_box=self.lucj_multi_detail_box, num_circuits=self.num_circuits, intra_qpu_mode=self.intra_qpu_mode, dd_mode=self.dd_mode, + set_num_circuits=self._set_num_circuits_silent, lucj_all_layouts=self._lucj_all_layouts, lucj_multi_results=self._lucj_multi_results, lucj_multi_norbs_list=self._lucj_multi_norbs, @@ -820,9 +823,9 @@ def _build_navigation_widgets(self): ) self.nav_bar = ToggleButtons( options=[ - ('✏️ Layout', 'manual'), ('📂 Load', 'auto'), + ('✏️ Layout', 'manual'), ('🤖 Auto', 'auto_lucj'), - ('📤 Export', 'export'), ('🔍 Error', 'error_inspect'), + ('📁 I/O', 'io'), ('🔍 Error', 'error_inspect'), ], value='manual', style={'button_width': '120px'}, ) @@ -1271,6 +1274,9 @@ def _build_auto_lucj_widgets(self, W): self.lbl_lucj_status = HTML("") # Sweep truncation banner (VF2 cap hit); empty/hidden otherwise. self.lbl_lucj_trunc = HTML("") + # Captured WARNING+ from the local sweep (loud notices bar); empty when + # the sweep emitted nothing. + self.lbl_lucj_notices = HTML("") # ── Stability filter (opt-in) ──────────────────────────── self.chk_stability_filter = Checkbox( @@ -1345,29 +1351,30 @@ def _build_auto_lucj_widgets(self, W): value='8, 8', description='norb per circuit:', placeholder='e.g. 8, 8 or 10, 10, 6', layout=W, style={'description_width': 'initial'}) - # Per-circuit ancilla (bridge) counts, parallel to norb. Blank → - # the single Ancilla dropdown applies to every circuit (legacy); - # otherwise one value per circuit (-1 = auto for that circuit). + # Per-circuit MIN ancillas (bridge floor) for the sweep, parallel to + # norb. Blank → auto per circuit; otherwise one value per circuit. self.lucj_multi_ancillas = Text( - value='', description='ancilla per circuit:', - placeholder='blank = use Ancilla above; or e.g. 2, 2 (-1 = auto)', + value='', description='min ancillas per circuit:', + placeholder='blank = auto; or e.g. 2, 2', layout=W, style={'description_width': 'initial'}, - tooltip='Legacy Generate: exact bridge count per circuit. ' - 'Sweep (🧺): per-circuit min ancillas (floor); ' - 'blank = engine default.') + tooltip='min ancillas per circuit (blank = auto)') # Buffer qubits: tiny range 0-5, numeric input is more direct. self.lucj_buffer_slider = BoundedIntText( value=1, min=0, max=5, description='Buffer qubits:', layout=Layout(width='220px'), style={'description_width': '110px'}) + # Legacy multi-circuit button — no longer shown in the Multi subpanel + # (the sweep is the single generate action). The widget + its handler + # (_on_lucj_multi) and engine (get_multi_circuit_layouts) stay wired and + # test-pinned; it is simply omitted from the layout below. self.btn_lucj_multi = Button( description='🤖 Generate Multi-Circuit', button_style='success', layout=W) - # Sweep-based multi-circuit: greedy auto-best per circuit with a - # per-circuit override dropdown (uses the ancilla sweep + buffer). + # Sweep-based multi-circuit (the ONLY multi generate action in the UI): + # greedy auto-best per circuit with a per-circuit override dropdown. self.btn_lucj_multi_sweep = Button( - description='🧺 Generate Multi-Circuit (sweep)', + description='🧺 Generate Multi-Circuit', button_style='info', layout=W) # Batch scan: run the whole multi-circuit batch on every compatible QPU. self.btn_scan_batch = Button( @@ -1377,6 +1384,9 @@ def _build_auto_lucj_widgets(self, W): 'backend and rank by batch fidelity') self.scan_batch_box = VBox([]) self.lbl_lucj_multi = HTML("") + # Captured WARNING+ from the multi-circuit sweep + replan (loud notices + # bar); empty when nothing was emitted. + self.lbl_lucj_multi_notices = HTML("") # Populated dynamically with per-circuit dropdowns when the # user clicks btn_lucj_multi. self.lucj_multi_detail_box = VBox() @@ -1648,6 +1658,9 @@ def _build_export_widgets(self, W): description='📤 Export PNG (HQ)', button_style='primary', layout=W) self.json_preview = HTML("") + # JSON preview starts collapsed; the open/closed choice persists for + # the session (the Export subpanel is rebuilt on every nav switch). + self._json_preview_open = False # Shared "Save folder" for every export (PNG / JSON / session / # style / GIF/MP4). Plain Text field — user types a path @@ -1730,6 +1743,25 @@ def _refresh_stability_filter_availability(self): self.chk_stability_filter.tooltip = ( 'Fetch calibration history first (Stability Check / Multi-day)') + @staticmethod + def _restore_tab_index(prev, tabs): + """Carry a Tab's ``selected_index`` across a from-scratch rebuild. + + Every structural refresh (num_circuits / dd_mode / intra_qpu_mode + observers, ``_toggle_intra_qpu``, an explicit ``update_view`` from the + multi Generate flow) funnels through the ``_build_*_view`` methods, + each of which mints a FRESH ``Tab`` whose ``selected_index`` defaults to + 0 — bouncing the user off whatever subpanel they were on (e.g. Multi → + Single mid-Generate). Restoring the previous index at this single choke + point fixes every current and future trigger. Clamped to the new child + count so a shrink (e.g. intra_qpu OFF drops the Multi subpanel) can't + point past the end. First build (prev is None) keeps the default 0.""" + prev_idx = getattr(prev, 'selected_index', None) + n = len(tabs.children) + if prev_idx is not None and n: + tabs.selected_index = min(prev_idx, n - 1) + return tabs + def _build_auto_lucj_view(self): """Build the 'Auto' nav tab view (LUCJ chemistry mode). @@ -1744,14 +1776,13 @@ def _build_auto_lucj_view(self): falls back to the dropdown). """ self._refresh_stability_filter_availability() + prev_tabs = getattr(self, '_auto_lucj_tabs', None) name = esc(str(getattr(self.state, 'active_backend_name', '') or 'current backend')) - return VBox([ - HTML("
" - "🤖 Auto-LUCJ Layout Engine
"), - HTML("
"), - HTML("
" - "🔬 Single Circuit
"), + # Subpanel 1 — "Single Circuit": everything except the Multi-Circuit + # section (single-circuit controls + the local results + the scan + # block). Mirrors the Error tab's Tab-based subpanel switcher. + single_panel = VBox([ self.lucj_norb_slider, self.lucj_ancilla_dd, self.lucj_min_ancilla, @@ -1767,13 +1798,12 @@ def _build_auto_lucj_view(self): self.btn_lucj_run, self.lbl_lucj_trunc, self.lbl_lucj_status, - # ── Local (current backend) results — ABOVE the scan block ── + self.lbl_lucj_notices, HTML("
"), HTML(f"
📍 This backend ({name})
"), self.dd_lucj_layout, self.lbl_lucj_detail, - # ── Remote scan block — its own header + Clear control ────── HTML("
"), HBox([ HTML("
"), - HTML("
" - "🔗 Multi-Circuit (Multi-Programming)
"), + ], layout=Layout(padding='6px')) + # Subpanel 2 — "Multi-Circuit": revealed only while Multi-Programming + # (intra-QPU) is enabled; the enable checkbox rebuilds this view. + multi_panel = VBox([ self.lucj_multi_norbs, self.lucj_multi_ancillas, self.lucj_buffer_slider, - self.btn_lucj_multi, + # Legacy btn_lucj_multi intentionally omitted — the sweep button is + # the single generate action. Handler/engine remain wired + pinned. self.btn_lucj_multi_sweep, self.btn_scan_batch, self.lbl_lucj_multi, + self.lbl_lucj_multi_notices, self.lucj_multi_detail_box, self.scan_batch_box, ], layout=Layout(padding='6px')) + self._auto_single_panel = single_panel + self._auto_multi_panel = multi_panel + if self.intra_qpu_mode.value: + tabs = Tab(children=[single_panel, multi_panel]) + tabs.set_title(0, '🔬 Single Circuit') + tabs.set_title(1, '🔗 Multi-Circuit') + else: + tabs = Tab(children=[single_panel]) + tabs.set_title(0, '🔬 Single Circuit') + # Keep the user on the subpanel they were viewing across rebuilds. + self._auto_lucj_tabs = self._restore_tab_index(prev_tabs, tabs) + return VBox([ + HTML("
🤖 Auto-LUCJ Layout Engine
"), + HTML("
"), + tabs, + ], layout=Layout(padding='6px')) + + def _on_json_preview_toggle(self, change): + """Persist the JSON-preview open/closed choice; refresh on expand.""" + self._json_preview_open = change['new'] is not None + if self._json_preview_open: + self._get_export() + + def _build_import_export_view(self): + """The unified '📁 I/O' nav tab: an Export subpanel and an + Import subpanel (the former '📂 Load' view), switched via a Tab — the + same pattern as the Error / Auto tabs.""" + prev_tabs = getattr(self, '_io_tabs', None) + io_tabs = Tab(children=[self._build_export_view(), + self._build_auto_view()]) + io_tabs.set_title(0, '📤 Export') + io_tabs.set_title(1, '📥 Import') + # Same class of bug as the Auto tab: a refresh while the user is on the + # Import subpanel would otherwise snap back to Export. + self._io_tabs = self._restore_tab_index(prev_tabs, io_tabs) + return io_tabs def _build_export_view(self): - """Build the 'Export' nav tab view. Aggregates every export/save - control: live JSON preview, Export Layout (JSON), Export PNG - (popup wired by ``setup_png_export``), Export Session, Export - Style Preset, Export Time-Lapse. - """ + """Build the Export subpanel: JSON preview (collapsible), Export Layout + (JSON), Export PNG, Export Session, Export Style Preset, Export + Time-Lapse. + """ + preview = Accordion(children=[self.json_preview]) + preview.set_title(0, 'JSON preview') + preview.selected_index = 0 if self._json_preview_open else None + preview.observe(self._on_json_preview_toggle, names='selected_index') return VBox([ HTML("
📁 Save folder (applies to every export below)
"), self.save_folder, HTML("
"), - HTML("
📋 JSON Preview
"), - self.json_preview, + preview, HTML("
"), HTML("
📤 Export Layout
"), self.export_format, @@ -1929,6 +2001,10 @@ def _build_error_view(self): _err_tabs = Tab(children=[_err_tab_map, _err_tab_analysis]) _err_tabs.set_title(0, '🔍 Calibration') _err_tabs.set_title(1, '🏆 Analysis') + # Preserve the Calibration/Analysis subtab across rebuilds (same class + # of bug as the Auto/I/O tabs). + self._err_tabs = self._restore_tab_index( + getattr(self, '_err_tabs', None), _err_tabs) return _err_tabs def _refresh(self, *args): @@ -2494,11 +2570,13 @@ def _load_device_graph(self, change=None, force=False): self.dd_lucj_layout.options = [] self.dd_lucj_layout.disabled = True self.lbl_lucj_status.value = "" + self.lbl_lucj_notices.value = "" self.lbl_lucj_detail.value = "" self._lucj_multi_results.clear() self._lucj_multi_norbs.clear() self._lucj_multi_dropdowns.clear() self.lbl_lucj_multi.value = "" + self.lbl_lucj_multi_notices.value = "" self.lucj_multi_detail_box.children = () # {} (not None) for delta props — plot.py readers guard on @@ -2573,12 +2651,12 @@ def _update_view(self, change=None): # Update nav bar: hide Auto-LUCJ in general mode is_lucj = self.dd_mode.value == 'lucj' if is_lucj: - new_opts = [('✏️ Layout', 'manual'), ('📂 Load', 'auto'), - ('🤖 Auto', 'auto_lucj'), - ('📤 Export', 'export'), ('🔍 Error', 'error_inspect')] + new_opts = [('✏️ Layout', 'manual'), ('🤖 Auto', 'auto_lucj'), + ('📁 I/O', 'io'), + ('🔍 Error', 'error_inspect')] else: - new_opts = [('✏️ Layout', 'manual'), ('📂 Load', 'auto'), - ('📤 Export', 'export'), ('🔍 Error', 'error_inspect')] + new_opts = [('✏️ Layout', 'manual'), ('📁 I/O', 'io'), + ('🔍 Error', 'error_inspect')] current_vals = [v for _, v in self.nav_bar.options] new_vals = [v for _, v in new_opts] if current_vals != new_vals: @@ -2611,14 +2689,13 @@ def _update_view(self, change=None): self._ext_fns["update_grank"]() if mode == 'manual': self.content_box.children = [self._build_manual_view()] - elif mode == 'auto': - self.content_box.children = [self._build_auto_view()] elif mode == 'auto_lucj': self.content_box.children = [self._build_auto_lucj_view()] - elif mode == 'export': + elif mode == 'io': + # Unified Import / Export tab (Export + former Load subpanels). self._get_export() self._ext_fns["update_fidelity"]() - self.content_box.children = [self._build_export_view()] + self.content_box.children = [self._build_import_export_view()] elif mode == 'error_inspect': self.content_box.children = [self._build_error_view()] @@ -2698,6 +2775,31 @@ def _enable_export_gif(self): _log.exception( "update_fidelity failed after history load") + def _set_num_circuits_silent(self, n): + """Set ``num_circuits`` WITHOUT the full ``_update_view`` rebuild its + observer would fire — used when a multi-circuit sweep/legacy apply + changes the count as a RESULT of its own action. + + The visible Multi subpanel is already updated in place (its summary and + per-circuit override dropdowns are persistent widgets refreshed by the + caller), so rebuilding ``content_box`` would only repaint an identical + panel — the flicker X2b targets. A count change genuinely needs just the + OFF-SCREEN refresh: the per-circuit manual UI + the ancilla-tool + options — exactly what ``_build_dynamic_ui`` does (it never touches + ``content_box``). The nav options don't depend on ``num_circuits`` (only + on ``dd_mode``), so they need no refresh here. + + The unobserve→set→observe idiom (same as ``_update_view``'s nav-bar + reseed) silences only THIS assignment; the ``_restore_tab_index`` helper + still guards every legitimate full rebuild (checkbox toggles, nav + switches).""" + self.num_circuits.unobserve(self._update_view, 'value') + try: + self.num_circuits.value = n + finally: + self.num_circuits.observe(self._update_view, 'value') + self._build_dynamic_ui() + def _toggle_intra_qpu(self, change): """Observer for ``intra_qpu_mode`` — enable/disable num_circuits + refresh view.""" self.num_circuits.disabled = not change['new'] diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index 40d37ce..c272c67 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -370,14 +370,6 @@ def _on_connect_qpu2(b): s2.props_warning = props_warn s2.active_coords = new_coords - # if this connect was staged from a scan pick for this - # backend, pre-load the chosen candidate so QPU-2 paints it. - pend = _pending_handoff[0] - if pend is not None and pend[0] == backend_name: - with contextlib.suppress(Exception): - _apply_candidate_to_state(s2, pend[1]) - _pending_handoff[0] = None - # Build the FULL secondary UI — feature-parity with QPU 1. # build_mapper_ui internally calls _load_device_graph which # populates s2.x_coord / qubit_ids / edges_list from props, @@ -385,6 +377,20 @@ def _on_connect_qpu2(b): # ahead of time anymore. full_ui_2, f2, w2 = build_mapper_ui( s2, is_secondary=True, return_widgets=True) + + # If this connect was staged from a scan pick for THIS backend, + # paint the chosen candidate now — AFTER the build. Applying it + # before build_mapper_ui was a silent no-op: _load_device_graph + # calls state.clear_all_layouts(), wiping any pre-loaded slot, so + # the candidate never reached the first paint. Apply post-clear and + # repaint the figure so it shows on the very first view. + pend = _pending_handoff[0] + if pend is not None and pend[0] == backend_name: + with contextlib.suppress(Exception): + _apply_candidate_to_state(s2, pend[1]) + from .. import plot as _plot + _plot.refresh_plot(f2, s2, w2) + _pending_handoff[0] = None # Top-level shape: HBox([ui_sidebar, fig_box]). # fig_box.children = (lbl_fig1, zoom_bar, fig). # diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index 032cb95..a95d806 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -7,7 +7,7 @@ import contextlib import logging -from ipywidgets import Button, Dropdown, HTML +from ipywidgets import Button, Dropdown, HBox, HTML, Layout from ..constants import hex_to_rgba from ..html_safe import esc @@ -91,6 +91,36 @@ def emit(self, record): pass +@contextlib.contextmanager +def _capture_qpu_notices(context_getter): + """Capture WARNING+ records off the 'qpu_mapper' logger for the duration of + a sweep and stop them leaking under the notebook cell (propagate=False). + Attaches the handler in the try; restores BOTH the handler and propagate in + finally, so a raising sweep can't leave the logger muted or double-handled. + Yields the handler — read `handler.records` (a list of (context, message)) + after (or inside) the block. + + Shared by every sweep path: the multi-QPU scan, the local single sweep, and + the multi-circuit sweep + replan. Restoration is the try/finally guarantee + the tests pin.""" + logger = logging.getLogger('qpu_mapper') + orig_propagate = logger.propagate + handler = _ScanNoticeCapture(context_getter) + try: + logger.addHandler(handler) + logger.propagate = False + except Exception: + pass + try: + yield handler + finally: + try: + logger.removeHandler(handler) + logger.propagate = orig_propagate + except Exception: + pass + + def setup_lucj_callbacks(ctx): """Wire all LUCJ-related callbacks. Called from ui.py after widget creation.""" @@ -110,6 +140,7 @@ def setup_lucj_callbacks(ctx): btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status lbl_lucj_trunc = ctx.lbl_lucj_trunc + lbl_lucj_notices = ctx.lbl_lucj_notices dd_lucj_layout = ctx.dd_lucj_layout lbl_lucj_detail = ctx.lbl_lucj_detail @@ -121,9 +152,11 @@ def setup_lucj_callbacks(ctx): btn_scan_batch = ctx.btn_scan_batch scan_batch_box = ctx.scan_batch_box lbl_lucj_multi = ctx.lbl_lucj_multi + lbl_lucj_multi_notices = ctx.lbl_lucj_multi_notices lucj_multi_detail_box = ctx.lucj_multi_detail_box num_circuits = ctx.num_circuits + set_num_circuits = ctx.set_num_circuits # count change w/o full view rebuild intra_qpu_mode = ctx.intra_qpu_mode _lucj_all_layouts = ctx.lucj_all_layouts @@ -231,23 +264,22 @@ def _on_lucj_layout_select(change): f"{scale}; internal ranking " f"sum {entry['additive_score']:.4f}, " f"{esc(str(entry.get('source', '')))}") - anc = ', '.join(str(q) for q in entry['ancillas']) + # Compact counts only — the placed qubit ids live on the map and in + # the Export tab, so the detail panel need not dump index lists. + counts = (f"α={len(entry['alpha'])} β={len(entry['beta'])} " + f"Anc={len(entry['ancillas'])}") lbl_lucj_detail.value = ( f"
" - f"{header}
" - f"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in entry['beta'])}
" - f"ancillas: {anc}
" + f"{header}
{counts}
" ) else: sc = f"{entry['score']:.4f}" if entry['score'] is not None else "N/A" + counts = f"α={len(entry['alpha'])} β={len(entry['beta'])}" lbl_lucj_detail.value = ( f"
" - f"#{entry['rank']} (err={sc})
" - f"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in entry['beta'])}
" + f"#{entry['rank']} (err={sc})
{counts}" ) # The LQS shown here is the circuit-level score — the same number # the Estimated Layout-Quality box reports. '(template)' flags the @@ -324,6 +356,18 @@ def _selected_date_anchor(): ts = getattr(state, 'point_timestamp', None) return ts[:10] if isinstance(ts, str) and len(ts) >= 10 else None + def _local_scored_vintage(): + """Provenance stamp for the LOCAL Auto sweep, mirroring the scan + detail's 'live · HH:MM'. A selected PAST date → 'scored on '; + otherwise the live fetch moment → 'scored on live · HH:MM'. Makes the + two-moments-two-numbers reality visible so a scan-vs-local mismatch + reads as calibration drift, not a bug. esc()'d value.""" + anchor = _selected_date_anchor() + if anchor: + return f"scored on {esc(anchor)}" + from datetime import datetime as _dt + return f"scored on live · {_dt.now().strftime('%H:%M')}" + def _local_scoring_props(): """Pre-rank on the SAME epoch as the C1 circuit-score — the selected date's arrays — so product_score and lqs_circuit never mix @@ -518,11 +562,15 @@ def _generate_sweep(norb): cap = _k_cap_phrase(norb, res.get('k_max_effective')) cap_txt = f" · {esc(cap)}" if cap else "" mode_txt = f" · {esc(_sweep_mode_label(res))}" + # Provenance stamp — mirrors the scan detail's 'live · HH:MM' so the + # user can SEE this number and a scan row's number were taken at + # DIFFERENT moments (calibration drift), not that one is wrong. + vin_txt = f" · {_local_scored_vintage()}" lbl_lucj_status.value = ( f"
✅ {_format_sweep_status(res)}{mode_txt}" - f"{cap_txt}
") + f"{cap_txt}{vin_txt}") else: lbl_lucj_status.value = ( f"
= 0) → legacy single-count search, - # unchanged. 'Auto' (-1) → stratified sweep (new default). - if requested_ancillas is not None and requested_ancillas >= 0: - _generate_legacy(norb, requested_ancillas) - else: - _generate_sweep(norb) + # Capture WARNING+ off 'qpu_mapper' for the sweep so bridge/VF2 + # notices land in the loud notices bar, not under the cell. + with _capture_qpu_notices( + lambda: state.active_backend_name or 'local sweep') as handler: + # Exact count picked (>= 0) → legacy single-count search, + # unchanged. 'Auto' (-1) → stratified sweep (new default). + if requested_ancillas is not None and requested_ancillas >= 0: + _generate_legacy(norb, requested_ancillas) + else: + _generate_sweep(norb) + lbl_lucj_notices.value = _notices_html(handler.records) except Exception as e: lbl_lucj_status.value = ( f"
" - f"{esc(str(t['name']))} ✓") - else: - rows.append(f"{esc(str(t['name']))} " - f"— {esc(str(t['reason']))}") + # One compact line: eligible names joined by ' · ' (+ count), then the + # skipped ones after an em-dash with a SHORT reason. The full per- + # backend reasons ride in the title tooltip. + elig = [t for t in targets if t['eligible']] + skip = [t for t in targets if not t['eligible']] + skip_txt = ', '.join( + f"{esc(str(t['name']))} ({esc(_short_reason(t.get('reason')))})" + for t in skip) + if elig: + names = ' · '.join(esc(str(t['name'])) for t in elig) + line = f"Targets: {names} ({len(elig)})" + if skip: + line += f" — skipped: {skip_txt}" + else: + line = "Targets: none" + if skip: + line += f" — {skip_txt}" + tip = esc(' | '.join( + (f"{t['name']}: eligible" if t['eligible'] + else f"{t['name']}: {t.get('reason')}") + for t in targets)) scan_results_box.children = [HTML( - "
Targets:
" - + "
".join(rows) + "
")] + f"
" + f"{line}
")] def _stage_handoff(backend_name, candidate): hook = inter_qpu_handoff[0] if inter_qpu_handoff else None @@ -908,165 +990,195 @@ def _vintage_cell(vintage): return "—" return f"{esc(str(vintage))}" + def _best_scan_entry(sweep): + """The single-scan candidate to hand off for a QPU: the entry with the + highest displayed metric (lqs_circuit, else product_score).""" + best, best_v = None, None + for entries in sweep.get('strata', {}).values(): + for e in entries: + v = e.get('lqs_circuit') + if v is None: + v = e['product_score'] + if best is None or v > best_v: + best, best_v = e, v + return best + + def _scan_best_lqs(r): + """The single-scan display metric quoted EVERYWHERE for a backend: + the MAX circuit LQS (lqs_circuit) across ALL its strata, ignoring None + (annotation failed). Falls back to the product heuristic — flagged + '(template)' — only when NOTHING was circuit-scored. Returns + (value, is_template) so the comparison-table cell, the selector label + and the detail line all quote the SAME number (previously the label + quoted best_lqs = max product_score, diverging from the lqs_circuit + table/detail).""" + sweep = r.get('sweep') or {} + lqs_vals = [e['lqs_circuit'] + for entries in sweep.get('strata', {}).values() + for e in entries if e.get('lqs_circuit') is not None] + if lqs_vals: + return max(lqs_vals), False + return (r.get('best_lqs') or 0.0), True + + def _scan_best_lqs_str(r): + """`_scan_best_lqs` formatted as the display percent string.""" + val, is_tmpl = _scan_best_lqs(r) + return f"{val * 100.0:.1f}%{' (template)' if is_tmpl else ''}" + + def _scan_selector(rows, *, label_fn, detail_fn, open_ok_fn, payload_fn, + disabled_tip): + """One Dropdown over scan rows (already ranked) + one detail line + one + '🔗 open on QPU 2' button. Selecting a row updates the detail; the open + button is disabled (with a tooltip) for rows that cannot be opened + (errors, or a batch that does not fully fit).""" + opts = [(label_fn(r), i) for i, r in enumerate(rows)] + if not opts: + return [] + dd = Dropdown(options=opts, value=0, description='QPU:', layout=W, + style={'description_width': '40px'}) + det = HTML("") + btn = Button(description='🔗 open on QPU 2', button_style='', + layout=Layout(width='180px')) + + def _sync(idx): + r = rows[idx] + det.value = detail_fn(r) + ok = open_ok_fn(r) + btn.disabled = not ok + btn.tooltip = '' if ok else disabled_tip + + dd.observe(lambda ch: ch['new'] is not None and _sync(ch['new']), + names='value') + + def _open(_b): + if dd.value is None: + return + r = rows[dd.value] + if not open_ok_fn(r): + return + payload = payload_fn(r) + if payload is not None: + _stage_handoff(r['name'], payload) # single candidate OR list + + btn.on_click(_open) + _sync(0) + return [dd, det, HBox([btn], layout=Layout(align_items='center'))] + + def _scan_detail_line2(r): + """Second detail line — the per-backend data the removed comparison + table used to carry: stability badge · k-cap phrase · calibration + vintage. Segments that don't apply are omitted; '' when none apply. + All dynamic values are esc()'d inside the reused helpers / here.""" + segs = [] + badge = _stability_badge(r) # already-styled, esc'd HTML + if badge: + segs.append(badge) + cap = _k_cap_phrase(_scan.get('norb', 0), + (r.get('sweep') or {}).get('k_max_effective')) + if cap: + segs.append(f"{esc(cap)}") + vintage = r.get('vintage') + if vintage: + segs.append(_vintage_cell(vintage)) # styled 'live ·
" + best = _best_scan_entry(sweep) + counts = (f"α={len(best['alpha'])} β={len(best['beta'])} " + f"Anc={len(best['ancillas'])}") if best else "" + # line 1 (as before): per-k bests + counts. + line1 = f"{esc(_format_best_per_k(strata))}
{counts}" + # line 2 (rescued from the table): stability · cap · calib. + line2 = _scan_detail_line2(r) + line2_html = f"
{line2}" if line2 else "" + return box + f"{line1}{line2_html}
" + + selector = _scan_selector( + results, + label_fn=_single_label, + detail_fn=_single_detail, + open_ok_fn=lambda r: not r.get('error') and r.get('best_lqs') is not None, + payload_fn=lambda r: _best_scan_entry(r.get('sweep') or {}), + disabled_tip='no candidates to open on QPU 2') + children.extend(selector) scan_results_box.children = children - def _append_notices(notices): - # Collapsible "⚠ notices (N)" under the results table: - # deduplicated messages (message → ×count), grouped by backend - # context. Hidden when empty. + def _notices_html(notices): + """The LOUD "⚠ notices" widget HTML — an amber warning bar with a count + badge (Y-pass styling), clearly clickable, expanding to the grouped, + deduplicated messages (message → ×count, grouped by backend context). + `notices` is a list of (context, message) tuples. Returns '' when empty + so callers can hide the widget. Shared by scan, local and multi.""" if not notices: - return + return "" from collections import OrderedDict groups = OrderedDict() - for ctx, msg in notices: - groups.setdefault(ctx, OrderedDict()) - groups[ctx][msg] = groups[ctx].get(msg, 0) + 1 + for bctx, msg in notices: + groups.setdefault(bctx, OrderedDict()) + groups[bctx][msg] = groups[bctx].get(msg, 0) + 1 parts = [] - for ctx, msgs in groups.items(): - parts.append(f"{esc(str(ctx))}") + for bctx, msgs in groups.items(): + parts.append(f"{esc(str(bctx))}") for msg, cnt in msgs.items(): suffix = f" ×{cnt}" if cnt > 1 else "" parts.append(f"  {esc(msg)}{esc(suffix)}") - html = ( - f"
" - f"⚠ notices ({len(notices)})" - f"
" + "
".join(parts) + "
" + # LOUD collapsed header: an amber warning bar with a count badge, + # clearly clickable. Expanded content keeps the small grey styling. + return ( + f"
" + f"⚠ notices " + f"{len(notices)}" + f"" + f"
" + + "
".join(parts) + "
" f"
") + + def _append_notices(notices): + # Collapsible loud notices under the scan results. Hidden when empty. + html = _notices_html(notices) + if not html: + return scan_results_box.children = list(scan_results_box.children) + [HTML(html)] def _on_scan_done(payload): @@ -1130,30 +1242,16 @@ def _on_scan_click(b): and chk_scan_stability.value) def _work(): - # Capture WARNING+ off 'qpu_mapper' for the scan's - # duration and stop them leaking under the cell (propagate=False). - # Attach in try, restore BOTH in finally (done + error paths). - logger = logging.getLogger('qpu_mapper') - orig_propagate = logger.propagate - handler = _ScanNoticeCapture(lambda: _scan.get('current') or 'general') - try: - logger.addHandler(handler) - logger.propagate = False - except Exception: - pass - try: + # Capture WARNING+ off 'qpu_mapper' for the scan's duration and stop + # them leaking under the cell — the same context every sweep uses. + with _capture_qpu_notices( + lambda: _scan.get('current') or 'general') as handler: # One scan path, one param source — forwards hybrid. result = _scan_backends(eligible, norb, get_backend, get_props, use_scan_filter) # Circuit-level LQS per backend — one scale everywhere. _annotate_scan_circuit_lqs(result, get_backend, get_props) return (result, list(handler.records)) - finally: - try: - logger.removeHandler(handler) - logger.propagate = orig_propagate - except Exception: - pass scan_spawn_bg(_work, on_done=_on_scan_done, on_error=_on_scan_error) btn_scan_qpus.on_click(_on_scan_click) @@ -1222,8 +1320,10 @@ def _on_lucj_multi(b): ) if not intra_qpu_mode.value and len(norb_list) > 1: - intra_qpu_mode.value = True - num_circuits.value = len(norb_list) + intra_qpu_mode.value = True # OFF→ON reveal: legitimate rebuild + # Same treatment as the sweep path: targeted count refresh, no + # visible Auto-view rebuild (results render in place below). + set_num_circuits(len(norb_list)) state.push_undo() for res in results: @@ -1268,8 +1368,7 @@ def _show_detail(entry, lbl): lbl.value = ( f"
" - f"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in entry['beta'])}
") + f"α={len(entry['alpha'])} β={len(entry['beta'])}") _show_detail(cands[0], lbl_circ) @@ -1335,7 +1434,8 @@ def _on_change(change): f"{ancilla_warning}
" f"Use dropdowns below to switch layouts per circuit.") - ctx.update_view() + # No ctx.update_view(): the count refresh is targeted (above) and + # the detail widgets / summary render into persistent widgets. except Exception as e: lbl_lucj_multi.value = ( @@ -1405,8 +1505,10 @@ def _apply_multi_sweep(result): if not circuits: return if not intra_qpu_mode.value and len(circuits) > 1: - intra_qpu_mode.value = True - num_circuits.value = len(circuits) + intra_qpu_mode.value = True # OFF→ON reveal: legitimate rebuild + # Count change from our own apply → targeted refresh, no view rebuild + # (the Multi results below render in place; no flicker). + set_num_circuits(len(circuits)) state.push_undo() for c in circuits: _apply_multi_candidate(c['circuit_idx'], c['chosen']) @@ -1500,13 +1602,17 @@ def _on_multi_override(i, choice): def _work(): from ..multi_sweep import replan_from - return replan_from(result, i, choice) + with _capture_qpu_notices(lambda: f'replan C{i + 1}') as handler: + new_result = replan_from(result, i, choice) + return (new_result, list(handler.records)) - def _done(new_result): + def _done(payload): + new_result, records = payload _multi_sweep['result'] = new_result _apply_multi_sweep(new_result) _multi_sweep['replan_in_flight'] = False _render_multi_sweep_output(new_result) # rebuilds dropdowns (enabled) + lbl_lucj_multi_notices.value = _notices_html(records) def _err(exc): _multi_sweep['replan_in_flight'] = False @@ -1540,6 +1646,7 @@ def _on_lucj_multi_sweep(b): btn_lucj_multi_sweep.disabled = True btn_lucj_multi_sweep.description = '⏳ Sweeping...' lbl_lucj_multi.value = "" + lbl_lucj_multi_notices.value = "" kwargs = _sweep_kwargs_from_ui() excl = _multi_stability_exclusions() scoring_props = _local_scoring_props() @@ -1547,25 +1654,30 @@ def _on_lucj_multi_sweep(b): def _reset_btn(): btn_lucj_multi_sweep.disabled = False - btn_lucj_multi_sweep.description = '🧺 Generate Multi-Circuit (sweep)' + btn_lucj_multi_sweep.description = '🧺 Generate Multi-Circuit' def _work(): from ..multi_sweep import sweep_multi_circuits - return sweep_multi_circuits( - norbs, state.active_backend, scoring_props, - min_bridges=min_bridges_list, top_n=kwargs['top_n'], - buffer_qubits=buffer, exclude_qubits=excl, - mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], - diversity_threshold=kwargs['diversity_threshold'], - circuit_score_fn=_circuit_score) - - def _done(result): + with _capture_qpu_notices(lambda: 'multi sweep') as handler: + result = sweep_multi_circuits( + norbs, state.active_backend, scoring_props, + min_bridges=min_bridges_list, top_n=kwargs['top_n'], + buffer_qubits=buffer, exclude_qubits=excl, + mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], + diversity_threshold=kwargs['diversity_threshold'], + circuit_score_fn=_circuit_score) + return (result, list(handler.records)) + + def _done(payload): + result, records = payload _reset_btn() _multi_sweep['result'] = result - _apply_multi_sweep(result) - _render_multi_sweep_output(result) - with contextlib.suppress(Exception): - ctx.update_view() + _apply_multi_sweep(result) # targeted count refresh (no rebuild) + _render_multi_sweep_output(result) # summary + dropdowns in place + lbl_lucj_multi_notices.value = _notices_html(records) + # No ctx.update_view() here: _apply_multi_sweep already did the + # targeted refresh + _refresh()/_get_export(), and the Multi results + # render into persistent widgets — a full rebuild would only flicker. def _err(exc): _reset_btn() @@ -1601,50 +1713,57 @@ def _batch_metric(res): return m, False return (res.get('total_product') or 0.0), True - def _batch_ks(res): - return ', '.join(f"k={len(c['chosen']['ancillas'])}" - for c in res.get('circuits', [])) + def _batch_line_html(res): + """Compact per-QPU line: 'C1: k=3 · 72.2% | batch: 72.2%'. A circuit + that could not fit is labeled inline ('Ci: does not fit'); '(template)' + marks a product-only metric.""" + parts = [] + for c in res.get('circuits', []): + ch = c['chosen'] + pct, is_tmpl = _entry_lqs_pct(ch) + tmpl = ' (template)' if is_tmpl else '' + parts.append(f"C{c['circuit_idx'] + 1}: k={len(ch['ancillas'])} " + f"· {pct}{tmpl}") + fa = res.get('failed_at') + if fa is not None: + parts.append(f"C{fa + 1}: does not fit") + m, is_tmpl = _batch_metric(res) + parts.append(f"batch: {m * 100.0:.1f}%{' (template)' if is_tmpl else ''}") + return ' | '.join(parts) def _render_batch_results(scan_result): - head = ("" - "" - "" - "" - "" - "") - rows, detail_widgets = [], [] - for r in scan_result['results']: + # ONE QPU selector over the scan_qpus-ranked batches: pick a backend, + # see its per-circuit detail, open the whole batch on QPU 2. A batch + # that does not fully fit is selectable but not openable. + def _label(r): name = esc(str(r['name'])) if r.get('error'): - rows.append( - f"") - continue + return f"{name} — ✗ error" + m, is_tmpl = _batch_metric(r.get('sweep') or {}) + return (f"{name} — batch {m * 100.0:.1f}%" + f"{' (template)' if is_tmpl else ''}") + + def _detail(r): + box = ("
") + if r.get('error'): + return box + f"✗ {esc(str(r['error']))}
" + return box + f"{esc(_batch_line_html(r.get('sweep') or {}))}" + + def _open_ok(r): res = r.get('sweep') or {} - m, is_tmpl = _batch_metric(res) - lqs = f"{m * 100.0:.1f}%{' (template)' if is_tmpl else ''}" - fa = res.get('failed_at') - fit = ('ok' if fa is None - else f"failed_at={fa}") - rows.append( - f"" - f"" - f"" - f"") - # Per-QPU expandable detail + a one-click handoff button. - if res.get('circuits'): - detail_widgets.append(HTML( - f"
" - f"{name} — {esc(_multi_summary_html(res))}
")) - btn = Button(description=f'📡 open {r["name"]} on QPU 2', - layout=W, button_style='') - chosen = [c['chosen'] for c in res['circuits']] - nm = r['name'] - btn.on_click(lambda _b, nm=nm, ch=chosen: _batch_handoff(nm, ch)) - detail_widgets.append(btn) - table = HTML(head + "".join(rows) + "
QPUbatch LQSper-circuit kfit
{name}✗ {esc(str(r['error']))}
{name}{esc(lqs)}{esc(_batch_ks(res))}{fit}
") - scan_batch_box.children = [table] + detail_widgets + return (not r.get('error') and bool(res.get('circuits')) + and res.get('failed_at') is None) + + def _payload(r): + res = r.get('sweep') or {} + return [c['chosen'] for c in res.get('circuits', [])] + + scan_batch_box.children = _scan_selector( + scan_result['results'], + label_fn=_label, detail_fn=_detail, open_ok_fn=_open_ok, + payload_fn=_payload, + disabled_tip='batch does not fully fit on this backend') def _batch_handoff(backend_name, chosen_list): hook = inter_qpu_handoff[0] if inter_qpu_handoff else None @@ -1800,8 +1919,7 @@ def _cb(change): label.value = ( f"
" - f"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in entry['beta'])}
") + f"α={len(entry['alpha'])} β={len(entry['beta'])}") if ci < len(_lucj_multi_norbs_list) - 1: _reoptimize_downstream(ci) return _cb diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py new file mode 100644 index 0000000..4962d5e --- /dev/null +++ b/tests/test_auto_subpanels.py @@ -0,0 +1,137 @@ +"""Auto-tab Single/Multi subpanels, candidate-detail declutter, and the +export-is-auto-current pin. +""" +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Button + + +def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _entry(anc, rank): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(anc), 'bridge_slots': (0,), 'product_score': 0.4, + 'additive_score': 0.5, 'lqs_circuit': 0.4, 'rank_in_stratum': rank, + 'source': 'derived'} + + +def _canned(): + e = [_entry([4], 1), _entry([5], 2)] + return {'strata': {1: e}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 5, + 'n_candidates_scored': 5, 'excluded_qubits': [], + 'per_stratum': {1: {'n_direct': 0, 'n_derived': 2, + 'truncated': False, 'shuffled': False}}, + 'mapping_cap': 2000} + + +def _build(monkeypatch): + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b, state + + +# ── t1: subpanels follow the Multi-Programming enable ─────────────────────── + +def test_subpanels_follow_multi_programming(monkeypatch): + b, state = _build(monkeypatch) + + b.intra_qpu_mode.value = False + b._build_auto_lucj_view() + assert len(b._auto_lucj_tabs.children) == 1 # Single only + assert b._auto_lucj_tabs.get_title(0) == '🔬 Single Circuit' + # Multi widgets are not in the single panel. + assert b.btn_scan_batch not in b._auto_single_panel.children + + b.intra_qpu_mode.value = True + b._build_auto_lucj_view() + assert len(b._auto_lucj_tabs.children) == 2 # Single + Multi + assert b._auto_lucj_tabs.get_title(1) == '🔗 Multi-Circuit' + assert b.btn_scan_batch in b._auto_multi_panel.children + assert b.btn_lucj_multi_sweep in b._auto_multi_panel.children + + +# ── R3 t1: exactly TWO buttons in the Multi subpanel — no legacy node ──────── + +def test_multi_subpanel_has_two_buttons_no_legacy(monkeypatch): + b, state = _build(monkeypatch) + b.intra_qpu_mode.value = True + b._build_auto_lucj_view() + + buttons = [w for w in b._auto_multi_panel.children if isinstance(w, Button)] + assert len(buttons) == 2 # generate + batch + assert set(buttons) == {b.btn_lucj_multi_sweep, b.btn_scan_batch} + assert b.btn_lucj_multi not in b._auto_multi_panel.children # legacy gone + # The sweep button is the single generate action — no "(sweep)" qualifier. + assert b.btn_lucj_multi_sweep.description == '🧺 Generate Multi-Circuit' + # The ancilla field speaks one (sweep) language. + assert b.lucj_multi_ancillas.tooltip == 'min ancillas per circuit (blank = auto)' + assert 'Legacy' not in (b.lucj_multi_ancillas.tooltip or '') + + +# ── R3 t2: the legacy handler + engine stay defined (source pin) ──────────── + +def test_legacy_handler_and_engine_still_defined(): + panel = Path('qpu_mapper/ui/lucj_panel.py').read_text() + assert 'def _on_lucj_multi(' in panel # handler retained + assert 'get_multi_circuit_layouts' in panel # engine path retained + # And the widget object is still wired (clickable) for the pinned tests. + from qpu_mapper.ui.builder import MapperUIBuilder + assert hasattr(MapperUIBuilder, '_build_auto_lucj_view') + + +# ── t3: candidate detail shows counts, never qubit index lists ────────────── + +def test_detail_panel_counts_not_qubit_lists(monkeypatch): + b, state = _build(monkeypatch) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned()) + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() + b.dd_lucj_layout.value = 1 # change → fire select + + v = b.lbl_lucj_detail.value + assert 'α=2' in v and 'β=2' in v and 'Anc=1' in v # compact counts + assert 'α: ' not in v and 'β: ' not in v # no index dumps + assert '0, 1' not in v and 'ancillas:' not in v # no id lists + + +# ── t5: an applied batch (C1..Cn) is auto-reflected in the export ────────── + +def test_export_reads_applied_batch(): + from qpu_mapper.export.codegen import get_qiskit_layout_code + state = SimpleNamespace(layouts_data={ + 0: {'alpha': ['0', '1'], 'beta': ['2', '3'], 'other': [], 'name': 'C1'}, + 1: {'alpha': ['4', '5'], 'beta': ['6', '7'], 'other': [], 'name': 'C2'}, + }) + # n_circ = 2 (what the export computes when intra-QPU is on with 2 circuits). + code = get_qiskit_layout_code(state, 'lucj', 2) + assert 'C1' in code and 'C2' in code # both circuits + assert '0' in code and '7' in code # each circuit's qubits + # Circuit 1's physical qubits appear in its layout dict. + assert '{0: 0, 1: 1, 2: 2, 3: 3}' in code + assert '{0: 4, 1: 5, 2: 6, 3: 7}' in code diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index b68ba2e..99c731b 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -202,11 +202,25 @@ def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): b.lucj_multi_norbs.value = '8, 8' b.btn_scan_batch.click() - table = b.scan_batch_box.children[0].value - assert table.index('ibm_hi') < table.index('ibm_lo') # sorted - assert '61.0%' in table and '40.0%' in table - assert 'failed_at=1' in table # labeled, not errored - assert '✗' not in table + # ONE selector dropdown (no table), labels sorted by batch LQS + one button. + from ipywidgets import Dropdown, HTML, HBox + kids = list(b.scan_batch_box.children) + dd = next(c for c in kids if isinstance(c, Dropdown)) + det = next(c for c in kids if isinstance(c, HTML)) + btn = next(c for w in kids for c in + (w.children if isinstance(w, HBox) else [w]) if isinstance(c, Button)) + + labels = [o[0] for o in dd.options] + assert not any('3' in html # loud header + count badge assert 'stale cache housekeeping ×2' in html # deduped with count assert 'other notice' in html # the singleton (no ×) assert 'other notice ×' not in html @@ -157,4 +165,4 @@ def test_no_notices_section_when_empty(monkeypatch): _patch_targets(monkeypatch) _patch_engine(monkeypatch, lambda *a, **k: _sweep()) b.btn_scan_qpus.click() - assert '⚠ notices' not in _all_html(b.scan_results_box) + assert 'notices' not in _all_html(b.scan_results_box) diff --git a/tests/test_scan_targets_line.py b/tests/test_scan_targets_line.py new file mode 100644 index 0000000..1d031a2 --- /dev/null +++ b/tests/test_scan_targets_line.py @@ -0,0 +1,123 @@ +"""The one-line scan-targets summary (eligible names + short skip reasons).""" +from types import SimpleNamespace + +import numpy as np + + +def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _noop_spawn(fn, on_done=None, on_error=None): + # Do NOT run the scan work — leave the rendered Targets line in place. + return None + + +def _build(monkeypatch, active='ibm_boston'): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _noop_spawn) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) + monkeypatch.setattr("qpu_mapper.qpu_scan._detect_family", lambda b: 'Heron') + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = active + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b, state + + +def _targets_html(b): + return b.scan_results_box.children[0].value + + +# ── t1: mixed fixture → exact compact line ────────────────────────────────── + +def test_targets_line_compact_mixed(monkeypatch): + b, state = _build(monkeypatch, active='ibm_boston') + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_pittsburgh', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_fez', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_marrakesh', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_kingston', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_boston', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_miami', 'family': 'Nighthawk', 'eligible': False, + 'reason': 'different family (Nighthawk)'}]) + b.btn_scan_qpus.click() + + html = _targets_html(b) + # ibm_boston is the active backend → marked 'current' by the handler. + assert ('Targets: ibm_pittsburgh · ibm_fez · ibm_marrakesh · ' + 'ibm_kingston (4) — skipped: ibm_boston (current), ' + 'ibm_miami (Nighthawk)') in html + # Full reasons in the tooltip. + assert "title='" in html + assert 'ibm_miami: different family (Nighthawk)' in html + assert 'ibm_boston: current backend' in html + + +def test_short_reasons_mapped(monkeypatch): + b, state = _build(monkeypatch, active='none') + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_ok', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_small', 'family': 'Heron', 'eligible': False, + 'reason': 'needs >= 17 qubits, has 12'}, + {'name': 'ibm_unk', 'family': None, 'eligible': False, + 'reason': 'family unknown'}, + {'name': 'ibm_other', 'family': 'Flamingo', 'eligible': False, + 'reason': 'different family (Flamingo)'}]) + b.btn_scan_qpus.click() + + html = _targets_html(b) + assert 'ibm_ok (1)' in html + assert 'ibm_small (too small)' in html + assert 'ibm_unk (unknown family)' in html + assert 'ibm_other (Flamingo)' in html + + +# ── t2: no eligible targets → 'none' form ────────────────────────────────── + +def test_targets_line_none(monkeypatch): + b, state = _build(monkeypatch, active='none') + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Nighthawk', 'eligible': False, + 'reason': 'different family (Nighthawk)'}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': False, + 'reason': 'needs >= 17 qubits, has 12'}]) + b.btn_scan_qpus.click() + + html = _targets_html(b) + assert 'Targets: none — ibm_a (Nighthawk), ibm_b (too small)' in html + assert 'skipped:' not in html # 'none' form omits the word + + +# ── t3: esc() on a hostile backend name ───────────────────────────────────── + +def test_targets_line_escapes_name(monkeypatch): + b, state = _build(monkeypatch, active='none') + from qpu_mapper import qpu_scan as qs + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': '', 'family': 'Heron', 'eligible': True, + 'reason': None}]) + b.btn_scan_qpus.click() + + html = _targets_html(b) + assert '<script>' in html and '' not in html diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index b9ddf30..faf7f2e 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -127,6 +127,38 @@ def _dropdowns(children): return [c for c in children if isinstance(c, Dropdown)] +def _walk(node): + yield node + for ch in getattr(node, 'children', []): + yield from _walk(ch) + + +def _selector(b): + from ipywidgets import Dropdown + return next(w for w in b.scan_results_box.children if isinstance(w, Dropdown)) + + +def _labels(b): + """The scan selector's dropdown option labels (name — best%).""" + return [lbl for lbl, _ in _selector(b).options] + + +def _detail(b, i): + """Select row i in the selector and return its rendered detail HTML.""" + from ipywidgets import HTML + dd = _selector(b) + dd.value = i + ch = list(b.scan_results_box.children) + di = ch.index(dd) + return next(w.value for w in ch[di + 1:] if isinstance(w, HTML)) + + +def _detail_by_name(b, name): + dd = _selector(b) + idx = next(i for lbl, i in dd.options if name in lbl) + return _detail(b, idx) + + # ── happy path — table sorted, dropdowns, button re-enabled ───────────────── def test_scan_happy_path(monkeypatch): @@ -135,10 +167,11 @@ def test_scan_happy_path(monkeypatch): b.btn_scan_qpus.click() children = b.scan_results_box.children - table_html = children[0].value - assert table_html.index('ibm_b') < table_html.index('ibm_a') # sorted - assert '60.0%' in table_html and '40.0%' in table_html - assert len(_dropdowns(children)) == 2 # per success + # The per-QPU blocks are ONE selector dropdown, ranked (best first). + assert len(_dropdowns(children)) == 1 + labels = _labels(b) + assert labels[0].startswith('ibm_b') and 'ibm_a' in labels[1] # sorted + assert '60.0%' in labels[0] and '40.0%' in labels[1] # best% in label assert b.btn_scan_qpus.disabled is False @@ -167,10 +200,12 @@ def test_scan_failed_row_escaped(monkeypatch): 'ibm_c': RuntimeError('boom ')}) b.btn_scan_qpus.click() - table_html = b.scan_results_box.children[0].value - assert 'color:#999' in table_html - assert 'boom <x>' in table_html - assert '' not in table_html + # The errored backend is a selectable row; its label + detail name the + # esc()'d error (no raw angle brackets leak into HTML). + assert any('ibm_c' in lbl and '✗ error' in lbl for lbl in _labels(b)) + detail = _detail_by_name(b, 'ibm_c') + assert 'boom <x>' in detail + assert '' not in detail # ── handoff — selecting a remote candidate stages it ──────────────────────── @@ -182,13 +217,19 @@ def test_scan_handoff_on_select(monkeypatch): b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) b.btn_scan_qpus.click() - dds = _dropdowns(b.scan_results_box.children) - dds[0].value = 0 # ibm_b top candidate + # Select the top QPU in the selector, then click its "open on QPU 2" button. + from ipywidgets import Button, HBox + sel = _dropdowns(b.scan_results_box.children)[0] + sel.value = 0 # ibm_b (top-ranked) + btns = [c for w in b.scan_results_box.children + for c in (w.children if isinstance(w, HBox) else [w]) + if isinstance(c, Button)] + btns[0].click() assert len(staged) == 1 name, cand = staged[0] assert name == 'ibm_b' - assert cand['ancillas'] == [4, 5] # flat[0] = k=2 entry + assert cand['ancillas'] == [4, 5] # the QPU's best (k=2) candidate # ── sweep mode greys the score checkbox ──────────────────────────────── @@ -220,7 +261,7 @@ def test_scan_circuit_lqs_annotated(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) _patch_scan(monkeypatch) # stub props score → circuit LQS b.btn_scan_qpus.click() - assert '(template)' not in b.scan_results_box.children[0].value + assert not any('(template)' in lbl for lbl in _labels(b)) def test_scan_template_suffix_only_on_failure(monkeypatch): @@ -229,7 +270,7 @@ def test_scan_template_suffix_only_on_failure(monkeypatch): _patch_scan(monkeypatch, props={'ibm_b': _StubProps(None), 'ibm_a': _StubProps(None), 'ibm_c': _StubProps(None)}) b.btn_scan_qpus.click() - assert '(template)' in b.scan_results_box.children[0].value + assert any('(template)' in lbl for lbl in _labels(b)) # ── vintage renders 'live · ' (no stale badge) ─────────── @@ -240,9 +281,9 @@ def test_scan_live_vintage(monkeypatch): 'ibm_a': _StubProps(0.4, 'live · 09:30'), 'ibm_c': _StubProps(0.0, 'live · 09:30')}) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value - assert 'live · 09:30' in table - assert 'stale calib' not in table # stale-badge path removed + detail = _detail(b, 0) # calib vintage on detail line 2 + assert 'live · 09:30' in detail + assert 'stale calib' not in detail # stale-badge path removed # ── a fetch failure → honest error row, others complete ────────────── @@ -264,9 +305,8 @@ def gp(backend): monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", get_props) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value - assert 'network down' in table # ibm_a → honest error row - assert 'live · 09:30' in table # ibm_b completed + assert 'network down' in _detail_by_name(b, 'ibm_a') # honest error row + assert 'live · 09:30' in _detail_by_name(b, 'ibm_b') # ibm_b completed # ── stability filter still reads the cache for HISTORY ──────────────── @@ -351,10 +391,10 @@ def test_active_backend_skipped_with_reference(monkeypatch): b.btn_scan_qpus.click() assert 'stub' not in swept # active never swept - table = b.scan_results_box.children[0].value - assert '📍 stub' in table - assert 'current backend' in table - assert 'run Auto above' in table # no local sweep yet → hint + # (The removed comparison table used to render a greyed '📍 ' + # reference row; that row is gone with the table. The skip behaviour — the + # active backend is never re-swept — is what still matters and is pinned.) + assert 'stub' not in [lbl.split(' —')[0] for lbl in _labels(b)] # not a row # ── scan honors the hybrid checkbox ───────────────────────────────────── @@ -379,8 +419,8 @@ def test_scan_honors_hybrid_checkbox(monkeypatch): def _scan_html(b): from ipywidgets import HTML - return " ".join(c.value for c in b.scan_results_box.children - if isinstance(c, HTML)) + return " ".join(w.value for w in _walk(b.scan_results_box) + if isinstance(w, HTML)) def _patch_one_target(monkeypatch, sweep, props_obj): @@ -402,9 +442,8 @@ def score_layout(self, q): _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _RaiseProps()) b.btn_scan_qpus.click() - html = _scan_html(b) - assert '(template)' in html # None → template, not 0.0% - assert 'circuit score unavailable' in html # failure named in notices + assert any('(template)' in lbl for lbl in _labels(b)) # None → template + assert 'circuit score unavailable' in _scan_html(b) # named in notices def test_genuine_zero_renders_as_zero(monkeypatch): @@ -417,9 +456,9 @@ def score_layout(self, q): _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _ZeroProps()) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value - assert '0.0%' in table # genuine zero shown as 0.0% - assert '(template)' not in table # 0.0 is a real score + # Genuine zero shows as 0.0% in the per-k detail; not flagged (template). + assert '0.0%' in _detail(b, 0) + assert not any('(template)' in lbl for lbl in _labels(b)) def test_summary_best_is_max_over_non_none(monkeypatch): @@ -433,6 +472,6 @@ def score_layout(self, q): _patch_one_target(monkeypatch, _sweep(0.60, 0.50), _VaryProps()) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value - assert '62.0%' in table # summary = max, NOT the - assert not table.split('ibm_a')[1].startswith('0.0') # k_max 0.0 wall + label = _labels(b)[0] + assert '62.0%' in label # summary/label = max, NOT + assert '— 0.0%' not in label # the k_max 0.0 wall diff --git a/tests/test_scan_ui_pass.py b/tests/test_scan_ui_pass.py new file mode 100644 index 0000000..24cb211 --- /dev/null +++ b/tests/test_scan_ui_pass.py @@ -0,0 +1,241 @@ +"""SCAN UI PASS regressions: label==table metric (Y1), table behind a toggle +(Y2), loud notices header (Y3). + +The label used to quote r['best_lqs'] (= max product_score) while the table and +detail quoted max lqs_circuit — so the SAME backend could read 73.0% in the +selector and 65.3% in the table. These tests pin all three to one number and +pin the table-behind-a-toggle + loud-notices UI. +""" +import re +from types import SimpleNamespace + +import numpy as np +from ipywidgets import HTML, Dropdown + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover - defensive + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _entry(prod, k): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(range(4, 4 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 1.0, + 'rank_in_stratum': 1, 'source': 'vf2'} + + +def _sweep(prod_hi, prod_lo): + return {'strata': {2: [_entry(prod_lo, 2)], 1: [_entry(prod_hi, 1)]}, + 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 10, 'n_candidates_scored': 20, + 'per_stratum': {2: {'n_direct': 1, 'n_derived': 0, 'truncated': False}, + 1: {'n_direct': 1, 'n_derived': 1, 'truncated': False}}} + + +class _FixedProps: + """score_layout returns a FIXED fidelity (the circuit LQS), independent of + the entry's product_score — so we can drive product_score != lqs_circuit and + prove the label follows lqs_circuit, not the product heuristic.""" + def __init__(self, fid, vintage='live'): + self._fid = fid + self.vintage = vintage + + def score_layout(self, qubits): + if self._fid is None: + raise RuntimeError("no circuit score") + return {'fidelity': self._fid} + + +def _build(monkeypatch, spawn=_sync_spawn, marshal=lambda cb: cb()): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr(au, 'marshal_to_main', marshal) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" # NOT a target → no ref row + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = ["ibm_a"] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b + + +def _patch_one(monkeypatch, sweep, props_obj, name='ibm_a'): + monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': name, 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: sweep) + monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: props_obj)) + + +def _walk(node): + yield node + for ch in getattr(node, 'children', []): + yield from _walk(ch) + + +def _has_table(b): + """True if a comparison-table node (its 'best LQS' header) is anywhere in + the scan results tree — it must NOT be, post-removal.""" + return any(isinstance(w, HTML) and 'best LQS' in w.value + for w in _walk(b.scan_results_box)) + + +def _selector_dd(b): + return next(w for w in b.scan_results_box.children if isinstance(w, Dropdown)) + + +def _detail(b, i): + """Select row i and return its rendered detail HTML.""" + dd = _selector_dd(b) + dd.value = i + ch = list(b.scan_results_box.children) + di = ch.index(dd) + return next(w.value for w in ch[di + 1:] if isinstance(w, HTML)) + + +def _pct(s): + m = re.search(r'(\d+\.\d)%', s) + return m.group(1) if m else None + + +# ── t1 (Y1): selector label quotes max lqs_circuit (== the detail metric) ─── + +def test_label_quotes_lqs_circuit(monkeypatch): + b = _build(monkeypatch) + # product_score peaks at 0.73 (would drive a product-based label to 73.0%), + # but the circuit LQS is 0.653 → label + detail read 65.3%. + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653)) + b.btn_scan_qpus.click() + + label = _selector_dd(b).options[0][0] # top row's label + assert _pct(label) == '65.3' # follows lqs_circuit, NOT 73.0 + assert '73.0%' not in label + assert '65.3%' in _detail(b, 0) # detail per-k agrees + + +def test_label_template_fallback(monkeypatch): + b = _build(monkeypatch) + # No circuit score (score_layout raises) → label falls back to product best + # with the '(template)' flag. + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(None)) + b.btn_scan_qpus.click() + + label = _selector_dd(b).options[0][0] + assert '(template)' in label + assert _pct(label) == '73.0' + + +# ── t2 (R2): detail line 2 carries cap + calib; omits absent segments ─────── + +def test_detail_line2_cap_and_calib(monkeypatch): + b = _build(monkeypatch) + b.lucj_norb_slider.value = 20 # request k=5; sweep caps at 2 + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653, 'live · 21:11')) + b.btn_scan_qpus.click() + + d = _detail(b, 0) + assert 'k capped at 2 (requested 5)' in d # cap segment rescued + assert 'live · 21:11' in d # calib segment rescued + assert '🛡' not in d # no stability filter → omitted + + +def test_detail_line2_omits_absent_cap(monkeypatch): + b = _build(monkeypatch) + b.lucj_norb_slider.value = 8 # request k=2 == k_max → no cap + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653, 'live · 09:00')) + b.btn_scan_qpus.click() + + d = _detail(b, 0) + assert 'capped' not in d # not capped → omitted + assert 'live · 09:00' in d # calib still present + + +# ── t1 (R1): NO comparison table + NO toggle checkbox in the results tree ─── + +def test_no_table_no_checkbox(monkeypatch): + b = _build(monkeypatch) + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653)) + b.btn_scan_qpus.click() + + from ipywidgets import Checkbox + assert not _has_table(b) # table node gone + # No "Show comparison table" checkbox anywhere in the results tree… + assert not any(isinstance(w, Checkbox) + and 'comparison table' in (w.description or '') + for w in _walk(b.scan_results_box)) + # …and the widget/attribute is removed from the builder entirely. + assert not hasattr(b, 'chk_show_scan_table') + # The selector is the only results UI. + assert any(isinstance(w, Dropdown) for w in b.scan_results_box.children) + + +# ── t3 (R3): selector + open still drives handoff (no table involved) ─────── + +def test_selector_open_drives_handoff_no_table(monkeypatch): + b = _build(monkeypatch) + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653)) + staged = [] + b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) + b.btn_scan_qpus.click() + + assert not _has_table(b) + from ipywidgets import Button, HBox + _selector_dd(b).value = 0 + btns = [c for w in b.scan_results_box.children + for c in (w.children if isinstance(w, HBox) else [w]) + if isinstance(c, Button)] + btns[0].click() + + assert len(staged) == 1 + name, cand = staged[0] + assert name == 'ibm_a' + # circuit LQS ties across strata → first-scored (k=2) entry wins. + assert cand['ancillas'] == [4, 5] + + +# ── t4 (Y3): notices collapsed header carries the LOUD style + count ──────── + +def test_notices_header_loud_with_count(monkeypatch): + b = _build(monkeypatch) + # score_layout raises → per-candidate 'circuit score unavailable' notices. + _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(None)) + b.btn_scan_qpus.click() + + notices = next(w.value for w in _walk(b.scan_results_box) + if isinstance(w, HTML) and '\s*\d+\s*', notices) # a numeric count in the badge diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index b43c4f9..887184f 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -45,6 +45,18 @@ def _canned_res(stability): 'stability': stability} +def _detail_by_name(b, name): + """Select the scan-selector row whose label contains `name` and return its + rendered detail HTML (the comparison table is gone; per-backend stability / + cap / calib now live on the detail's second line).""" + from ipywidgets import Dropdown, HTML + dd = next(w for w in b.scan_results_box.children if isinstance(w, Dropdown)) + dd.value = next(i for lbl, i in dd.options if name in lbl) + ch = list(b.scan_results_box.children) + di = ch.index(dd) + return next(w.value for w in ch[di + 1:] if isinstance(w, HTML)) + + def _build(monkeypatch, *, history=False, spawn=_sync_spawn, marshal=lambda cb: cb()): import qpu_mapper.async_util as au @@ -175,9 +187,8 @@ def test_scan_stability_badges(monkeypatch): vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value - assert '🛡 −2 qubits' in table # cached → filtered - assert 'n/a (no cached history)' in table # fresh → n/a + assert '🛡 −2 qubits' in _detail_by_name(b, 'ibm_a') # cached → filtered + assert 'n/a (no cached history)' in _detail_by_name(b, 'ibm_b') # fresh → n/a # ── filter OFF keeps the plain sweep path ─────────────────────────────── @@ -264,9 +275,8 @@ def _load(name, ts): vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) b.btn_scan_qpus.click() - table = b.scan_results_box.children[0].value # (a) isolation: ibm_c's raise became an error row, loop not killed. - assert 'cache read exploded' in table + assert 'cache read exploded' in _detail_by_name(b, 'ibm_c') # (b) both badge paths: cached → filtered, fresh → n/a. - assert '🛡 −2 qubits' in table # ibm_a cached → filtered - assert 'n/a (no cached history)' in table # ibm_b (after ibm_c) fresh + assert '🛡 −2 qubits' in _detail_by_name(b, 'ibm_a') # cached → filtered + assert 'n/a (no cached history)' in _detail_by_name(b, 'ibm_b') # fresh → n/a diff --git a/tests/test_subpanel_persistence.py b/tests/test_subpanel_persistence.py new file mode 100644 index 0000000..749a4f3 --- /dev/null +++ b/tests/test_subpanel_persistence.py @@ -0,0 +1,245 @@ +"""SUBPANEL SELECTION MUST SURVIVE REBUILDS. + +Every structural refresh rebuilds a nav view from scratch, minting a fresh Tab +whose selected_index defaults to 0. Firing Generate Multi-Circuit from the Multi +subpanel used to bounce the user back to Single mid-operation. These tests pin +that the Auto / I/O / Error subtabs keep their selection across rebuilds. +""" +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Dropdown + + +def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _mentry(anc): + return {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': list(anc), + 'bridge_slots': tuple(range(0, 4 * len(anc), 4)), + 'product_score': 0.60, 'additive_score': 0.5, 'lqs_circuit': 0.60, + 'rank_in_stratum': 1, 'source': 'vf2'} + + +def _mcircuit(i, anc): + ch = _mentry(anc) + return {'circuit_idx': i, 'norb': 8, 'chosen': ch, 'strata': {1: [ch]}, + 'k_max_effective': 1, 'min_bridges': 1, 'vf2_truncated': False, + 'per_stratum': {1: {'n_direct': 0, 'n_derived': 1, + 'truncated': False, 'shuffled': False}}, + 'mapping_cap': 2000, 'excluded_qubits': []} + + +def _mresult(): + return {'circuits': [_mcircuit(0, [4]), _mcircuit(1, [6])], + 'total_product': 0.36, 'total_lqs_circuit': 0.36, + 'placed_qubits': [], 'buffer_qubits_used': [], 'failed_at': None, + '_context': {'stub': True}} + + +def _build(monkeypatch): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() # no .coords → Auto allowed + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b, state + + +# ── t1: the user's exact sequence — Generate Multi stays on Multi ─────────── + +def test_multi_generate_keeps_multi_subpanel(monkeypatch): + b, state = _build(monkeypatch) + import qpu_mapper.multi_sweep as ms + monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) + + b.intra_qpu_mode.value = True # reveal the Multi subpanel + b.nav_bar.value = 'auto_lucj' # on the Auto tab + assert len(b._auto_lucj_tabs.children) == 2 + b._auto_lucj_tabs.selected_index = 1 # user picks Multi-Circuit + + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() # ← the action that bounced + + # Still on Multi (the fresh Tab from the rebuild carried the index over). + assert b._auto_lucj_tabs.selected_index == 1 + # Results rendered in place. + assert 'circuit(s) placed' in b.lbl_lucj_multi.value + assert state.layouts_data[0]['ancilla'] == ['4'] # batch applied + assert state.layouts_data[1]['ancilla'] == ['6'] + + +def test_num_circuits_change_keeps_multi_subpanel(monkeypatch): + # The num_circuits observer fires _update_view during the multi flow; a + # bare structural rebuild must also preserve the selection. + b, state = _build(monkeypatch) + b.intra_qpu_mode.value = True + b.nav_bar.value = 'auto_lucj' + b._auto_lucj_tabs.selected_index = 1 + + b.num_circuits.value = 3 # structural change → rebuild + assert b._auto_lucj_tabs.selected_index == 1 + + +# ── t2: fresh reveal defaults to Single; rebuilds while ON preserve ───────── + +def test_fresh_reveal_single_then_preserve(monkeypatch): + b, state = _build(monkeypatch) + + b.intra_qpu_mode.value = False + b._build_auto_lucj_view() + assert len(b._auto_lucj_tabs.children) == 1 + assert b._auto_lucj_tabs.selected_index == 0 + + b.intra_qpu_mode.value = True # fresh reveal of Multi + b._build_auto_lucj_view() + assert len(b._auto_lucj_tabs.children) == 2 + assert b._auto_lucj_tabs.selected_index == 0 # defaults to Single + + b._auto_lucj_tabs.selected_index = 1 # user picks Multi + b._build_auto_lucj_view() # subsequent rebuild + assert b._auto_lucj_tabs.selected_index == 1 # preserved + + # Turning it OFF clamps past-the-end index back to the only subpanel. + b.intra_qpu_mode.value = False + b._build_auto_lucj_view() + assert len(b._auto_lucj_tabs.children) == 1 + assert b._auto_lucj_tabs.selected_index == 0 + + +# ── t3: same-class pins for the I/O and Error tabs ───────────────────────── + +def test_io_subtab_survives_rebuild(monkeypatch): + b, state = _build(monkeypatch) + b.nav_bar.value = 'io' + assert len(b._io_tabs.children) == 2 + b._io_tabs.selected_index = 1 # Import subpanel + b._update_view() # a refresh while on I/O + assert b._io_tabs.selected_index == 1 # still Import, not Export + + +def test_error_subtab_survives_rebuild(monkeypatch): + b, state = _build(monkeypatch) + b.nav_bar.value = 'error_inspect' + assert len(b._err_tabs.children) == 2 + b._err_tabs.selected_index = 1 # Analysis subtab + b._update_view() # a refresh while on Error + assert b._err_tabs.selected_index == 1 # still Analysis + + +# ══ X2b — no visible rebuild on Multi Generate ═════════════════════════════ + +def _on_multi(b): + """Put the UI on the Auto tab with the Multi subpanel revealed + selected.""" + b.intra_qpu_mode.value = True + b.nav_bar.value = 'auto_lucj' + b._auto_lucj_tabs.selected_index = 1 + return b._auto_lucj_tabs + + +# ── W3 t1: the Tab widget instance is UNCHANGED after Generate (no rebuild) ── + +def test_multi_generate_no_rebuild(monkeypatch): + b, state = _build(monkeypatch) + import qpu_mapper.multi_sweep as ms + monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) + tab_before = _on_multi(b) + content_before = b.content_box.children[0] + + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + # Same widget instances — the visible panel was updated in place, not rebuilt. + assert b._auto_lucj_tabs is tab_before + assert b.content_box.children[0] is content_before + assert b._auto_lucj_tabs.selected_index == 1 # still on Multi + assert 'circuit(s) placed' in b.lbl_lucj_multi.value # results rendered + + +# ── W3 t2: the targeted widgets ARE refreshed (no rebuild ≠ no update) ─────── + +def test_multi_generate_targeted_widgets_refreshed(monkeypatch): + b, state = _build(monkeypatch) + import qpu_mapper.multi_sweep as ms + monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) + _on_multi(b) + + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + # Per-circuit override dropdowns reflect the 2-circuit result (in place). + dds = [c for c in b.lucj_multi_detail_box.children if isinstance(c, Dropdown)] + assert len(dds) == 2 + # ancilla-tool options + manual per-circuit tabs re-seeded for the new count + # (the targeted _build_dynamic_ui, done WITHOUT a content rebuild). + anc_labels = [lbl for lbl, _ in b.ancilla_tool.options] + assert 'Add Ancilla C1' in anc_labels and 'Add Ancilla C2' in anc_labels + assert len(b.manual_tabs.children) == 2 + + +# ── W3 t3: a checkbox toggle STILL rebuilds legitimately (X behavior intact) ─ + +def test_checkbox_toggle_still_rebuilds(monkeypatch): + b, state = _build(monkeypatch) + b.intra_qpu_mode.value = True + b.nav_bar.value = 'auto_lucj' + tab_before = b._auto_lucj_tabs + + b.intra_qpu_mode.value = False # legitimate structural change + assert b._auto_lucj_tabs is not tab_before # a real rebuild happened + assert len(b._auto_lucj_tabs.children) == 1 # Multi subpanel dropped + + +# ── W3 t4: the legacy multi Generate path gets the same no-rebuild treatment ─ + +def test_legacy_multi_generate_no_rebuild(monkeypatch): + b, state = _build(monkeypatch) + monkeypatch.setattr( + "qpu_mapper.auto_lucj.get_multi_circuit_layouts", + lambda **k: [ + {'circuit_idx': i, 'norb': 8, 'num_bridges': 0, + 'all_candidates': [{'layout': [0, 1, 2, 3], 'alpha': [0, 1], + 'beta': [2, 3], 'score': 0.03, 'rank': 1, + 'layout_full': [0, 1, 2, 3, 4]}]} + for i in range(2)]) + tab_before = _on_multi(b) + + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi.click() # legacy (non-sweep) multi + + assert b._auto_lucj_tabs is tab_before # no rebuild here either + assert b._auto_lucj_tabs.selected_index == 1 + assert 'circuits placed' in b.lbl_lucj_multi.value diff --git a/tests/test_sweep_notices.py b/tests/test_sweep_notices.py new file mode 100644 index 0000000..2fa2d49 --- /dev/null +++ b/tests/test_sweep_notices.py @@ -0,0 +1,214 @@ +"""NOTICE CAPTURE FOR ALL SWEEP PATHS. + +The scan already captured qpu_mapper WARNING+ into its loud '⚠ notices' bar via +a scoped handler. These tests pin the SAME capture for the LOCAL sweep and the +MULTI sweep + replan: warnings render into the respective notices widget, +deduplicate (message ×count), and NEVER leak to the root logger (propagate is +restored in finally — proven on the error path). +""" +import logging +from types import SimpleNamespace + +import numpy as np + +_QLOG = 'qpu_mapper' + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: + if on_error: + on_error(e) + return None + if on_done: + on_done(r) + return None + + +def _entry(prod, k): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': list(range(4, 4 + k)), + 'bridge_slots': tuple(range(0, 4 * k, 4)), + 'product_score': prod, 'additive_score': 1.0, 'lqs_circuit': None, + 'rank_in_stratum': 1, 'source': 'vf2'} + + +def _sweep(): + return {'strata': {2: [_entry(0.50, 2)], 1: [_entry(0.60, 1)]}, + 'k_max_effective': 2, 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 10, 'n_candidates_scored': 20, 'mapping_cap': 2000, + 'per_stratum': {2: {'n_direct': 1, 'n_derived': 0, 'truncated': False}, + 1: {'n_direct': 1, 'n_derived': 1, 'truncated': False}}} + + +def _multi_result(): + ch = _entry(0.60, 1) + return {'circuits': [{'circuit_idx': 0, 'chosen': ch, 'strata': {1: [ch]}, + 'per_stratum': {1: {'truncated': False}}}], + 'total_lqs_circuit': None, 'total_product': 0.60, 'failed_at': None} + + +def _build(monkeypatch): + import qpu_mapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b + + +class _RootSpy(logging.Handler): + """Records everything that reaches the ROOT logger — nothing captured + during a sweep should show up here (propagate=False).""" + def __init__(self): + super().__init__(level=logging.WARNING) + self.messages = [] + + def emit(self, record): + self.messages.append(record.getMessage()) + + +def _capture_handlers(): + from qpu_mapper.ui.lucj_panel import _ScanNoticeCapture + return [h for h in logging.getLogger(_QLOG).handlers + if isinstance(h, _ScanNoticeCapture)] + + +# ── t1: local sweep warning → notices rendered, nothing hits the root ─────── + +def test_local_sweep_notice_captured_not_leaked(monkeypatch): + b = _build(monkeypatch) + spy = _RootSpy() + root = logging.getLogger() + root.addHandler(spy) + lg = logging.getLogger(_QLOG) + try: + def warn_sweep(norb, backend, props, **kw): + lg.warning("Requested 6 bridges does not fit; falling back") + return _sweep() + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + warn_sweep) + + b.lucj_ancilla_dd.value = -1 # Auto → stratified sweep path + b.btn_lucj_run.click() + + notices = b.lbl_lucj_notices.value + assert 'notices' in notices # loud bar rendered + assert 'Requested 6 bridges does not fit' in notices + assert 'background:#fff3cd' in notices # same amber Y-pass styling + # Not leaked under the cell: the root logger never saw it. + assert not any('Requested 6 bridges' in m for m in spy.messages) + # Handler detached after the sweep (restoration). + assert _capture_handlers() == [] + finally: + root.removeHandler(spy) + + +# ── t2: duplicate messages deduplicate with ×count ────────────────────────── + +def test_local_sweep_dedup_count(monkeypatch): + b = _build(monkeypatch) + lg = logging.getLogger(_QLOG) + + def warn_sweep(norb, backend, props, **kw): + lg.warning("vf2 truncating to 2000") + lg.warning("vf2 truncating to 2000") + lg.warning("bridge fallback") + return _sweep() + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", warn_sweep) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + + notices = b.lbl_lucj_notices.value + assert 'vf2 truncating to 2000 ×2' in notices # deduped with count + assert 'bridge fallback' in notices # singleton, no × + assert 'bridge fallback ×' not in notices + assert '>3' in notices # badge = 3 total records + + +# ── t3 is the existing scan suite (unchanged) — see test_scan_notices.py ──── + + +# ── t4: restoration on error — BOTH paths (try/finally proof) ─────────────── + +def test_local_sweep_restores_on_error(monkeypatch): + b = _build(monkeypatch) + lg = logging.getLogger(_QLOG) + assert lg.propagate is True # baseline + + def boom_sweep(norb, backend, props, **kw): + lg.warning("partial notice before the crash") + raise RuntimeError("sweep exploded") + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", boom_sweep) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() # handler catches → error banner + + assert '❌' in b.lbl_lucj_status.value # error surfaced + assert lg.propagate is True # restored despite raise + assert _capture_handlers() == [] # handler detached + + +def test_multi_sweep_restores_on_error(monkeypatch): + b = _build(monkeypatch) + lg = logging.getLogger(_QLOG) + assert lg.propagate is True + + def boom_multi(*a, **k): + lg.warning("multi partial notice") + raise RuntimeError("multi exploded") + monkeypatch.setattr("qpu_mapper.multi_sweep.sweep_multi_circuits", boom_multi) + + b.lucj_multi_norbs.value = "8" + b.btn_lucj_multi_sweep.click() + + assert '❌' in b.lbl_lucj_multi.value # error surfaced + assert lg.propagate is True # restored despite raise + assert _capture_handlers() == [] + + +# ── multi sweep happy path → notices rendered into the multi widget ───────── + +def test_multi_sweep_notice_captured(monkeypatch): + b = _build(monkeypatch) + lg = logging.getLogger(_QLOG) + + def warn_multi(*a, **k): + lg.warning("Requested 6 bridges does not fit; falling back") + lg.warning("Requested 6 bridges does not fit; falling back") + return _multi_result() + monkeypatch.setattr("qpu_mapper.multi_sweep.sweep_multi_circuits", warn_multi) + + b.lucj_multi_norbs.value = "8" + b.btn_lucj_multi_sweep.click() + + notices = b.lbl_lucj_multi_notices.value + assert 'Requested 6 bridges does not fit; falling back ×2' in notices + assert 'background:#fff3cd' in notices + assert _capture_handlers() == [] diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index ed26445..39350d8 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -147,6 +147,36 @@ def entry(kk, rank): } +# ── A3: local sweep status carries a 'scored on live · HH:MM' vintage ─────── +# so a scan-vs-local number mismatch reads as calibration drift (the two +# numbers were taken at different moments), not a bug. + +def test_local_sweep_status_shows_live_vintage(builder, monkeypatch): + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _fake_sweep_result()) + b = builder + b.btn_lucj_run.click() + + status = b.lbl_lucj_status.value + assert '✅' in status # success summary + import re + assert re.search(r'scored on live · \d\d:\d\d', status) # live vintage stamp + + +def test_local_sweep_status_vintage_uses_past_date(builder, monkeypatch): + monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _fake_sweep_result()) + b = builder + # A selected PAST date → the vintage names that date, not live. + b.state.time_mode = 'point' + b.state.point_timestamp = '2026-07-01 08:00:00' + b.btn_lucj_run.click() + + status = b.lbl_lucj_status.value + assert 'scored on 2026-07-01' in status + assert 'live ·' not in status + + def test_top_n_field_controls_dropdown_entries(builder, monkeypatch): monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", _fake_sweep_topn) diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py index 8f8d072..afdaa46 100644 --- a/tests/test_ui_cleanup.py +++ b/tests/test_ui_cleanup.py @@ -70,11 +70,11 @@ def _build(monkeypatch): def test_local_block_above_scan(monkeypatch): b = _build(monkeypatch) - view = b._build_auto_lucj_view() - children = list(view.children) - # The local sweep dropdown must precede the scan results container. + b._build_auto_lucj_view() + # The single-circuit content now lives in its own subpanel (the Auto tab + # splits Single / Multi via a Tab); the ordering invariant holds there. + children = list(b._auto_single_panel.children) assert children.index(b.dd_lucj_layout) < children.index(b.scan_results_box) - # And the "This backend ()" header exists, with the active name. from ipywidgets import HTML headers = [c.value for c in children if isinstance(c, HTML)] assert any('📍 This backend (ibm_here)' in h for h in headers) From 4bdde3ca3e7b00d0ff95a7e0f0212316491808dd Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Wed, 15 Jul 2026 16:14:38 -0400 Subject: [PATCH 22/66] Plot hardening: node trace follows state, paint failures surfaced, dropdown ordering, dead code --- qpu_mapper/plot.py | 19 +++++++- qpu_mapper/ui/inter_qpu.py | 29 +++++++++-- qpu_mapper/ui/lucj_panel.py | 30 +++++++----- tests/test_inter_qpu_handoff.py | 85 ++++++++++++++++++++++++++++----- tests/test_multi_sweep_ui.py | 48 +++++++++++++++++++ tests/test_plot_node_guard.py | 77 +++++++++++++++++++++++++++++ 6 files changed, 260 insertions(+), 28 deletions(-) create mode 100644 tests/test_plot_node_guard.py diff --git a/qpu_mapper/plot.py b/qpu_mapper/plot.py index 2305dbb..17b0889 100644 --- a/qpu_mapper/plot.py +++ b/qpu_mapper/plot.py @@ -534,13 +534,30 @@ def refresh_plot(fig, state, widgets_ref): # place on the first refresh. (We used .uid first, but # FigureWidget regenerates .uid; .meta is preserved.) q_trace = _trace_by_meta(fig, _META_QUBITS) - if q_trace is not None: + # Node markers must never diverge from the state being painted. The + # per-node text / color / line arrays are all sized to n_q; if we wrote + # them while leaving q_trace.x/y at a STALE length, the markers would + # keep old positions but receive empty color/text → invisible nodes, + # edges still drawn ("edges but no nodes"). So (a) rewrite x/y from the + # SAME state (state.x_coord/y_coord) in the same update, and (b) if the + # state carries no qubits (or coords don't cover them), refuse to empty + # a populated trace — leave it intact and warn loudly instead. + coords_ok = (n_q > 0 + and len(state.x_coord) >= n_q and len(state.y_coord) >= n_q) + if q_trace is not None and coords_ok: + q_trace.x = tuple(float(state.x_coord[i]) for i in range(n_q)) + q_trace.y = tuple(float(state.y_coord[i]) for i in range(n_q)) q_trace.mode = 'markers+text' if w.show_numbers.value else 'markers' q_trace.hoverinfo = 'text' if is_err else 'none' q_trace.text = tuple(str(state.qubit_ids[i]) for i in range(n_q)) if w.show_numbers.value else tuple('' for _ in range(n_q)) q_trace.hovertext = tuple(h_text) q_trace.marker.update(color=list(colors), size=int(w.size_slider.value), line=dict(color=list(l_colors), width=list(l_widths))) q_trace.update(textfont=dict(color=list(text_colors), size=int(w.font_size_slider.value))) + elif q_trace is not None: + _log.warning( + "refresh_plot: %d qubit_ids vs %d/%d coords — leaving the " + "existing qubit trace intact (edges-but-no-nodes guard).", + n_q, len(state.x_coord), len(state.y_coord)) fig.layout.paper_bgcolor = 'white'; fig.layout.plot_bgcolor = 'white'; fig.layout.font.color = 'black' _update_colorbars(fig, state, q_arr, g_arr, q_prop_key, g_prop_key, q_label, g_label, is_err, _is_delta) diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index c272c67..195dda7 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -385,11 +385,20 @@ def _on_connect_qpu2(b): # the candidate never reached the first paint. Apply post-clear and # repaint the figure so it shows on the very first view. pend = _pending_handoff[0] + paint_err = None if pend is not None and pend[0] == backend_name: - with contextlib.suppress(Exception): + # Narrow try (was a blanket suppress): a candidate-paint failure + # must never crash the connect, but it must NOT be hidden either + # — last night's empty-map survived precisely because it was + # swallowed. Log it and surface it on the QPU-2 status below. + try: _apply_candidate_to_state(s2, pend[1]) from .. import plot as _plot _plot.refresh_plot(f2, s2, w2) + except Exception as _pe: # noqa: BLE001 - reported below + paint_err = _pe + _log.warning("QPU-2 candidate paint failed for %s: %s", + backend_name, _pe, exc_info=True) _pending_handoff[0] = None # Top-level shape: HBox([ui_sidebar, fig_box]). # fig_box.children = (lbl_fig1, zoom_bar, fig). @@ -465,6 +474,10 @@ def _on_connect_qpu2(b): f"{'
📅 ' + esc(s2.calibration_data_label or '') if s2.calibration_data_label else ''}" f"" ) + if paint_err is not None: + lbl_qpu2_status.value += ( + f"
" + f"⚠ candidate paint failed: {esc(str(paint_err))}
") except Exception as e: lbl_qpu2_status.value = ( f"" @@ -498,16 +511,26 @@ def _auto_connect(backend_name, candidate): if (s2 is not None and getattr(s2, 'active_backend_name', None) == backend_name): _pending_handoff[0] = None - with contextlib.suppress(Exception): + # Narrow try (was a blanket suppress): repaint failures are logged + # and surfaced, not hidden — see the first-connect path. + paint_err = None + try: _apply_candidate_to_state(s2, candidate) if _fig2[0] is not None and _w2[0] is not None: from .. import plot as _plot _plot.refresh_plot(_fig2[0], s2, _w2[0]) + except Exception as _pe: # noqa: BLE001 - reported below + paint_err = _pe + _log.warning("QPU-2 same-backend repaint failed for %s: %s", + backend_name, _pe, exc_info=True) lbl_qpu2_status.value = ( f"
✅ Applied to already-connected " - f"{esc(str(backend_name))}.
") + f"{esc(str(backend_name))}." + + ("" if paint_err is None else + f"
" + f"⚠ candidate paint failed: {esc(str(paint_err))}
")) return # A connect already in flight → the staging above is enough; diff --git a/qpu_mapper/ui/lucj_panel.py b/qpu_mapper/ui/lucj_panel.py index a95d806..960c7c5 100644 --- a/qpu_mapper/ui/lucj_panel.py +++ b/qpu_mapper/ui/lucj_panel.py @@ -155,7 +155,6 @@ def setup_lucj_callbacks(ctx): lbl_lucj_multi_notices = ctx.lbl_lucj_multi_notices lucj_multi_detail_box = ctx.lucj_multi_detail_box - num_circuits = ctx.num_circuits set_num_circuits = ctx.set_num_circuits # count change w/o full view rebuild intra_qpu_mode = ctx.intra_qpu_mode @@ -1553,16 +1552,30 @@ def _cb(change): _on_multi_override(i, flat[idx]) return _cb + def _multi_override_sort_key(e): + """Order override alternatives by the DISPLAYED metric: circuit LQS + descending, template (no lqs_circuit) entries sink below all scored + ones, product_score breaks ties. So the dropdown reads best→worst and + the preselected chosen sits at/near the top — not mid-list by stratum.""" + lqs = e.get('lqs_circuit') + return (0 if lqs is not None else 1, + -(lqs if lqs is not None else 0.0), + -(e.get('product_score') or 0.0)) + def _build_multi_override_dropdowns(result): _multi_sweep['dropdowns'] = {} widgets = [] for c in result['circuits']: i = c['circuit_idx'] + # Flatten across strata, then rank by the displayed metric (best + # first) — labels keep "k=… · #… · LQS …%" so no info is lost. + entries = sorted( + (e for k in c['strata'] for e in c['strata'][k]), + key=_multi_override_sort_key) flat, opts = [], [] - for k in sorted(c['strata'].keys(), reverse=True): - for e in c['strata'][k]: - opts.append((_entry_label(e), len(flat))) - flat.append(e) + for e in entries: + opts.append((_entry_label(e), len(flat))) + flat.append(e) if not opts: continue chosen_idx = next((j for j, e in enumerate(flat) @@ -1765,13 +1778,6 @@ def _payload(r): payload_fn=_payload, disabled_tip='batch does not fully fit on this backend') - def _batch_handoff(backend_name, chosen_list): - hook = inter_qpu_handoff[0] if inter_qpu_handoff else None - if hook is None: - return - with contextlib.suppress(Exception): - hook(backend_name, chosen_list) # list → batch handoff - def _on_scan_batch(b): if state.active_backend is None: lbl_lucj_multi.value = ( diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py index 173420f..60aa0e5 100644 --- a/tests/test_inter_qpu_handoff.py +++ b/tests/test_inter_qpu_handoff.py @@ -228,16 +228,35 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): # This drives the REAL build (only the device/network deps are stubbed) and # proves the candidate both LANDS on QPU-2 state AND reaches the figure. -def _qubit_marker_colors(fig): - """The per-qubit marker colour array from the figure (len == n_qubits).""" - for tr in fig.data: - mc = getattr(getattr(tr, 'marker', None), 'color', None) - if isinstance(mc, (list, tuple)) and len(mc) == 8: - return list(mc) - return [] +def _qubit_trace(fig): + from qpu_mapper.plot import _META_QUBITS + return next((tr for tr in fig.data + if getattr(tr, 'meta', None) == _META_QUBITS), None) -def test_first_connect_paints_candidate_real_build(monkeypatch): +def _qubit_marker_colors(fig): + """The per-qubit marker colour array from the figure (len == n_qubits).""" + qt = _qubit_trace(fig) + col = getattr(getattr(qt, 'marker', None), 'color', None) if qt else None + return list(col) if isinstance(col, (list, tuple)) else [] + + +def _assert_base_map(fig, n): + """The QPU-2 DEVICE map must have n qubit markers WITH index labels AND + per-node colours — never edges-on-empty-cells. Pins the D-class 'bare + edges, no nodes, no labels' failure so it can never regress silently.""" + qt = _qubit_trace(fig) + assert qt is not None, "qubit node trace missing entirely" + assert qt.x is not None and len(qt.x) == n, f"node positions: {qt.x}" + assert qt.text is not None and len(qt.text) == n, "node index labels missing" + col = getattr(qt.marker, 'color', None) + assert isinstance(col, (list, tuple)) and len(col) == n, "node colours missing" + + +def _primary_with_stubs(monkeypatch): + """A built primary MapperUIBuilder with device/network deps stubbed so the + REAL secondary build_mapper_ui runs on connect. Returns (b, capture) where + capture records the connected s2/fig via a build wrapper.""" import numpy as np def _fake_device(state, vendor, chip, date, prefetched_props=None): @@ -274,7 +293,6 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): b = MapperUIBuilder(state) b.build() - # Capture the connected QPU-2 state + figure by wrapping the REAL build. import qpu_mapper.ui as ui_pkg real = ui_pkg.build_mapper_ui cap = {} @@ -284,6 +302,11 @@ def _wrap(s2, is_secondary=False, return_widgets=False): cap['s2'], cap['fig'] = s2, res[1] return res monkeypatch.setattr(ui_pkg, 'build_mapper_ui', _wrap) + return b, cap + + +def test_first_connect_paints_candidate_real_build(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) cand = {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [4], 'lqs_circuit': 0.54} b._inter_qpu_handoff[0]('ibm_k', cand) @@ -292,9 +315,47 @@ def _wrap(s2, is_secondary=False, return_widgets=False): d = cap['s2'].layouts_data[0] assert d['alpha'] == ['0', '1'] and d['beta'] == ['2', '3'] and d['ancilla'] == ['4'] assert d['styles'] # per-qubit paint styles set - # (b) figure RECEIVED the layout — the 5 candidate qubits are painted, not - # the unpainted white; an untouched qubit stays white (specificity). + # (b) the DEVICE map itself drew — nodes + labels present (not edges-only). + _assert_base_map(cap['fig'], 8) + # (c) the candidate reached the figure — its 5 qubits painted, others white. colors = _qubit_marker_colors(cap['fig']) - assert len(colors) == 8 assert all(colors[i] != '#ffffff' for i in (0, 1, 2, 3, 4)) # painted assert colors[7] == '#ffffff' # untouched + + +# ── D3: the base device map is present on ALL THREE paint entry points ────── + +def test_same_backend_repaint_keeps_base_map(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) + b._inter_qpu_handoff[0]('ibm_k', {'alpha': [0], 'beta': [1], 'ancillas': [2]}) + fig = cap['fig'] + _assert_base_map(fig, 8) # after first connect + + # Same backend again → in-place repaint (no rebuild). Base map must survive. + b._inter_qpu_handoff[0]('ibm_k', {'alpha': [5], 'beta': [6], 'ancillas': [7]}) + _assert_base_map(fig, 8) # still nodes + labels + colors = _qubit_marker_colors(fig) + assert colors[5] != '#ffffff' and colors[7] != '#ffffff' # new candidate painted + assert colors[0] == '#ffffff' # old selection cleared + + +def test_manual_connect_no_candidate_keeps_base_map(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) + # A connect with an EMPTY batch (no candidate to apply) still must draw the + # full device map — nodes + labels — exactly like a manual Connect QPU 2. + b._inter_qpu_handoff[0]('ibm_k', []) + _assert_base_map(cap['fig'], 8) + colors = _qubit_marker_colors(cap['fig']) + assert all(c == '#ffffff' for c in colors) # unpainted default nodes + + +def test_batch_handoff_keeps_base_map_real_build(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) + batch = [{'alpha': [0], 'beta': [1], 'ancillas': [2]}, + {'alpha': [3], 'beta': [4], 'ancillas': [5]}] + b._inter_qpu_handoff[0]('ibm_k', batch) # LIST → batch handoff + # Base device map intact (nodes + labels + colours) after a batch paint. + _assert_base_map(cap['fig'], 8) + # Both circuits landed on QPU-2 state. + assert cap['s2'].layouts_data[0]['ancilla'] == ['2'] + assert cap['s2'].layouts_data[1]['ancilla'] == ['5'] diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py index fd3f2d7..410ec61 100644 --- a/tests/test_multi_sweep_ui.py +++ b/tests/test_multi_sweep_ui.py @@ -130,6 +130,54 @@ def test_multi_sweep_happy_path(monkeypatch): assert b.btn_lucj_multi_sweep.disabled is False # re-armed +# ── override dropdown ranks best→worst by LQS, not by stratum order ───────── + +def test_override_dropdown_sorted_best_first(monkeypatch): + import re + b, state = _build(monkeypatch) + # k=2 stratum has a LOWER LQS than k=1 — stratified order (k desc) would put + # the worse candidate first. The dropdown must instead read best→worst. + e_k2 = _entry([4, 5], 0.40, lqs=0.40, rank=1) + e_k1a = _entry([4], 0.66, lqs=0.65, rank=1) # the chosen best + e_k1b = _entry([5], 0.55, lqs=0.55, rank=2) + c0 = _circuit(0, e_k1a, {2: [e_k2], 1: [e_k1a, e_k1b]}) + result = {'circuits': [c0], 'total_product': 0.65, + 'total_lqs_circuit': 0.65, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': None, '_context': {}} + _patch_engine(monkeypatch, result) + + b.lucj_multi_norbs.value = '8' + b.btn_lucj_multi_sweep.click() + + dds = _dropdowns(b.lucj_multi_detail_box) + assert len(dds) == 1 + labels = [o[0] for o in dds[0].options] + pcts = [float(re.search(r'LQS ([\d.]+)%', l).group(1)) for l in labels] + assert pcts == [65.0, 55.0, 40.0] # descending, best first + assert dds[0].value == 0 # chosen best preselected + assert 'LQS 65.0%' in labels[0] + + +def test_override_template_entries_sink(monkeypatch): + b, state = _build(monkeypatch) + # A scored entry (lqs_circuit) must rank ABOVE a template one (no + # lqs_circuit) even if the template's product_score is higher. + scored = _entry([4], 0.30, lqs=0.30, rank=1) # scored 30% + templ = _entry([5], 0.90, rank=2) # template, no lqs + c0 = _circuit(0, scored, {1: [templ, scored]}) + result = {'circuits': [c0], 'total_product': 0.30, + 'total_lqs_circuit': 0.30, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': None, '_context': {}} + _patch_engine(monkeypatch, result) + + b.lucj_multi_norbs.value = '8' + b.btn_lucj_multi_sweep.click() + + labels = [o[0] for o in _dropdowns(b.lucj_multi_detail_box)[0].options] + assert 'template' in labels[1].lower() # template sinks below + assert 'template' not in labels[0].lower() # scored ranks first + + # ── override — replan_from(result, 0, alt) re-applies + updates summary ── def test_multi_sweep_override(monkeypatch): diff --git a/tests/test_plot_node_guard.py b/tests/test_plot_node_guard.py new file mode 100644 index 0000000..597545b --- /dev/null +++ b/tests/test_plot_node_guard.py @@ -0,0 +1,77 @@ +"""F1 guard: refresh_plot must never leave the qubit node trace with positions +but empty colour/text ('edges but no nodes'). It (a) rewrites x/y from the SAME +state it paints, and (b) refuses to empty a populated trace when the state has +no qubit_ids — logging loudly instead. +""" +import logging +from types import SimpleNamespace + +import numpy as np + + +def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _build(monkeypatch): + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "stub" + state.active_chip = "stub_chip" + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b + + +def _qubit_trace(fig): + from qpu_mapper.plot import _META_QUBITS + return next(t for t in fig.data if getattr(t, 'meta', None) == _META_QUBITS) + + +def test_refresh_preserves_nodes_when_qubit_ids_empty(monkeypatch, caplog): + b = _build(monkeypatch) + from qpu_mapper import plot + + qt = _qubit_trace(b.fig) + assert len(qt.x) == 8 and len(qt.marker.color) == 8 # nodes present + + # Emptying qubit_ids while edges remain used to wipe the node colour/text + # (positions kept) → invisible nodes, edges drawn. The guard must refuse. + b.state.qubit_ids = [] + with caplog.at_level(logging.WARNING, logger='qpu_mapper.plot'): + plot.refresh_plot(b.fig, b.state, b.widgets_ref) + + assert len(qt.x) == 8 # positions intact + assert isinstance(qt.marker.color, (list, tuple)) and len(qt.marker.color) == 8 + assert qt.text is not None and len(qt.text) == 8 # labels intact + assert any('edges-but-no-nodes' in r.message for r in caplog.records) + + +def test_refresh_rewrites_node_positions_from_state(monkeypatch): + b = _build(monkeypatch) + from qpu_mapper import plot + + # Move the device coordinates, then refresh: the node trace x/y must follow + # the state (same source), so it can never diverge from what is painted. + b.state.x_coord = [v + 100.0 for v in b.state.x_coord] + plot.refresh_plot(b.fig, b.state, b.widgets_ref) + + qt = _qubit_trace(b.fig) + assert list(qt.x) == [float(v) for v in b.state.x_coord] + assert len(qt.x) == len(qt.marker.color) == len(b.state.qubit_ids) From f9c3e1753f5d637e43010af08c28bd52dd464c80 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Wed, 15 Jul 2026 18:19:35 -0400 Subject: [PATCH 23/66] inter-QPU debug --- qpu_mapper/__init__.py | 8 + qpu_mapper/async_util.py | 211 ++++++++---- qpu_mapper/ui/builder.py | 7 + qpu_mapper/ui/inter_qpu.py | 173 +++++----- tests/test_async_util.py | 534 ++++++++++++++++++++++------- tests/test_inter_qpu_handoff.py | 51 ++- tests/test_inter_qpu_live_model.py | 146 ++++++++ 7 files changed, 846 insertions(+), 284 deletions(-) create mode 100644 tests/test_inter_qpu_live_model.py diff --git a/qpu_mapper/__init__.py b/qpu_mapper/__init__.py index a9f7a46..554895f 100644 --- a/qpu_mapper/__init__.py +++ b/qpu_mapper/__init__.py @@ -16,6 +16,14 @@ def run(): """Launch the QPU Mapper UI (sidebar layout).""" + # Capture the kernel main loop HERE — run() is called from a notebook cell, + # which is GUARANTEED to be the main thread with the kernel loop up. This is + # the earliest, most reliable capture point; later build() calls are + # capture-once + main-only, so they never overwrite it (e.g. the secondary + # build re-entering build() must not clobber this with a worker/None value). + from .async_util import init_main_loop + init_main_loop() + def _on_connect(vendor, backend_name, backend, chip, props, props_warning, ansatz, service, available_backends): diff --git a/qpu_mapper/async_util.py b/qpu_mapper/async_util.py index d95ee6f..356bd86 100644 --- a/qpu_mapper/async_util.py +++ b/qpu_mapper/async_util.py @@ -4,94 +4,163 @@ `default_spawn_bg` runs a function on a daemon thread and marshals its completion callback back onto the kernel's main event loop. Extracted from ui.time_panel.py so non-UI callers (connection, ui.history, ui/builder) can -use it without importing a UI panel module. Imports only stdlib, so it can -never participate in an import cycle with the rest of the package. +use it without importing a UI panel module. Imports only stdlib (tornado is a +soft, lazy secondary), so it can never participate in an import cycle with the +rest of the package. + +Threading contract (the whole point of this module): +ipywidgets value writes are advertised as thread-safe, but +plotly.FigureWidget.batch_update() — invoked by refresh_plot on the +completion callback — silently drops its comm mutations when run from a +worker thread, giving an empty/ghost map LIVE (invisible headless, which has +no frontend). So the completion callback MUST run on the thread that owns the +kernel loop. We guarantee that by capturing the main loop + main-thread +identity ONCE, on the main thread, at setup time (:func:`init_main_loop`, +called from build()), and scheduling onto THAT captured loop from workers — +never resolving a loop from the calling worker (which has none). """ +import asyncio import logging import threading _log = logging.getLogger(__name__) -# Cached scheduler — resolved once on the kernel's main thread (the thread -# that first imports a module which imports this one, i.e. during -# build_mapper_ui). Resolving per-job did identical work on every call: -# import tornado, fetch IOLoop.current(), allocate a lambda. `_MAIN_LOOP_ -# SCHEDULER` may be None if the import-time resolver failed; default_spawn_bg -# re-tries lazily on first call so a kernel that started its event loop AFTER -# import still works. -_MAIN_LOOP_SCHEDULER = None - - -def _resolve_main_loop_scheduler(): - """Return a callable that schedules a zero-arg function on the main - event loop, so background workers can hand UI mutations back to the - thread that owns the kernel. - - Why we need this: ipywidgets value assignments are advertised as - thread-safe, but plotly.FigureWidget.batch_update() — invoked by - refresh_plot via on_done — has produced rendering glitches when - called from worker threads (cached geometry, ghost edges). Marshaling - the callback onto the main loop guarantees the figure mutates on the - same thread the kernel runs on. - - Resolution order: - 1. a RUNNING event loop → tornado IOLoop (classic notebook + most - JupyterLab kernels), else asyncio call_soon_threadsafe - 2. inline fallback (run on the worker thread, original behaviour) - - We gate on a *running* loop via ``asyncio.get_running_loop()`` FIRST. - That call never warns; ``tornado.ioloop.IOLoop.current()`` (and the - ``asyncio.get_event_loop()`` it wraps) emits Python ≥3.10's "There is no - current event loop" DeprecationWarning when called with no loop running — - the headless-test case. With no running loop the correct scheduler is the - inline fallback anyway (a non-running loop's ``add_callback`` would never - fire), so we must never reach that deprecated path. +# Captured ONCE on the MAIN thread by init_main_loop(). This (thread, loop) +# pair is the ONLY scheduling state — no per-callsite resolution, no sticky +# "inline" cache that a worker could inherit. `_MAIN_LOOP` stays None headless +# (no running loop) → marshal runs inline, warning-free. +_MAIN_THREAD = None # threading.Thread that owns the kernel +_MAIN_LOOP = None # captured asyncio loop or tornado IOLoop (or None) +_MAIN_LOOP_KIND = None # 'asyncio' | 'tornado' | None + + +def _capture_main_loop(): + """Return (loop, kind) for the loop owned by THIS (main) thread, or + (None, None). Tiered, because the live capture happens inside a WIDGET + CALLBACK (launch_mapper → build), NOT top-level cell code — so + ``get_running_loop()`` often fails there even though the kernel loop is + running and owned by this thread. + + 1. ``get_running_loop()`` — we're inside a coroutine/callback ON it; + 2. the thread's ALREADY-SET event loop, IF ``is_running()`` — the + ipykernel case: the thread owns the running kernel loop but we're in a + widget-callback context, not its coroutine. Read via the policy's + thread-local so we never CREATE (and leak) a loop when none is set — + which would trip ResourceWarning under -W error headless; + 3. a current tornado ``IOLoop`` (wraps the same asyncio loop). + Headless (no running/set loop, no IOLoop) → (None, None) → marshal inline. """ - import asyncio + # 1. running loop try: - running = asyncio.get_running_loop() + return asyncio.get_running_loop(), 'asyncio' except RuntimeError: - running = None - if running is not None: - try: - from tornado.ioloop import IOLoop - loop = IOLoop.current() # safe: a loop is running - return lambda cb: loop.add_callback(cb) - except Exception: - _log.debug("tornado IOLoop unavailable", exc_info=True) - return lambda cb: running.call_soon_threadsafe(cb) - # No running event loop (headless tests, or kernel loop not yet started) — - # run inline on the worker thread (original fallback behaviour). - return lambda cb: cb() + pass + # 2. the thread's ALREADY-SET, running event loop (live ipykernel main + # thread) — read the policy thread-local, never call get_event_loop() + # (which creates+leaks a loop when none is set). + try: + policy = asyncio.get_event_loop_policy() + local = getattr(policy, '_local', None) + loop = getattr(local, '_loop', None) + if loop is not None and loop.is_running(): + return loop, 'asyncio' + except Exception: + _log.debug("asyncio set-loop probe failed", exc_info=True) + # 3. tornado IOLoop (optional dependency); probed WITHOUT creating one. + try: + import warnings + from tornado.ioloop import IOLoop + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + loop = IOLoop.current(instance=False) + if loop is not None: + return loop, 'tornado' + except Exception: + _log.debug("tornado IOLoop probe failed", exc_info=True) + return None, None + + +def init_main_loop(): + """Capture the kernel main loop + main-thread identity — CAPTURE-ONCE, + MAIN-ONLY. + + Call at true startup (run()) and from the UI build. Two guards make it safe + to call from anywhere, any number of times — critical because the SECONDARY + build re-enters build() and, if that ever runs on a worker, must NOT clobber + a good main-thread capture with None (the live empty-map cause: a worker + capture wrote ``loop=None`` over the real loop → marshal fell back to + inline-on-worker): + + * if a loop is ALREADY captured → return (never overwrite a good value); + * if NOT on the main thread → return (a worker owns no loop; capturing + there would only ever write None). Logged so the live toggle shows it. + + Otherwise capture via the tiered :func:`_capture_main_loop` and log an INFO + line so the live toggle shows thread + whether a loop was actually found. + Headless leaves the loop None (and retries on the next main-thread call), + so :func:`marshal_to_main` runs inline, warning-free. + """ + global _MAIN_THREAD, _MAIN_LOOP, _MAIN_LOOP_KIND + if _MAIN_LOOP is not None: + return # already captured — never redo + if threading.current_thread() is not threading.main_thread(): + _log.debug("capture skipped: not on main thread (%s)", + threading.current_thread().name) + return + _MAIN_THREAD = threading.current_thread() + _MAIN_LOOP, _MAIN_LOOP_KIND = _capture_main_loop() + _log.info("main loop captured: thread=%s loop=%s kind=%s", + _MAIN_THREAD.name, _MAIN_LOOP is not None, _MAIN_LOOP_KIND) + + +def _schedule_on_captured_loop(cb): + """Thread-safe schedule of ``cb`` onto the CAPTURED main loop.""" + if _MAIN_LOOP_KIND == 'asyncio': + _MAIN_LOOP.call_soon_threadsafe(cb) + else: # tornado IOLoop + _MAIN_LOOP.add_callback(cb) def marshal_to_main(cb): - """Schedule a zero-arg callback ``cb`` onto the kernel main loop. + """Run zero-arg ``cb`` on the kernel main loop. + + Resolution (uses the pair captured by :func:`init_main_loop`, NEVER the + calling thread's context): - The incremental-update counterpart to :func:`default_spawn_bg` (which - only marshals completion). Use it to push progress updates from a worker - thread to widgets without ever touching them off-thread. Reuses the same - cached scheduler. Safe to call from any thread; on a kernel with no event - loop it falls back to running ``cb`` inline. + 1. already on the captured main thread → run inline (correct + warning- + free — this is the manual-button and headless-main path); + 2. off-thread with a captured loop → schedule onto THAT loop + (``call_soon_threadsafe`` / ``add_callback``) so the callback lands on + the main thread — the live worker→main hand-off; + 3. no captured loop (headless, or init_main_loop never ran) → inline. + + Safe to call from any thread. """ - global _MAIN_LOOP_SCHEDULER - if _MAIN_LOOP_SCHEDULER is None: - _MAIN_LOOP_SCHEDULER = _resolve_main_loop_scheduler() - _MAIN_LOOP_SCHEDULER(cb) + if _MAIN_THREAD is not None and threading.current_thread() is _MAIN_THREAD: + _log.debug("marshal_to_main: inline (already on main thread)") + cb() + return + if _MAIN_LOOP is not None: + try: + _schedule_on_captured_loop(cb) + _log.debug("marshal_to_main: scheduled to captured loop (%s)", + _MAIN_LOOP_KIND) + return + except Exception: + _log.exception("marshal_to_main: scheduling onto the captured loop " + "failed; running inline") + else: + _log.debug("marshal_to_main: inline (no captured loop)") + cb() def default_spawn_bg(fn, on_done=None, on_error=None): - """Run `fn()` in a daemon thread and marshal the completion callback - (`on_done` or `on_error`) onto the main event loop. - - Callers can substitute their own spawn_bg (e.g. queue + Play-timer) - if they need finer control over scheduling.""" - global _MAIN_LOOP_SCHEDULER - if _MAIN_LOOP_SCHEDULER is None: - _MAIN_LOOP_SCHEDULER = _resolve_main_loop_scheduler() - schedule = _MAIN_LOOP_SCHEDULER + """Run `fn()` in a daemon thread and marshal its completion callback + (`on_done` or `on_error`) onto the kernel main loop via marshal_to_main. + Callers can substitute their own spawn_bg (e.g. queue + Play-timer) if + they need finer control over scheduling.""" def _safe(cb, arg): try: cb(arg) @@ -104,10 +173,10 @@ def _worker(): except Exception as exc: _log.exception("Background op raised") if on_error: - schedule(lambda err=exc: _safe(on_error, err)) + marshal_to_main(lambda err=exc: _safe(on_error, err)) return if on_done: - schedule(lambda: _safe(on_done, result)) + marshal_to_main(lambda: _safe(on_done, result)) t = threading.Thread(target=_worker, daemon=True) t.start() diff --git a/qpu_mapper/ui/builder.py b/qpu_mapper/ui/builder.py index 34fd7a9..3c94e3a 100644 --- a/qpu_mapper/ui/builder.py +++ b/qpu_mapper/ui/builder.py @@ -95,6 +95,13 @@ def build(self, return_widgets=False): reach the Fig Width/Height sliders directly instead of walking the tree by description). ``self.widgets_ref`` is always populated. """ + # Capture the kernel main loop + main-thread identity HERE — build() + # runs on the main thread inside the running loop (live cell execution), + # which is the only place asyncio.get_running_loop() succeeds. Workers + # then schedule their paint onto THIS captured loop instead of resolving + # (and inline-running) on themselves. Idempotent; no-op headless. + from ..async_util import init_main_loop + init_main_loop() ui_hbox, _ = self._run_pipeline() self.ui_hbox = ui_hbox if return_widgets: diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index 195dda7..e26df9d 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -96,10 +96,9 @@ def setup_inter_qpu(ctx): _dispose2 = [None] # callable that unobserves all QPU 2 widgets _connect_in_flight = [False] # race guard: one auto-connect at a time - # Background runner for the ONE-CLICK auto-connect. The Connect-QPU2 - # button handler is SYNCHRONOUS + network-touching; the scan pattern - # (default_spawn_bg + marshalled on_done/on_error) keeps the kernel - # responsive. Injectable via ctx for headless tests. + # Background runner for the ONE-CLICK auto-connect: the network fetch runs + # on a worker; default_spawn_bg marshals the completion (the PAINT) back + # onto the kernel main loop. Injectable via ctx for headless tests. _spawn_bg = getattr(ctx, 'spawn_bg', None) if _spawn_bg is None: from ..async_util import default_spawn_bg as _spawn_bg @@ -320,34 +319,38 @@ def stage_remote_candidate(backend_name, candidate): if handoff_cell is not None: handoff_cell[0] = lambda bn, cand: _auto_connect(bn, cand) - # ── Connect-QPU2 handler ──────────────────────────────────── - def _on_connect_qpu2(b): - # Returns None on success, or an error STRING on failure — so the - # one-click auto path can tell whether to fall back to staged. - # The button's on_click ignores the return, so its behaviour is - # unchanged. - backend_name = dd_backend_qpu2.value - if not backend_name: - lbl_qpu2_status.value = ( - "" - "Select a backend" - ) - return 'Select a backend' - if state.active_service is None: - lbl_qpu2_status.value = ( - "" - "No service connected" - ) - return 'No service connected' - - lbl_qpu2_status.value = ( - f"" - f"⏳ Connecting {esc(backend_name)}..." - ) + # ── Connect-QPU2: worker-safe FETCH + main-thread PAINT ────── + # Every ipywidgets / plotly FigureWidget mutation (build_mapper_ui, + # _apply_candidate_to_state, refresh_plot, mounting into + # qpu2_fig_box) MUST run on the kernel's main thread. A FigureWidget + # mutated from a background worker sends its comm messages on a + # non-kernel thread and the browser channel silently drops them — + # the map paints nothing (no error, no exception). This is why the + # one-click auto-connect produced an empty QPU-2 map while the manual + # button (which runs in the widget-callback = main thread) always + # worked. So we fetch (network only, no widgets) on the worker and + # marshal the PAINT back to the main loop via default_spawn_bg's + # on_done, matching the "marshal background work back before touching + # any widget" rule the rest of the codebase already follows. + def _connect_qpu2_fetch(backend_name): + """Worker-safe: backend handle + properties + coord resolution. + Touches NO widgets. Returns the device bundle or raises (the + caller surfaces the error).""" + from ..connection import _check_properties + from ..constants import resolve_coords + new_backend = state.active_service.backend(backend_name) + props, props_warn = _check_properties(new_backend, backend_name) + new_coords, chip_label = resolve_coords(new_backend) + return new_backend, props, props_warn, new_coords, chip_label + + def _connect_qpu2_paint(backend_name, fetched): + """Main-thread ONLY: build the full secondary UI, apply any staged + candidate, repaint, and mount the QPU-2 figure. Returns None on + success or an error STRING on failure (so the auto path can fall + back to staged).""" + new_backend, props, props_warn, new_coords, chip_label = fetched try: - from ..connection import _check_properties - from ..constants import resolve_coords - # Late import to avoid the ui ↔ ui.inter_qpu cycle that would + # Late import to avoid the ui <-> ui.inter_qpu cycle that would # otherwise trigger at module load time. from . import build_mapper_ui @@ -357,12 +360,6 @@ def _on_connect_qpu2(b): s2.active_ansatz = state.active_ansatz s2.current_colorscale = state.current_colorscale s2.active_vendor = 'IBM' - - new_backend = state.active_service.backend(backend_name) - props, props_warn = _check_properties(new_backend, backend_name) - - new_coords, chip_label = resolve_coords(new_backend) - s2.active_backend = new_backend s2.active_backend_name = backend_name s2.active_chip = chip_label @@ -372,25 +369,19 @@ def _on_connect_qpu2(b): # Build the FULL secondary UI — feature-parity with QPU 1. # build_mapper_ui internally calls _load_device_graph which - # populates s2.x_coord / qubit_ids / edges_list from props, - # so we don't need to call data_mod.generate_device_data - # ahead of time anymore. + # populates s2.x_coord / qubit_ids / edges_list from props. full_ui_2, f2, w2 = build_mapper_ui( s2, is_secondary=True, return_widgets=True) # If this connect was staged from a scan pick for THIS backend, - # paint the chosen candidate now — AFTER the build. Applying it - # before build_mapper_ui was a silent no-op: _load_device_graph - # calls state.clear_all_layouts(), wiping any pre-loaded slot, so - # the candidate never reached the first paint. Apply post-clear and - # repaint the figure so it shows on the very first view. + # paint the chosen candidate now — AFTER the build (which calls + # clear_all_layouts()). pend = _pending_handoff[0] paint_err = None if pend is not None and pend[0] == backend_name: # Narrow try (was a blanket suppress): a candidate-paint failure - # must never crash the connect, but it must NOT be hidden either - # — last night's empty-map survived precisely because it was - # swallowed. Log it and surface it on the QPU-2 status below. + # must never crash the connect, but it must NOT be hidden either. + # Log it and surface it on the QPU-2 status below. try: _apply_candidate_to_state(s2, pend[1]) from .. import plot as _plot @@ -400,16 +391,10 @@ def _on_connect_qpu2(b): _log.warning("QPU-2 candidate paint failed for %s: %s", backend_name, _pe, exc_info=True) _pending_handoff[0] = None - # Top-level shape: HBox([ui_sidebar, fig_box]). - # fig_box.children = (lbl_fig1, zoom_bar, fig). - # - # We only re-parent `sidebar2`, `zoom2_bar`, and `f2` into the - # inter-QPU layout. `lbl_fig1` (children[0] of fig_box2) and - # `fig_box2` itself are left orphan inside `full_ui_2` — they - # are never displayed (full_ui_2 has no parent), but we keep - # a reference via the `_dispose2` lambda below so the disposer - # walks them and clears any observers when inter-QPU is - # toggled off. + + # Re-parent sidebar2 / zoom2_bar / f2 into the inter-QPU layout; + # lbl_fig1 + fig_box2 stay orphan inside full_ui_2 (never displayed, + # kept only so _dispose2 can unobserve them on toggle-off). sidebar2 = full_ui_2.children[0] fig_box2 = full_ui_2.children[1] zoom2_bar = fig_box2.children[1] @@ -419,12 +404,8 @@ def _on_connect_qpu2(b): _w2[0] = w2 # kept for same-backend repaint _sidebar2[0] = sidebar2 _zoom2[0] = zoom2_bar - # Disposer: walk the full widget tree (sidebar + fig_box) and - # unobserve_all on each descendant. The tree has ~300 widgets - # so a generic walker is more robust than enumerating them. _dispose2[0] = lambda: _walk_unobserve_all(full_ui_2) - # Place QPU2 sidebar in the switchable content if _qpu2_content_box[0] is not None: _qpu2_content_box[0].children = [sidebar2] if _qpu_toggle[0] is not None: @@ -444,25 +425,12 @@ def _on_connect_qpu2(b): f"📡 {esc(backend_name)}" ) qpu2_fig_box.children = [lbl_fig2, zoom2_bar, f2] - # Match inter-QPU fig size by setting the QPU 2 sliders — - # their observers (wired by build_mapper_ui) propagate the - # value to f2.update_layout for us. Without this, the sliders - # in the QPU 2 sidebar stayed at 1700/1650 (default) while - # f2 was shrunk to 1200/1400, so the next slider drag would - # snap f2 back to the wrong size. - # QPU2's fig-size sliders come from its WidgetsRef now — no - # fragile description-string tree-walk that breaks silently if a - # slider label is renamed. These are the same slider objects - # mounted in sidebar2, so setting .value fires their observers - # (wired by build_mapper_ui) and resizes f2. + # Match inter-QPU fig size via the QPU 2 sliders (their observers + # propagate to f2.update_layout). w2.plot_w_slider.value = 1200 w2.plot_h_slider.value = 1400 - # All interpolated values come from external/IBM data (backend - # name, chip label, props warnings, calibration label) and a - # session-loaded session file could carry adversarial strings - # via state restore — escape every one of them before they hit - # the HTML widget. + # Escape every externally-sourced string before it hits the widget. lbl_qpu2_status.value = ( f"
" f"⚠ candidate paint failed: {esc(str(paint_err))}
") + return None except Exception as e: lbl_qpu2_status.value = ( f"" @@ -485,6 +454,40 @@ def _on_connect_qpu2(b): ) return str(e) + # ── Connect-QPU2 handler (manual button entry) ────────────── + def _on_connect_qpu2(b): + # Manual path: validate, then fetch + paint INLINE on the main + # thread (the widget-callback context that has always worked live). + # Returns None on success, or an error STRING on failure — so the + # one-click auto path can tell whether to fall back to staged. + backend_name = dd_backend_qpu2.value + if not backend_name: + lbl_qpu2_status.value = ( + "" + "Select a backend" + ) + return 'Select a backend' + if state.active_service is None: + lbl_qpu2_status.value = ( + "" + "No service connected" + ) + return 'No service connected' + + lbl_qpu2_status.value = ( + f"" + f"⏳ Connecting {esc(backend_name)}..." + ) + try: + fetched = _connect_qpu2_fetch(backend_name) + except Exception as e: # noqa: BLE001 - surfaced + lbl_qpu2_status.value = ( + f"" + f"❌ {esc(str(e))}" + ) + return str(e) + return _connect_qpu2_paint(backend_name, fetched) + btn_connect_qpu2.on_click(_on_connect_qpu2) # ── one-click auto-connect on a scan-candidate pick ─────── @@ -550,16 +553,22 @@ def _finish(): _connect_in_flight[0] = False btn_connect_qpu2.disabled = False - def _done(err): + # default_spawn_bg marshals on_done / on_error onto the kernel main + # loop, so _paint runs on the MAIN thread even though the fetch ran on + # a worker — the whole point of the split. The paint (build + apply + + # refresh + mount) must never touch a FigureWidget off-thread. + def _paint(fetched): # runs on the main loop (marshalled) _finish() - if err: # handler swallowed the exception, returned it + err = _connect_qpu2_paint(backend_name, fetched) + if err: # paint reported a failure string _staged_with_error(backend_name, candidate, err) - def _error(exc): # handler itself raised unexpectedly + def _error(exc): # the worker fetch itself raised _finish() _staged_with_error(backend_name, candidate, exc) - _spawn_bg(lambda: _on_connect_qpu2(None), on_done=_done, on_error=_error) + _spawn_bg(lambda: _connect_qpu2_fetch(backend_name), + on_done=_paint, on_error=_error) # Expose the label-refresh hook so ui.backend_switch can call it after a # backend switch (the switcher has no other handle on this closure). diff --git a/tests/test_async_util.py b/tests/test_async_util.py index a0a3f37..5b2dbcd 100644 --- a/tests/test_async_util.py +++ b/tests/test_async_util.py @@ -1,32 +1,41 @@ -"""Regression tests for qpu_mapper.async_util.default_spawn_bg. - -Historical bug: the on_error path inside _worker scheduled -`lambda: _safe(on_error, exc)`. Python 3 unbinds `exc` when the except -block exits — with a DEFERRED scheduler (tornado add_callback, -asyncio call_soon_threadsafe), the lambda runs later and raises -NameError, silently swallowed inside `_safe`; the user's on_error is -never invoked. Inline execution masks the bug because the lambda runs -before `exc` is cleared. The fix binds `exc` as a default argument: -`lambda err=exc: _safe(on_error, err)`. - -The tests below drive the DEFERRED path explicitly — the queued-callback -harness reproduces the failure mode observed with real tornado/asyncio -schedulers, without depending on either. +"""Regression tests for qpu_mapper.async_util. + +Two invariants pinned here: + +1. **Cross-thread marshalling reaches the MAIN loop** (the live empty-map root + cause). ``marshal_to_main`` captures the main loop + main-thread identity at + setup and, from a worker, schedules onto THAT loop — it never resolves a + loop from the calling worker (which has none) and inline-runs the paint on + the worker. Headless simulates this by running a real asyncio loop on a + dedicated thread and marshalling from another thread. + +2. **Deferred-scheduler exc binding** (historical bug): ``_worker`` schedules + ``lambda err=exc: _safe(on_error, err)`` — binding ``exc`` as a default so a + DEFERRED scheduler (which runs the lambda after the except block cleared + ``exc``) still delivers it. Driven via a deferred marshal_to_main. """ +import threading + import pytest import qpu_mapper.async_util as async_util @pytest.fixture -def _scheduler_isolation(): - """Save and restore the module-level _MAIN_LOOP_SCHEDULER around the - test so different scheduler configurations don't leak between tests.""" - saved = async_util._MAIN_LOOP_SCHEDULER +def _capture_isolation(): + """Save/restore the captured (main thread, loop, kind) triple, and RESET it + to the clean (None, None, None) so each test starts fresh — capture-once + would otherwise let one test's capture short-circuit the next.""" + saved = (async_util._MAIN_THREAD, async_util._MAIN_LOOP, + async_util._MAIN_LOOP_KIND) + async_util._MAIN_THREAD = None + async_util._MAIN_LOOP = None + async_util._MAIN_LOOP_KIND = None try: yield finally: - async_util._MAIN_LOOP_SCHEDULER = saved + (async_util._MAIN_THREAD, async_util._MAIN_LOOP, + async_util._MAIN_LOOP_KIND) = saved def _join(thread): @@ -34,120 +43,96 @@ def _join(thread): assert not thread.is_alive(), "worker thread did not finish" -def test_on_error_receives_exception_with_deferred_scheduler(_scheduler_isolation): - """Deferred scheduler regression: with the OLD code the lambda would - resolve `exc` after the except block cleared it, NameError'd inside - _safe, and `capture` would never be called.""" - queued = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append # defer — don't run - - captured = [] +# ── M3 t1: THE live-shaped regression — worker → captured main loop ───────── - def _boom(): - raise ValueError("kaboom") - - def _on_error(e): - captured.append(e) - - t = async_util.default_spawn_bg(_boom, on_error=_on_error) - _join(t) # except block has exited by now - assert queued, "on_error callback should have been queued" - for cb in queued: # drain the deferred queue - cb() - - assert len(captured) == 1, "on_error must run exactly once" - assert isinstance(captured[0], ValueError) - assert str(captured[0]) == "kaboom" - - -def test_on_done_receives_result_with_deferred_scheduler(_scheduler_isolation): - """Sanity: the success path (already-correct in the old code) - keeps working under the same deferred scheduler.""" - queued = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append - - sentinel = object() - captured = [] - - def _ok(): - return sentinel +def test_marshal_schedules_onto_captured_loop_from_worker(monkeypatch, + _capture_isolation): + """A real asyncio loop runs on a dedicated 'main' thread; marshal_to_main + invoked from ANOTHER (worker) thread must run the callback ON THE LOOP's + thread, never inline on the worker. Impossible to fail before this pass — + nothing simulated the worker-with-no-loop hand-off.""" + import asyncio + import queue - def _on_done(r): - captured.append(r) + loop = asyncio.new_event_loop() + started = threading.Event() - t = async_util.default_spawn_bg(_ok, on_done=_on_done) - _join(t) - for cb in queued: - cb() - - assert captured == [sentinel] + def _run_loop(): + asyncio.set_event_loop(loop) + loop.call_soon(started.set) + loop.run_forever() + loop_thread = threading.Thread(target=_run_loop, name='fake-main-loop', + daemon=True) + loop_thread.start() + assert started.wait(2.0), "fake main loop did not start" -def test_inline_fallback_scheduler(_scheduler_isolation): - """No-event-loop path: the scheduler runs the callback synchronously - on the worker thread. on_error must still fire.""" - async_util._MAIN_LOOP_SCHEDULER = lambda cb: cb() + # Capture, exactly as init_main_loop would on that thread. + monkeypatch.setattr(async_util, '_MAIN_THREAD', loop_thread) + monkeypatch.setattr(async_util, '_MAIN_LOOP', loop) + monkeypatch.setattr(async_util, '_MAIN_LOOP_KIND', 'asyncio') + try: + ran_on = queue.Queue() + called_from = queue.Queue() - captured = [] + def _cb(): + ran_on.put(threading.current_thread().ident) - def _boom(): - raise RuntimeError("inline-boom") + def _worker(): + called_from.put(threading.current_thread().ident) + async_util.marshal_to_main(_cb) - def _on_error(e): - captured.append(e) + w = threading.Thread(target=_worker, name='worker', daemon=True) + w.start() + _join(w) - t = async_util.default_spawn_bg(_boom, on_error=_on_error) - _join(t) + landed = ran_on.get(timeout=2.0) + assert landed == loop_thread.ident # ran on the MAIN loop + assert landed != called_from.get_nowait() # NOT on the worker + finally: + loop.call_soon_threadsafe(loop.stop) + loop_thread.join(2.0) + loop.close() - assert len(captured) == 1 - assert isinstance(captured[0], RuntimeError) - assert str(captured[0]) == "inline-boom" +# ── M3 t3: caller already on the captured main thread → inline fast path ──── -def test_callback_exception_is_contained(_scheduler_isolation): - """_safe wraps the user callback so an exception it raises does not - escape into the scheduler / worker. The worker must finish cleanly.""" - queued = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append +def test_marshal_inline_on_main_thread(monkeypatch, _capture_isolation): + # A captured loop that MUST NOT be used from the main-thread caller. + class _ExplodingLoop: + def call_soon_threadsafe(self, cb): # pragma: no cover + raise AssertionError("must not schedule when already on main") - def _ok(): - return 1 + monkeypatch.setattr(async_util, '_MAIN_THREAD', threading.current_thread()) + monkeypatch.setattr(async_util, '_MAIN_LOOP', _ExplodingLoop()) + monkeypatch.setattr(async_util, '_MAIN_LOOP_KIND', 'asyncio') - def _on_done_that_raises(_r): - raise RuntimeError("callback failure — must be contained by _safe") + ran = [] + async_util.marshal_to_main(lambda: ran.append(threading.current_thread().ident)) + assert ran == [threading.current_thread().ident] # inline, on this thread - t = async_util.default_spawn_bg(_ok, on_done=_on_done_that_raises) - _join(t) # worker thread finished normally - # Draining the callback must not propagate the exception either — _safe - # logs it and returns. - for cb in queued: - cb() +# ── M3 t2: headless (no captured loop) → inline, zero warnings ────────────── -# ── Zero-warnings guard: the scheduler resolver must never trip tornado's -# "There is no current event loop" DeprecationWarning in a headless -# context (no running loop) — the regression that put 1 warning back in -# the suite after the calibration-epoch merge. ─────────────────────────── +def test_init_main_loop_headless_no_loop_no_warning(monkeypatch, + _capture_isolation): + import warnings -def _install_warning_tornado(monkeypatch): - """Inject a fake tornado.ioloop whose IOLoop.current() emits the exact - deprecation, so we can assert our resolver does NOT reach it with no - running loop — independent of whether real tornado is installed.""" + # Fake tornado whose IOLoop.current() would emit the Py>=3.10 deprecation + # with no running loop — init_main_loop must NOT let it escape. import sys import types - import warnings as _w class _IOLoop: @staticmethod - def current(): - # Faithful to real tornado: the deprecation fires ONLY when there - # is no running loop (IOLoop.current() → asyncio.get_event_loop()). + def current(instance=True): import asyncio as _a + import warnings as _w try: _a.get_running_loop() except RuntimeError: _w.warn("There is no current event loop", DeprecationWarning) - return types.SimpleNamespace(add_callback=lambda cb: cb()) + return None # no current IOLoop headless tornado = types.ModuleType("tornado") ioloop = types.ModuleType("tornado.ioloop") @@ -156,34 +141,329 @@ def current(): monkeypatch.setitem(sys.modules, "tornado", tornado) monkeypatch.setitem(sys.modules, "tornado.ioloop", ioloop) - -def test_resolver_no_deprecation_without_running_loop(monkeypatch): - import warnings import asyncio - _install_warning_tornado(monkeypatch) - # Guarantee no current/running loop in this thread. - monkeypatch.setattr(asyncio, "get_running_loop", - lambda: (_ for _ in ()).throw(RuntimeError("no loop"))) - with warnings.catch_warnings(record=True) as rec: - warnings.simplefilter("always") - sched = async_util._resolve_main_loop_scheduler() - assert [str(x.message) for x in rec] == [] # tornado never touched + prev = _policy_set_loop() + asyncio.set_event_loop(None) # no set loop → tier-2 skips + try: + with warnings.catch_warnings(record=True) as rec: + warnings.simplefilter("always") + async_util.init_main_loop() + finally: + asyncio.set_event_loop(prev) + + assert [str(x.message) for x in rec] == [] # deprecation never escapes + assert async_util._MAIN_LOOP is None # no loop captured headless + + # And marshal on this (captured main) thread runs inline. ran = [] - sched(lambda: ran.append(1)) # inline fallback runs cb + async_util.marshal_to_main(lambda: ran.append(1)) assert ran == [1] -def test_resolver_uses_loop_scheduler_when_running(monkeypatch): - """With a running loop the tornado path IS taken (real tornado does not - warn in that case). Proves the fix didn't disable marshaling.""" +def test_init_main_loop_captures_running_loop(_capture_isolation): + """When a loop IS running on the calling thread, init captures it as the + asyncio main loop (the live cell-execution case).""" import asyncio - _install_warning_tornado(monkeypatch) async def _main(): - return async_util._resolve_main_loop_scheduler() + async_util.init_main_loop() + return async_util._MAIN_LOOP, async_util._MAIN_LOOP_KIND + + loop, kind = asyncio.run(_main()) + assert loop is not None and kind == 'asyncio' + + +# ── N3: capture sources — the live ipykernel case + tornado last resort ───── + +def _policy_set_loop(): + import asyncio + policy = asyncio.get_event_loop_policy() + return getattr(getattr(policy, '_local', None), '_loop', None) - sched = asyncio.run(_main()) - # Not the inline fallback: the tornado IOLoop scheduler was selected. - delivered = [] - sched(lambda: delivered.append(1)) - assert delivered == [1] + +def test_capture_via_set_loop_when_not_in_coroutine(monkeypatch, + _capture_isolation): + """THE live fix: get_running_loop() fails on the main thread (capture runs + in a widget callback — launch_mapper on Connect — not a coroutine), but the + thread OWNS a running loop set via set_event_loop. Capture must pick it up + from the policy thread-local (previously it gave up → None → worker inline).""" + import asyncio + loop = asyncio.new_event_loop() + started = threading.Event() + + def _run(): + loop.call_soon_threadsafe(started.set) + loop.run_forever() + t = threading.Thread(target=_run, name='kernel', daemon=True) + t.start() + assert started.wait(2.0) + + prev = _policy_set_loop() + asyncio.set_event_loop(loop) # policy._local._loop = loop + monkeypatch.setattr(asyncio, 'get_running_loop', + lambda: (_ for _ in ()).throw(RuntimeError('widget callback'))) + try: + async_util.init_main_loop() + assert async_util._MAIN_LOOP is loop # captured the RUNNING loop + assert async_util._MAIN_LOOP_KIND == 'asyncio' # via the set-loop tier + finally: + asyncio.set_event_loop(prev) # restore prior loop + loop.call_soon_threadsafe(loop.stop) + t.join(2.0) + loop.close() + + +def test_capture_via_tornado_last_resort(monkeypatch, _capture_isolation): + """No running loop, no running SET loop, but a current tornado IOLoop + exists → capture it (kind='tornado').""" + import asyncio + import sys + import types + + monkeypatch.setattr(asyncio, 'get_running_loop', + lambda: (_ for _ in ()).throw(RuntimeError('no loop'))) + prev = _policy_set_loop() + asyncio.set_event_loop(None) # no set loop → tier-2 skips + + sentinel = object() + + class _IOLoop: + @staticmethod + def current(instance=True): + return sentinel + tornado = types.ModuleType('tornado') + ioloop = types.ModuleType('tornado.ioloop') + ioloop.IOLoop = _IOLoop + tornado.ioloop = ioloop + monkeypatch.setitem(sys.modules, 'tornado', tornado) + monkeypatch.setitem(sys.modules, 'tornado.ioloop', ioloop) + try: + async_util.init_main_loop() + assert async_util._MAIN_LOOP is sentinel + assert async_util._MAIN_LOOP_KIND == 'tornado' + finally: + asyncio.set_event_loop(prev) + + +# ── N4: WIRING pin — the real UI build captures, then a worker schedules ──── + +def _build_ui(monkeypatch): + import numpy as np + + def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) + from qpu_mapper.state import SessionState + from qpu_mapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = 'stub' + state.active_chip = 'chip' + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = 'lucj' + state.active_vendor = 'IBM' + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ['_seed_'] + return MapperUIBuilder(state).build() + + +def test_build_invokes_capture(monkeypatch, _capture_isolation): + # Reset to a sentinel to PROVE build() re-runs init_main_loop(). + monkeypatch.setattr(async_util, '_MAIN_THREAD', None) + monkeypatch.setattr(async_util, '_MAIN_LOOP', None) + _build_ui(monkeypatch) + assert async_util._MAIN_THREAD is threading.current_thread() # wiring ran + + +def test_build_captures_loop_then_worker_schedules(monkeypatch, _capture_isolation): + """Integration-shaped: build the real UI from within a running loop (so the + build's init_main_loop captures it), then marshal from a WORKER and assert + the callback lands on the captured-loop thread — the 'scheduled to captured + loop' branch, pinned end-to-end through the wiring.""" + import asyncio + import queue + + async def _main(): + _build_ui(monkeypatch) # build() → init_main_loop() + assert async_util._MAIN_LOOP is asyncio.get_running_loop() + + ran_on = queue.Queue() + + def _cb(): + ran_on.put(threading.current_thread().ident) + + w = threading.Thread(target=lambda: async_util.marshal_to_main(_cb), + daemon=True) + w.start() + w.join(2.0) + for _ in range(200): # let the loop run the cb + if not ran_on.empty(): + break + await asyncio.sleep(0.005) + assert ran_on.get_nowait() == threading.get_ident() # ran on main loop + + asyncio.run(_main()) + + +# ── P3: capture-once + main-only — a worker must NEVER overwrite the capture ─ + +def test_worker_capture_does_not_overwrite_good_capture(monkeypatch, + _capture_isolation): + """THE live bug as a fixture: a good main-thread capture must survive a + later init_main_loop() reached FROM A WORKER (the secondary build + re-entering build() off-thread). Previously that wrote thread=, + loop=None over the real capture → marshal fell back to inline-on-worker.""" + sentinel_loop = object() + main_t = threading.current_thread() + monkeypatch.setattr(async_util, '_MAIN_THREAD', main_t) + monkeypatch.setattr(async_util, '_MAIN_LOOP', sentinel_loop) + monkeypatch.setattr(async_util, '_MAIN_LOOP_KIND', 'asyncio') + + seen = [] + + def _worker(): + async_util.init_main_loop() # reached from a worker + seen.append(threading.current_thread()) + w = threading.Thread(target=_worker, name='Thread-8 (_worker)', daemon=True) + w.start() + _join(w) + + assert async_util._MAIN_LOOP is sentinel_loop # capture preserved, not None + assert async_util._MAIN_THREAD is main_t # main-thread identity kept + + +def test_worker_capture_skipped_when_none_captured(monkeypatch, _capture_isolation): + """With NO capture yet, a worker call must SKIP — never write None (or the + worker thread) as the 'main' capture.""" + monkeypatch.setattr(async_util, '_MAIN_THREAD', None) + monkeypatch.setattr(async_util, '_MAIN_LOOP', None) + monkeypatch.setattr(async_util, '_MAIN_LOOP_KIND', None) + + def _worker(): + async_util.init_main_loop() + w = threading.Thread(target=_worker, name='worker', daemon=True) + w.start() + _join(w) + + assert async_util._MAIN_LOOP is None + assert async_util._MAIN_THREAD is None # worker never became 'main' + + +def test_secondary_build_on_worker_still_marshals_to_main(monkeypatch, + _capture_isolation): + """End-to-end: after a GOOD main capture (as run() produces), a worker that + re-enters init_main_loop (skipped) and then marshals the paint continuation + still lands it ON THE CAPTURED LOOP's thread — not inline on the worker.""" + import asyncio + import queue + + loop = asyncio.new_event_loop() + started = threading.Event() + + def _run(): + loop.call_soon_threadsafe(started.set) + loop.run_forever() + main_like = threading.Thread(target=_run, name='KernelMainLoop', daemon=True) + main_like.start() + assert started.wait(2.0) + + # Good capture, exactly as run() on the main thread would produce. + monkeypatch.setattr(async_util, '_MAIN_THREAD', main_like) + monkeypatch.setattr(async_util, '_MAIN_LOOP', loop) + monkeypatch.setattr(async_util, '_MAIN_LOOP_KIND', 'asyncio') + try: + ran_on = queue.Queue() + + def _secondary_worker(): + async_util.init_main_loop() # re-entry on worker → SKIP + assert async_util._MAIN_LOOP is loop # capture still good + async_util.marshal_to_main( + lambda: ran_on.put(threading.current_thread().ident)) + w = threading.Thread(target=_secondary_worker, name='Thread-8 (_worker)', + daemon=True) + w.start() + _join(w) + + assert ran_on.get(timeout=2.0) == main_like.ident # paint on captured loop + finally: + loop.call_soon_threadsafe(loop.stop) + main_like.join(2.0) + loop.close() + + +# ── t4: default_spawn_bg deferred-scheduler behaviour (exc binding etc.) ──── + +def test_on_error_receives_exception_with_deferred_scheduler(monkeypatch, + _capture_isolation): + """Deferred marshal: with the OLD code the lambda resolved `exc` after the + except block cleared it → NameError swallowed in _safe → on_error never + ran. The `err=exc` default binding fixes it.""" + queued = [] + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) + + captured = [] + + def _boom(): + raise ValueError("kaboom") + + t = async_util.default_spawn_bg(_boom, on_error=lambda e: captured.append(e)) + _join(t) # except block has exited + assert queued, "on_error callback should have been queued" + for cb in queued: + cb() + + assert len(captured) == 1 and isinstance(captured[0], ValueError) + assert str(captured[0]) == "kaboom" + + +def test_on_done_receives_result_with_deferred_scheduler(monkeypatch, + _capture_isolation): + queued = [] + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) + sentinel = object() + captured = [] + + t = async_util.default_spawn_bg(lambda: sentinel, + on_done=lambda r: captured.append(r)) + _join(t) + for cb in queued: + cb() + assert captured == [sentinel] + + +def test_inline_marshal_delivers_on_error(monkeypatch, _capture_isolation): + """Inline marshal (headless-style) runs the callback synchronously; on_error + still fires with the exception.""" + monkeypatch.setattr(async_util, 'marshal_to_main', lambda cb: cb()) + captured = [] + + t = async_util.default_spawn_bg( + lambda: (_ for _ in ()).throw(RuntimeError("inline-boom")), + on_error=lambda e: captured.append(e)) + _join(t) + assert len(captured) == 1 and isinstance(captured[0], RuntimeError) + assert str(captured[0]) == "inline-boom" + + +def test_callback_exception_is_contained(monkeypatch, _capture_isolation): + """_safe wraps the user callback so its exception never escapes the worker + or the scheduler.""" + queued = [] + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) + + def _raises(_r): + raise RuntimeError("callback failure — must be contained by _safe") + + t = async_util.default_spawn_bg(lambda: 1, on_done=_raises) + _join(t) + for cb in queued: # draining must not propagate + cb() diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py index 60aa0e5..905dffd 100644 --- a/tests/test_inter_qpu_handoff.py +++ b/tests/test_inter_qpu_handoff.py @@ -2,6 +2,7 @@ AND auto-connects QPU 2, with graceful fallback, race guards, and a same-backend shortcut. Headless: the network-touching connect deps are stubbed. """ +import threading from types import SimpleNamespace import pytest @@ -155,7 +156,8 @@ def _manual_spawn(fn, on_done=None, on_error=None): assert len(queued) == 1 # only ONE connect launched assert calls == [] # nothing has run yet - # Draining the single queued connect runs the path exactly once. + # Draining the single queued connect (fetch on the "worker", paint via the + # marshalled on_done) runs the path exactly once. fn, done, _ = queued[0] done(fn()) assert calls == ['ibm_k'] @@ -253,10 +255,11 @@ def _assert_base_map(fig, n): assert isinstance(col, (list, tuple)) and len(col) == n, "node colours missing" -def _primary_with_stubs(monkeypatch): +def _primary_with_stubs(monkeypatch, spawn=_sync_spawn): """A built primary MapperUIBuilder with device/network deps stubbed so the REAL secondary build_mapper_ui runs on connect. Returns (b, capture) where - capture records the connected s2/fig via a build wrapper.""" + capture records the connected s2/fig via a build wrapper. `spawn` is wired + BEFORE build so setup_inter_qpu captures it.""" import numpy as np def _fake_device(state, vendor, chip, date, prefetched_props=None): @@ -272,7 +275,7 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): monkeypatch.setattr("qpu_mapper.constants.resolve_coords", lambda b: ([(i, 0) for i in range(8)], 'chip')) import qpu_mapper.async_util as au - monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'default_spawn_bg', spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) from qpu_mapper.state import SessionState @@ -359,3 +362,43 @@ def test_batch_handoff_keeps_base_map_real_build(monkeypatch): # Both circuits landed on QPU-2 state. assert cap['s2'].layouts_data[0]['ancilla'] == ['2'] assert cap['s2'].layouts_data[1]['ancilla'] == ['5'] + + +# ── L4: paint runs ON THE MAIN THREAD (never a worker) ────────────────────── +# plotly FigureWidget mutations from a worker thread are silently dropped by +# the comm channel → empty map live. The scan handoff hook fires on the main +# thread, so the auto-connect does the build + apply + refresh SYNCHRONOUSLY +# there — like the manual Connect button that renders correctly live. + +def test_paint_runs_on_main_thread(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) + import qpu_mapper.ui as ui_pkg + inner = ui_pkg.build_mapper_ui + build_threads = [] + + def _wrap(s2, is_secondary=False, return_widgets=False): + build_threads.append(threading.current_thread()) + return inner(s2, is_secondary=is_secondary, return_widgets=return_widgets) + monkeypatch.setattr(ui_pkg, 'build_mapper_ui', _wrap) + + b._inter_qpu_handoff[0]('ibm_k', {'alpha': [0], 'beta': [1], 'ancillas': [2]}) + + # The QPU-2 figure was built on the MAIN thread (not a worker) and painted. + assert build_threads == [threading.main_thread()] + _assert_base_map(cap['fig'], 8) + + +def test_continuation_failure_falls_back_to_staged(monkeypatch): + b, cap = _primary_with_stubs(monkeypatch) + import qpu_mapper.ui as ui_pkg + + def _boom_build(*a, **k): + raise RuntimeError('build boom') + monkeypatch.setattr(ui_pkg, 'build_mapper_ui', _boom_build) + + b._inter_qpu_handoff[0]('ibm_k', {'alpha': [0], 'beta': [1], 'ancillas': [2]}) + + status = b.lbl_qpu2_status.value + assert 'staged' in status # fell back to staged + assert 'build boom' in status # error surfaced, not hidden + assert b.btn_connect_qpu2.disabled is False # trigger re-enabled diff --git a/tests/test_inter_qpu_live_model.py b/tests/test_inter_qpu_live_model.py new file mode 100644 index 0000000..70cbd8a --- /dev/null +++ b/tests/test_inter_qpu_live_model.py @@ -0,0 +1,146 @@ +"""LIVE-model regression for the QPU-2 empty-map bug. + +The one-click auto-connect used to hand the ENTIRE connect (build_mapper_ui + +apply candidate + refresh_plot + mounting the FigureWidget) to a background +worker. A plotly FigureWidget mutated off the kernel main thread sends its comm +messages on a non-kernel thread and the browser silently drops them: the QPU-2 +map paints nothing, with no error and no exception — invisible to a suite whose +`spawn_bg` runs inline. + +This test reproduces the LIVE threading model deterministically: the injected +`spawn_bg` runs the worker fn on a real background thread and marshals the +completion callback back to the MAIN (test) thread, exactly like +`default_spawn_bg` does against a running kernel loop. It then records which +thread each FigureWidget-touching operation (`build_mapper_ui`, `refresh_plot`) +executes on and asserts it is the main thread. + +Pre-fix: build + refresh run on the worker -> assertion fails (bug present). +Post-fix: only the network fetch runs on the worker; build + refresh are +marshalled to main -> assertion passes. +""" +import queue +import threading +from types import SimpleNamespace + +import pytest + + +class _RecLabel: + def __init__(self): + self.history = [] + + @property + def value(self): + return self.history[-1] if self.history else '' + + @value.setter + def value(self, v): + self.history.append(v) + + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._handlers = [] + + def observe(self, fn, names=None): + self._handlers.append(fn) + + def on_click(self, fn): + self._click = fn + + +def _ctx(*, spawn): + def _backend(n): + return SimpleNamespace(name=n) + + state = SimpleNamespace( + available_backends=['ibm_k'], active_backend_name='ibm_here', + active_service=SimpleNamespace(backend=_backend), + active_ansatz='lucj', current_colorscale='Viridis') + ctx = SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_RecLabel(), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), + full_ui=_Stub(children=[]), + handoff_cell=[None], + spawn_bg=spawn, + ) + return ctx + + +_CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} + + +def test_auto_connect_paints_on_main_thread(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + + main_thread = threading.current_thread() + build_threads = [] + refresh_threads = [] + + def _fake_build(s2, is_secondary=False, return_widgets=False): + build_threads.append(threading.current_thread()) + s2.qubit_ids = ['0', '1', '2'] + s2.edges_list = [(0, 1), (1, 2)] + fig = SimpleNamespace() + fig_box2 = SimpleNamespace(children=[SimpleNamespace(), + SimpleNamespace(), fig]) + full_ui = SimpleNamespace(children=[SimpleNamespace(), fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'chip_label')) + monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("qpu_mapper.plot.refresh_plot", + lambda fig, st, w: refresh_threads.append( + threading.current_thread())) + + # A spawn that mimics a LIVE kernel: worker fn on a background thread, + # completion callback marshalled back to the main thread via a queue the + # test drains. (default_spawn_bg does the same against a running loop.) + marshal_q = queue.Queue() + + def live_spawn(fn, on_done=None, on_error=None): + def _worker(): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + marshal_q.put((on_error, e)) + return + if on_done: + marshal_q.put((on_done, r)) + t = threading.Thread(target=_worker) + t.start() + t.join() + return t + + ctx = _ctx(spawn=live_spawn) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) # scan pick -> auto-connect + # Drain the marshalled completion(s) on the MAIN thread. + while not marshal_q.empty(): + cb, arg = marshal_q.get() + cb(arg) + + assert build_threads, "build_mapper_ui never ran" + assert refresh_threads, "refresh_plot never ran" + assert all(t is main_thread for t in build_threads), ( + f"build_mapper_ui ran off the main thread: {build_threads}") + assert all(t is main_thread for t in refresh_threads), ( + f"refresh_plot ran off the main thread: {refresh_threads}") + # And the connect still succeeded end to end. + assert 'Connected' in ctx.lbl_qpu2_status.value From c95c2a45da203d722a62ae3614f68c890e109b0d Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Wed, 15 Jul 2026 21:43:29 -0400 Subject: [PATCH 24/66] Fix inter-QPU handoff: QPU-2 map now paints on auto-connect --- qpu_mapper/ui/inter_qpu.py | 35 +++++++ tests/test_inter_qpu_resync.py | 161 +++++++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 tests/test_inter_qpu_resync.py diff --git a/qpu_mapper/ui/inter_qpu.py b/qpu_mapper/ui/inter_qpu.py index e26df9d..3624eeb 100644 --- a/qpu_mapper/ui/inter_qpu.py +++ b/qpu_mapper/ui/inter_qpu.py @@ -43,6 +43,36 @@ _log = logging.getLogger(__name__) +def _resync_widget_state(fig): + """Force ``fig``'s full state into its synced widget traits before the + figure is first mounted via ``Box.children``. + + plotly 6.x FigureWidget snapshots ``_widget_data``/``_widget_layout`` only + at construction (empty) and in ``_repr_mimebundle_`` (cell display). A + figure mounted as a child widget never passes through either, so the + frontend model renders whatever subset of the incremental + ``_py2js_addTraces``/``restyle``/``relayout`` messages it managed to apply. + In the live one-click handoff that subset lost the qubit node trace → + "edges but no nodes" empty map (the frontend model's ``do_data`` handler is + a no-op, so this resync repaints nothing once a view exists — it MUST run + before the mount). Re-snapshotting here makes the trait state + authoritative, matching what plotly itself does at display time. + + Touches plotly-private attributes, so it is a guarded no-op if they ever + move; failure must never break the connect (worst case: the pre-fix + behavior). Returns True if the resync was applied. + """ + try: + from copy import deepcopy + fig._widget_data = deepcopy(fig._data) + fig._widget_layout = deepcopy(fig._layout_obj._props) + return True + except Exception: # noqa: BLE001 - logged, never fatal + _log.warning("widget-state resync skipped (plotly internals moved?)", + exc_info=True) + return False + + def setup_inter_qpu(ctx): """Wire the inter-QPU toggle + connect-QPU2 callbacks. @@ -424,6 +454,11 @@ def _connect_qpu2_paint(backend_name, fetched): f"text-align:center;margin-bottom:2px;'>" f"📡 {esc(backend_name)}" ) + # Resync the full figure state into the synced widget traits so + # the view created by the mount below renders the complete figure + # regardless of which incremental messages the frontend applied. + # Must precede the children assignment (see _resync_widget_state). + _resync_widget_state(f2) qpu2_fig_box.children = [lbl_fig2, zoom2_bar, f2] # Match inter-QPU fig size via the QPU 2 sliders (their observers # propagate to f2.update_layout). diff --git a/tests/test_inter_qpu_resync.py b/tests/test_inter_qpu_resync.py new file mode 100644 index 0000000..dff9eb5 --- /dev/null +++ b/tests/test_inter_qpu_resync.py @@ -0,0 +1,161 @@ +"""QPU-2 empty-map fix: resync the FigureWidget state into its synced traits +BEFORE the figure is first mounted via Box.children. + +plotly 6.x snapshots _widget_data/_widget_layout only at construction and in +_repr_mimebundle_ (cell display); a figure mounted as a child widget passes +through neither, so the frontend model renders only the incremental messages it +managed to apply. In the live one-click handoff that lost the qubit node trace +→ "edges but no nodes". _resync_widget_state re-snapshots the trait state before +the mount so the view created by the mount renders the complete figure. +""" +from types import SimpleNamespace + +import pytest + + +# ── unit: the helper snapshots data + layout onto the synced traits ───────── + +def test_resync_helper_snapshots_state(): + pytest.importorskip('plotly') + import plotly.graph_objects as go + from qpu_mapper.ui.inter_qpu import _resync_widget_state + + fig = go.FigureWidget() + fig.add_trace(go.Scatter(x=[1.0, 2.0, 3.0], y=[0.0, 0.0, 0.0], + text=['a', 'b', 'c'], mode='markers+text')) + fig.add_shape(type='line', x0=0, y0=0, x1=1, y1=1) + + assert _resync_widget_state(fig) is True + # The node trace data landed in the synced _widget_data trait… + assert list(fig._widget_data[0]['x']) == [1.0, 2.0, 3.0] + # …and the layout shapes landed in the synced _widget_layout trait. + assert fig._widget_layout.get('shapes') + + +def test_resync_helper_never_raises(): + from qpu_mapper.ui.inter_qpu import _resync_widget_state + # Non-figure object → the plotly-private attribute access fails; the guard + # swallows it and returns False (never fatal to the connect). + assert _resync_widget_state(object()) is False + + +# ── integration: the auto-connect resyncs BEFORE mounting the figure ──────── + +class _RecLabel: + def __init__(self): + self.history = [] + + @property + def value(self): + return self.history[-1] if self.history else '' + + @value.setter + def value(self, v): + self.history.append(v) + + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._handlers = [] + + def observe(self, fn, names=None): + self._handlers.append(fn) + + def on_click(self, fn): + self._click = fn + + +class _RecChildrenBox: + """A container whose ``children`` setter records ('mount', tuple) events.""" + def __init__(self, events): + self._events = events + self._ch = [] + + @property + def children(self): + return self._ch + + @children.setter + def children(self, v): + self._ch = v + self._events.append(('mount', tuple(v))) + + +def _sync_spawn(fn, on_done=None, on_error=None): + try: + r = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return + if on_done: + on_done(r) + + +_CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} + + +def test_paint_resyncs_before_mount(monkeypatch): + from qpu_mapper.ui.inter_qpu import setup_inter_qpu + + events = [] + + def _rec_resync(fig): + events.append(('resync', fig)) + return True + monkeypatch.setattr("qpu_mapper.ui.inter_qpu._resync_widget_state", + _rec_resync) + + def _fake_build(s2, is_secondary=False, return_widgets=False): + s2.qubit_ids = ['0', '1', '2'] + s2.edges_list = [(0, 1), (1, 2)] + fig = SimpleNamespace(name='qpu2-fig') + fig_box2 = SimpleNamespace(children=[SimpleNamespace(), + SimpleNamespace(), fig]) + full_ui = SimpleNamespace(children=[SimpleNamespace(), fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'chip')) + monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("qpu_mapper.plot.refresh_plot", lambda fig, st, w: None) + + state = SimpleNamespace( + available_backends=['ibm_k'], active_backend_name='ibm_here', + active_service=SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)), + active_ansatz='lucj', current_colorscale='Viridis') + ctx = SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_RecLabel(), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), + qpu2_fig_box=_RecChildrenBox(events), + full_ui=_Stub(children=[]), + handoff_cell=[None], + spawn_bg=_sync_spawn, + ) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_k', _CAND) # scan pick → auto-connect + + resyncs = [e for e in events if e[0] == 'resync'] + assert len(resyncs) == 1 # exactly one resync + resync_fig = resyncs[0][1] + # The mount that carries the figure (the toggle's empty init, if any, is + # ignored) must contain the SAME figure object that was resynced… + fig_mounts = [i for i, e in enumerate(events) + if e[0] == 'mount' and resync_fig in e[1]] + assert len(fig_mounts) == 1 + # …and the resync must be ordered BEFORE that mount. + assert events.index(resyncs[0]) < fig_mounts[0] From 551ba2762da5aeeb60a815d3c58926458bdaac5e Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Wed, 15 Jul 2026 21:52:59 -0400 Subject: [PATCH 25/66] Comments clean-up --- qpu_mapper/export/autodetect.py | 4 ++-- qpu_mapper/stability.py | 6 +++--- tests/test_stability.py | 2 +- tests/test_time_status.py | 6 +----- 4 files changed, 7 insertions(+), 11 deletions(-) diff --git a/qpu_mapper/export/autodetect.py b/qpu_mapper/export/autodetect.py index 015fe06..5718d82 100644 --- a/qpu_mapper/export/autodetect.py +++ b/qpu_mapper/export/autodetect.py @@ -3,8 +3,8 @@ partitions when possible, and parse the textual `parse_auto_text` payload (used by the Auto-map UI tab). -NOTE: when the LUCJ VF2 recovery functions land (separate feature spec), -they belong here too — same domain, shared graph-component plumbing. +NOTE: when the LUCJ VF2 recovery functions land, they belong here too — +same domain, shared graph-component plumbing. """ import contextlib import logging diff --git a/qpu_mapper/stability.py b/qpu_mapper/stability.py index 704999a..357a555 100644 --- a/qpu_mapper/stability.py +++ b/qpu_mapper/stability.py @@ -21,7 +21,7 @@ import numpy as np -# "Bad" sample thresholds vs. series median (audit UX spec): +# "Bad" sample thresholds vs. series median: # errors > 2× median → bad # times < 0.5× median → bad # A series is unstable when ≥ `_min_bad_days(total)` samples are bad. @@ -31,7 +31,7 @@ def _min_bad_days(total: int) -> int: - """Bad-days threshold for "unstable". Spec: 2 of ≤14, 3 of >14 — + """Bad-days threshold for "unstable": 2 of ≤14, 3 of >14 — avoids flagging a single day-of-the-week dip on 7-day windows while still catching short bursts on 14-day ones. """ @@ -137,7 +137,7 @@ def analyze_property_stability(values, kind: str) -> dict: # ── Layout report ──────────────────────────────────────────────────────── -# Hard-coded for v1 per spec: qubit→readout_error, gate→cz_error. Module +# Hard-coded for v1: qubit→readout_error, gate→cz_error. Module # constants so a future per-property matrix (Robust LQS) won't need to # tear through call sites. _QUBIT_PROP_KEY = 'readout_error' diff --git a/tests/test_stability.py b/tests/test_stability.py index e022c29..4097e92 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -1,6 +1,6 @@ """Unit tests for qpu_mapper.stability.analyze_property_stability. -Covers the seven cases called out in the spec: +Covers seven cases: 1. Error kind, happy path (stable series) 2. Time kind, happy path (stable series) 3. NaN handling (NaN samples are skipped) diff --git a/tests/test_time_status.py b/tests/test_time_status.py index 9890012..09cb5b8 100644 --- a/tests/test_time_status.py +++ b/tests/test_time_status.py @@ -13,10 +13,6 @@ pointing to the LAST available entry (documented "show the latest we have" semantic); * happy-path output must be byte-identical to before the guards. - -The SPEC referred to the reader as ``describe_current_time``; the actual -function name in the code is ``describe_current_view`` (same signature, -same branches). """ from types import SimpleNamespace @@ -69,7 +65,7 @@ def _ref_state(mode, *, time_mode, cal_history_dates=(), range_index=0, # ═══════════════════════════════════════════════════════════════════════ -# Stale-index regressions — the SPEC's four crash scenarios +# Stale-index regressions — the four crash scenarios # ═══════════════════════════════════════════════════════════════════════ def test_describe_current_view_range_stale_index_does_not_raise(): From 4b11cecd8455d1f598cb8c1f0f1c23ab632faf99 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 20 Jul 2026 15:48:52 -0400 Subject: [PATCH 26/66] UI fixes: Error-tab header refresh on backend switch, tab titles, I/O reorder, PNG colorbars --- qpu_mapper/ui/backend_switch.py | 30 +++++ qpu_mapper/ui/builder.py | 71 ++++++------ qpu_mapper/ui/png_export.py | 47 ++++++++ qpu_mapper/ui/time_panel.py | 9 +- requirements.txt | 27 +++++ tests/test_auto_subpanels.py | 4 +- tests/test_error_tab_backend_switch.py | 147 +++++++++++++++++++++++++ tests/test_import_export_ui.py | 10 +- tests/test_png_colorbars.py | 123 +++++++++++++++++++++ tests/test_subpanel_persistence.py | 18 ++- 10 files changed, 437 insertions(+), 49 deletions(-) create mode 100644 requirements.txt create mode 100644 tests/test_error_tab_backend_switch.py create mode 100644 tests/test_png_colorbars.py diff --git a/qpu_mapper/ui/backend_switch.py b/qpu_mapper/ui/backend_switch.py index b9f1682..9506dc6 100644 --- a/qpu_mapper/ui/backend_switch.py +++ b/qpu_mapper/ui/backend_switch.py @@ -114,6 +114,12 @@ def setup_backend_switch(ctx): out — Output widget (used for traceback dump when the switch fails) + Optional ctx fields (absent in minimal callers/tests → treated as no-op): + refresh_qpu1_label — [None] cell holding ui.inter_qpu's QPU-1 label + refresh hook + refresh_time_panel — callable that re-renders the Time/Delta panel + (Error-tab header) for the switched backend + Returns the on_backend_switch handler in case the caller needs it for testing or programmatic invocation. """ @@ -147,6 +153,21 @@ def _refresh_qpu1_label(): _log.debug("Refreshing QPU-1 toggle label after backend switch") hook() + # Optional: best-effort callable to re-render the Time/Delta panel so the + # Error-tab header reflects the switched backend. Absent in callers/tests + # that don't build the panel — treat as "no hook". + refresh_time_panel = getattr(ctx, 'refresh_time_panel', None) + + def _refresh_time_panel(): + """Re-render the Time/Delta panel (Error-tab header + sub-panels) after + a switch. A hook failure must NEVER break or roll back a switch.""" + if refresh_time_panel is None: + return + try: + refresh_time_panel() + except Exception: + _log.exception("Time-panel refresh after backend switch failed") + def _on_backend_switch(change): new_name = change['new'] if (not new_name @@ -287,6 +308,11 @@ def _on_backend_switch(change): f"border:1px solid #abebc6;margin:3px 0;'>" f"{msg}" ) + # State + device graph now reflect the new backend (the + # time-state reset ran inside load_device_graph); re-render the + # Time/Delta panel so the Error-tab header stops showing the old + # backend. + _refresh_time_panel() except Exception as e: _log.exception("Backend switch failed") # Roll state back to the previous backend (the graph for the new @@ -302,6 +328,10 @@ def _on_backend_switch(change): # State rolled back to the old backend name — refresh the # switcher label to match, undoing any success-path relabel. _refresh_qpu1_label() + # …and re-render the Time/Delta panel against the rolled-back + # state (correct-by-construction: it renders whatever state + # says, which is now the old backend again). + _refresh_time_panel() hint = _classify_switch_error(e, new_name) lbl_switch_status.value = ( f"
✏️ Paste qubit list
"), + self.txt_auto, self.btn_auto, + HTML("
"), HTML("
📂 Load layout file
"), self.btn_unified_upload, - HTML("
"), - HTML("
✏️ Or paste qubit list
"), - self.txt_auto, self.btn_auto, HTML("
"), HTML("
💾 Load Session
"), self.btn_load_session, @@ -1786,9 +1790,9 @@ def _build_auto_lucj_view(self): prev_tabs = getattr(self, '_auto_lucj_tabs', None) name = esc(str(getattr(self.state, 'active_backend_name', '') or 'current backend')) - # Subpanel 1 — "Single Circuit": everything except the Multi-Circuit - # section (single-circuit controls + the local results + the scan - # block). Mirrors the Error tab's Tab-based subpanel switcher. + # Subpanel 1 — "Single" (single-circuit): everything except the + # Multi-Circuit section (single-circuit controls + the local results + + # the scan block). Mirrors the Error tab's Tab-based subpanel switcher. single_panel = VBox([ self.lucj_norb_slider, self.lucj_ancilla_dd, @@ -1824,8 +1828,8 @@ def _build_auto_lucj_view(self): self.lbl_scan_progress, self.scan_results_box, ], layout=Layout(padding='6px')) - # Subpanel 2 — "Multi-Circuit": revealed only while Multi-Programming - # (intra-QPU) is enabled; the enable checkbox rebuilds this view. + # Subpanel 2 — "Multi" (multi-circuit): revealed only while Multi- + # Programming (intra-QPU) is enabled; the enable checkbox rebuilds it. multi_panel = VBox([ self.lucj_multi_norbs, self.lucj_multi_ancillas, @@ -1843,11 +1847,11 @@ def _build_auto_lucj_view(self): self._auto_multi_panel = multi_panel if self.intra_qpu_mode.value: tabs = Tab(children=[single_panel, multi_panel]) - tabs.set_title(0, '🔬 Single Circuit') - tabs.set_title(1, '🔗 Multi-Circuit') + tabs.set_title(0, '🔬 Single') + tabs.set_title(1, '🔗 Multi') else: tabs = Tab(children=[single_panel]) - tabs.set_title(0, '🔬 Single Circuit') + tabs.set_title(0, '🔬 Single') # Keep the user on the subpanel they were viewing across rebuilds. self._auto_lucj_tabs = self._restore_tab_index(prev_tabs, tabs) return VBox([ @@ -1864,16 +1868,16 @@ def _on_json_preview_toggle(self, change): self._get_export() def _build_import_export_view(self): - """The unified '📁 I/O' nav tab: an Export subpanel and an - Import subpanel (the former '📂 Load' view), switched via a Tab — the - same pattern as the Error / Auto tabs.""" + """The unified '📁 I/O' nav tab: an Import subpanel (the former '📂 Load' + view) first, then an Export subpanel, switched via a Tab — the same + pattern as the Error / Auto tabs. Opens on Import by default.""" prev_tabs = getattr(self, '_io_tabs', None) - io_tabs = Tab(children=[self._build_export_view(), - self._build_auto_view()]) - io_tabs.set_title(0, '📤 Export') - io_tabs.set_title(1, '📥 Import') - # Same class of bug as the Auto tab: a refresh while the user is on the - # Import subpanel would otherwise snap back to Export. + io_tabs = Tab(children=[self._build_auto_view(), + self._build_export_view()]) + io_tabs.set_title(0, '📥 Import') + io_tabs.set_title(1, '📤 Export') + # Same class of bug as the Auto tab: a refresh while the user is on a + # non-default subpanel would otherwise snap back to index 0. self._io_tabs = self._restore_tab_index(prev_tabs, io_tabs) return io_tabs @@ -1924,11 +1928,11 @@ def _build_error_view(self): Returns a ``Tab`` widget with two sub-tabs: - * **🔍 Calibration** — Property & Scale row, Threshold - Filter, and the Calibration & Delta section anchored on - the hoisted ``self._time_panel`` (whose slider state - survives nav / num_circuits / mode changes). - * **🏆 Analysis** — collapsible Qubit Inspector accordion, + * **Calibration** — Property & Scale row, Threshold + Filter, and the Calibration section anchored on the hoisted + ``self._time_panel`` (whose slider state survives nav / + num_circuits / mode changes). + * **Analysis** — collapsible Qubit Inspector accordion, Ranking accordion, Qubit + Gate Trend rows, Stable Qubits + Stable Gates rows. @@ -1944,7 +1948,6 @@ def _build_error_view(self): HTML("
🔍 Focus
"), self.chk_focus_selected, self.chk_isolate, - HTML("
Error map of the layout only
"), HTML("
"), HTML("
🎯 Threshold Filter
"), self.chk_err_threshold, @@ -1956,7 +1959,7 @@ def _build_error_view(self): Label('Max', layout=Layout(width='30px')), self.txt_g_thr_max]), self.threshold_status, HTML("
"), - HTML("
⏱️ Calibration & Delta
"), + HTML("
⏱️ Calibration
"), self._time_panel, HTML("
"), self.lbl_calibration_date, @@ -2006,8 +2009,8 @@ def _build_error_view(self): ]) _err_tabs = Tab(children=[_err_tab_map, _err_tab_analysis]) - _err_tabs.set_title(0, '🔍 Calibration') - _err_tabs.set_title(1, '🏆 Analysis') + _err_tabs.set_title(0, 'Calibration') + _err_tabs.set_title(1, 'Analysis') # Preserve the Calibration/Analysis subtab across rebuilds (same class # of bug as the Auto/I/O tabs). self._err_tabs = self._restore_tab_index( diff --git a/qpu_mapper/ui/png_export.py b/qpu_mapper/ui/png_export.py index b8ce4aa..dad068a 100644 --- a/qpu_mapper/ui/png_export.py +++ b/qpu_mapper/ui/png_export.py @@ -40,6 +40,43 @@ _DISK_FULL_HINTS = ('no space left', 'disk full', 'enospc') +def _append_live_colorbars(export_fig, live_fig, plot_mod): + """Copy the live figure's visible colorbar traces onto the export figure. + + The static renderer (plot.build_static_figure) colors nodes/edges but has + no colorbar code; the interactive figure's two placeholder traces + (_META_CB_QUBIT / _META_CB_GATE) hold the exact colorbar configuration the + user is looking at (ranges, log/linear/delta regime, tick labels, titles). + Copying them guarantees the PNG shows what the screen shows. No-op when + the bars are hidden (design mode / no data) or the placeholders are + missing. Returns the number of bars appended. + """ + import plotly.graph_objects as go + appended = 0 + if live_fig is None: + return 0 + for meta in (plot_mod._META_CB_QUBIT, plot_mod._META_CB_GATE): + try: + tr = plot_mod._trace_by_meta(live_fig, meta) + if tr is None or not tr.marker.showscale: + continue + export_fig.add_trace(go.Scatter( + x=[None], y=[None], mode='markers', + hoverinfo='none', showlegend=False, + marker=tr.marker.to_plotly_json(), + )) + appended += 1 + except Exception: # noqa: BLE001 - never break export + _log.exception("colorbar copy failed for %s; PNG saved without it", + meta) + if appended: + # The bars render below the axes (y=-0.08); make sure the export + # canvas leaves room for them, whatever margin the user picked. + cur_b = getattr(export_fig.layout.margin, 'b', None) or 0 + export_fig.layout.margin.b = max(cur_b, 120) + return appended + + def _classify_write_error(exc: BaseException) -> str: """Map an exception from fig.write_image() to a short user-friendly hint. @@ -91,6 +128,11 @@ def setup_png_export(ctx): build_static_figure safe_path — path-sanitiser out — Output widget for log messages + + Optional ctx fields: + fig — the live FigureWidget; its visible colorbars are + copied onto the PNG (the static renderer has none). + Missing → PNG saved without colorbars, as before. """ state = ctx.state widgets_ref = ctx.widgets_ref @@ -101,6 +143,7 @@ def setup_png_export(ctx): user_save_path = ctx.user_save_path save_dir = ctx.save_dir lbl_png_status = ctx.lbl_png_status + live_fig = getattr(ctx, 'fig', None) # for _append_live_colorbars margin_slider = IntSlider( value=40, min=0, max=200, step=5, @@ -189,6 +232,10 @@ def _on_confirm(b): margin=margin_px, crop_to_selection=crop_checkbox.value, ) + # The static renderer has no colorbar code; copy the visible ones + # off the live figure so the PNG matches the screen (no-op in + # design mode / when the live fig is unavailable). + _append_live_colorbars(export_fig, live_fig, plot_mod) export_fig.write_image( img_path, scale=scale, width=opts['fig_width'], height=opts['fig_height'], diff --git a/qpu_mapper/ui/time_panel.py b/qpu_mapper/ui/time_panel.py index 99d015b..b85b88c 100644 --- a/qpu_mapper/ui/time_panel.py +++ b/qpu_mapper/ui/time_panel.py @@ -1015,12 +1015,9 @@ def _build_widgets(self): # ── 3. Per-mode sub-panels ────────────────────────────────── - # 3a — Live - self.sub_live = VBox([ - HTML(_status_html('info', - 'Showing the current live calibration from the backend.', - escape=False)) - ]) + # 3a — Live: no sub-panel content needed; the header already states + # what is shown ("Showing: Live calibration — "). + self.sub_live = VBox([]) # 3b — Snapshot self.dp_point = DatePicker(description='Date:', layout=_W) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2989105 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,27 @@ +# qpu_mapper (I-QMapper) — runtime dependencies. +# Mirrors [project.dependencies] in pyproject.toml (the source of truth). +# Install with: pip install -r requirements.txt +# Requires Python >= 3.10. + +# ── Core (required) ───────────────────────────────────────────────────────── +numpy>=1.23 +plotly>=5.13 +ipywidgets>=8.0 +ipython>=8.0 +anywidget>=0.9 +qiskit-ibm-runtime>=0.20 +qiskit>=1.0 +rustworkx>=0.13 +platformdirs>=3.0 + +# ── Optional features (uncomment as needed) ───────────────────────────────── +# PNG export (Export tab → "Export PNG"): the static image renderer. +# kaleido + +# Time-lapse GIF export (Export tab → "Export Time-Lapse"). +# imageio +# imageio-ffmpeg + +# ── Development / tests ───────────────────────────────────────────────────── +# pytest>=7 +# pytest-cov diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py index 4962d5e..fcf76c5 100644 --- a/tests/test_auto_subpanels.py +++ b/tests/test_auto_subpanels.py @@ -63,14 +63,14 @@ def test_subpanels_follow_multi_programming(monkeypatch): b.intra_qpu_mode.value = False b._build_auto_lucj_view() assert len(b._auto_lucj_tabs.children) == 1 # Single only - assert b._auto_lucj_tabs.get_title(0) == '🔬 Single Circuit' + assert b._auto_lucj_tabs.get_title(0) == '🔬 Single' # Multi widgets are not in the single panel. assert b.btn_scan_batch not in b._auto_single_panel.children b.intra_qpu_mode.value = True b._build_auto_lucj_view() assert len(b._auto_lucj_tabs.children) == 2 # Single + Multi - assert b._auto_lucj_tabs.get_title(1) == '🔗 Multi-Circuit' + assert b._auto_lucj_tabs.get_title(1) == '🔗 Multi' assert b.btn_scan_batch in b._auto_multi_panel.children assert b.btn_lucj_multi_sweep in b._auto_multi_panel.children diff --git a/tests/test_error_tab_backend_switch.py b/tests/test_error_tab_backend_switch.py new file mode 100644 index 0000000..0514c33 --- /dev/null +++ b/tests/test_error_tab_backend_switch.py @@ -0,0 +1,147 @@ +"""Error-tab header must follow a backend switch. + +The header text comes from time_panel.describe_current_view(state) but only +re-renders when the panel's own observers fire — a backend switch never touches +them. The builder now KEEPS the time-panel API handle and the switch wiring +calls api.rebuild() (best-effort, never breaking a switch) so the header +re-renders for the new backend. +""" +import types +from types import SimpleNamespace + +import pytest + + +# ── stubs shared by the switch-wiring tests ───────────────────────────────── + +class _W: + """Minimal widget stub: settable attrs + a no-op observe.""" + def __init__(self, **kw): + self.__dict__.update(kw) + + def observe(self, *a, **k): + pass + + +def _data_stub(): + return types.SimpleNamespace( + list_known_calibrations=lambda bn, d: [], + scan_day_calibrations=lambda s, b, d, progress_callback=None: [], + get_props_for_datetime=lambda s, b, t: (None, {}, {}), + fetch_calibration_history=lambda s, a, b, progress_callback=None: 0, + apply_history_snapshot=lambda s, ds: True, + _extract_last_update=lambda p: None, + _load_calibration=lambda bn, lu: None, + ) + + +def _export_stub(): + return types.SimpleNamespace(compute_error_delta=lambda a, b, c, d: ({}, {})) + + +# ── 1. header re-renders on api.rebuild() (the switch hook's effect) ───────── + +def test_header_updates_after_backend_switch(): + from qpu_mapper.ui.time_panel import build_time_panel + from qpu_mapper.state import SessionState + + state = SessionState() + state.active_backend_name = 'ibm_old' + state.time_mode = 'live' + panel, api = build_time_panel( + state=state, data_mod=_data_stub(), export_mod=_export_stub(), + refresh_plot=lambda: None, load_device_graph=lambda: None, + spawn_bg=lambda fn, on_done=None, on_error=None: ( + on_done(fn()) if on_done else fn()), + ) + api.rebuild() + assert 'ibm_old' in api._b.lbl_header.value + + # Post-switch condition (as the builder's reset produces it, then the + # switch wiring calls api.rebuild()). + state.active_backend_name = 'ibm_new' + state.time_mode = 'live' + state._live_qubit_props = None + api.rebuild() + + assert 'ibm_new' in api._b.lbl_header.value + assert 'ibm_old' not in api._b.lbl_header.value + + +# ── switch-wiring: hook fires on success (after load) + tolerates failure ──── + +def _switch_ctx(state, *, load_device_graph, refresh_time_panel): + return SimpleNamespace( + state=state, + dd_backend_switch=_W(disabled=False, options=[], value=state.active_backend_name), + lbl_switch_status=_W(value=''), + lbl_calibration_date=_W(value=''), + lbl_props_warning=_W(value=''), + chk_keep_layout=_W(value=False), + switching_backend=[False], + load_device_graph=load_device_graph, + refresh=lambda: None, get_export=lambda: None, + out=SimpleNamespace(), + refresh_time_panel=refresh_time_panel, + ) + + +def _fresh_state(): + from qpu_mapper.state import SessionState + state = SessionState() + state.active_backend_name = 'ibm_old' + state.active_chip = 'Heron r1' + state.active_service = SimpleNamespace(backend=lambda n: SimpleNamespace(name=n)) + state.available_backends = ['ibm_old', 'ibm_new'] + return state + + +def test_switch_invokes_time_panel_hook(monkeypatch): + from qpu_mapper.ui.backend_switch import setup_backend_switch + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'Heron r1')) + + events = [] + state = _fresh_state() + ctx = _switch_ctx( + state, + load_device_graph=lambda force=False: events.append('load'), + refresh_time_panel=lambda: events.append('hook')) + setup_backend_switch(ctx)({'new': 'ibm_new'}) + + assert events.count('hook') == 1 # ran exactly once + assert events.index('load') < events.index('hook') # AFTER load_device_graph + assert state.active_backend_name == 'ibm_new' # switch succeeded + + # A raising hook must NOT break the switch. + def _boom(): + raise RuntimeError('hook boom') + state2 = _fresh_state() + ctx2 = _switch_ctx( + state2, load_device_graph=lambda force=False: None, + refresh_time_panel=_boom) + setup_backend_switch(ctx2)({'new': 'ibm_new'}) + assert state2.active_backend_name == 'ibm_new' # switched despite hook error + + +def test_switch_rollback_invokes_hook(monkeypatch): + from qpu_mapper.ui.backend_switch import setup_backend_switch + monkeypatch.setattr("qpu_mapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + lambda b: ([], 'Heron r1')) + + events = [] + + def _load_fails(force=False): + raise RuntimeError('graph load failed') + state = _fresh_state() + ctx = _switch_ctx( + state, load_device_graph=_load_fails, + refresh_time_panel=lambda: events.append('hook')) + setup_backend_switch(ctx)({'new': 'ibm_new'}) + + assert events.count('hook') == 1 # hook ran on rollback too + assert state.active_backend_name == 'ibm_old' # state rolled back diff --git a/tests/test_import_export_ui.py b/tests/test_import_export_ui.py index e28887a..7c9debe 100644 --- a/tests/test_import_export_ui.py +++ b/tests/test_import_export_ui.py @@ -60,11 +60,11 @@ def test_unified_io_tab(monkeypatch): b.nav_bar.value = 'io' view = b.content_box.children[0] assert isinstance(view, Tab) and len(view.children) == 2 - assert view.get_title(0) == '📤 Export' - assert view.get_title(1) == '📥 Import' + assert view.get_title(0) == '📥 Import' + assert view.get_title(1) == '📤 Export' assert exp_calls # export path ran on open - export_panel, import_panel = view.children[0], view.children[1] + import_panel, export_panel = view.children[0], view.children[1] assert _contains(export_panel, b.btn_save_json) # export control present assert _contains(import_panel, b.btn_unified_upload) # import control present @@ -88,7 +88,7 @@ def test_old_nav_tabs_removed(monkeypatch): def test_json_preview_collapsible(monkeypatch): b, state = _build(monkeypatch) b.nav_bar.value = 'io' - export_panel = b.content_box.children[0].children[0] + export_panel = b.content_box.children[0].children[1] # Export is now 2nd subtab acc = _find(export_panel, Accordion) assert acc is not None assert acc.selected_index is None # collapsed by default @@ -103,5 +103,5 @@ def test_json_preview_collapsible(monkeypatch): # Choice persists: a rebuilt Export subpanel keeps the preview open. io2 = b._build_import_export_view() - acc2 = _find(io2.children[0], Accordion) + acc2 = _find(io2.children[1], Accordion) # Export is the 2nd subtab assert acc2.selected_index == 0 diff --git a/tests/test_png_colorbars.py b/tests/test_png_colorbars.py new file mode 100644 index 0000000..8ea2933 --- /dev/null +++ b/tests/test_png_colorbars.py @@ -0,0 +1,123 @@ +"""PNG export copies the live figure's visible colorbars onto the static +export figure (plot.build_static_figure has no colorbar code). + +Offline: never calls write_image (kaleido/chrome unavailable); uses plain +plotly figures and stubs the render/write path. +""" +import types +from types import SimpleNamespace + +import pytest + +pytest.importorskip('plotly') +import plotly.graph_objects as go # noqa: E402 + +from qpu_mapper import plot # noqa: E402 (constants + _trace_by_meta only) +from qpu_mapper.ui.png_export import _append_live_colorbars # noqa: E402 + + +def _cb_trace(meta, *, showscale, cmin, cmax, title): + return go.Scatter( + x=[None], y=[None], mode='markers', meta=meta, + hoverinfo='none', showlegend=False, + marker=dict(showscale=showscale, cmin=cmin, cmax=cmax, + colorscale='Viridis', colorbar=dict(title=title))) + + +# ── 1. visible bars are copied with their config + canvas gets bottom room ── + +def test_appends_visible_colorbars(): + live = go.Figure() + live.add_trace(_cb_trace(plot._META_CB_QUBIT, showscale=True, + cmin=0.0, cmax=1.0, title='Qubit')) + live.add_trace(_cb_trace(plot._META_CB_GATE, showscale=True, + cmin=2.0, cmax=3.0, title='Gate')) + export = go.Figure() + + n = _append_live_colorbars(export, live, plot) + + assert n == 2 + assert len(export.data) == 2 + assert sorted(t.marker.cmin for t in export.data) == [0.0, 2.0] + assert sorted(t.marker.cmax for t in export.data) == [1.0, 3.0] + assert sorted(t.marker.colorbar.title.text for t in export.data) == ['Gate', 'Qubit'] + assert export.layout.margin.b >= 120 + + +# ── 2. design mode (showscale=False) → nothing copied, margin untouched ───── + +def test_hidden_bars_are_not_copied(): + live = go.Figure() + live.add_trace(_cb_trace(plot._META_CB_QUBIT, showscale=False, + cmin=0.0, cmax=1.0, title='Qubit')) + live.add_trace(_cb_trace(plot._META_CB_GATE, showscale=False, + cmin=2.0, cmax=3.0, title='Gate')) + export = go.Figure() + margin_before = export.layout.margin.b + + n = _append_live_colorbars(export, live, plot) + + assert n == 0 + assert len(export.data) == 0 + assert export.layout.margin.b == margin_before # untouched + + +# ── 3. no live fig / no placeholder traces → no-op, no exception ──────────── + +def test_missing_live_fig_is_noop(): + export = go.Figure() + assert _append_live_colorbars(export, None, plot) == 0 + assert len(export.data) == 0 + + live = go.Figure() + live.add_trace(go.Scatter(x=[1], y=[1], meta='qubits')) # not a CB placeholder + assert _append_live_colorbars(export, live, plot) == 0 + assert len(export.data) == 0 + + +# ── 4. the export site runs the helper BETWEEN build and write ────────────── + +def _walk(node): + yield node + for ch in getattr(node, 'children', []): + yield from _walk(ch) + + +def test_export_site_invokes_helper(monkeypatch, tmp_path): + from ipywidgets import Text, Button, HTML, Output, Layout + from qpu_mapper.ui import png_export as pe + + events = [] + + class _FakeFig: + def write_image(self, path, scale=None, width=None, height=None): + events.append('write') + + plot_mod = SimpleNamespace( + collect_render_opts=lambda w: {'fig_width': 100, 'fig_height': 100}, + build_static_figure=lambda state, opts, margin=0, crop_to_selection=False: ( + events.append('build') or _FakeFig()), + _META_CB_QUBIT=plot._META_CB_QUBIT, _META_CB_GATE=plot._META_CB_GATE, + _trace_by_meta=plot._trace_by_meta, + ) + # Record that the helper ran (its own behavior is covered by tests 1-3). + monkeypatch.setattr(pe, '_append_live_colorbars', + lambda ef, lf, pm: events.append('append') or 0) + + out_path = str(tmp_path / 'shot.png') # does not exist yet + ctx = SimpleNamespace( + state=SimpleNamespace(), widgets_ref=SimpleNamespace(), + fname_img=Text(value='shot'), btn_save_img=Button(), W=Layout(), + plot_mod=plot_mod, safe_path=lambda p, *a, **k: p, + user_save_path=lambda name, ext, default_dir=None: out_path, + save_dir=lambda: str(tmp_path), out=Output(), + lbl_png_status=HTML(), fig=go.Figure(), + ) + popup, _, _ = pe.setup_png_export(ctx) + + btn_confirm = next(w for w in _walk(popup) + if isinstance(w, Button) and 'Export now' in (w.description or '')) + btn_confirm.click() + + # Helper ran, and it ran AFTER build_static_figure and BEFORE write_image. + assert events == ['build', 'append', 'write'] diff --git a/tests/test_subpanel_persistence.py b/tests/test_subpanel_persistence.py index 749a4f3..e2f42f4 100644 --- a/tests/test_subpanel_persistence.py +++ b/tests/test_subpanel_persistence.py @@ -146,9 +146,23 @@ def test_io_subtab_survives_rebuild(monkeypatch): b, state = _build(monkeypatch) b.nav_bar.value = 'io' assert len(b._io_tabs.children) == 2 - b._io_tabs.selected_index = 1 # Import subpanel + b._io_tabs.selected_index = 1 # Export subpanel (index 1) b._update_view() # a refresh while on I/O - assert b._io_tabs.selected_index == 1 # still Import, not Export + assert b._io_tabs.selected_index == 1 # still Export, not Import (index 0) + + +def test_io_import_first_paste_first(monkeypatch): + from ipywidgets import HTML + b, state = _build(monkeypatch) + b.nav_bar.value = 'io' + # I/O opens on Import (index 0); Export is the second sub-tab. + assert b._io_tabs.get_title(0) == '📥 Import' + assert b._io_tabs.get_title(1) == '📤 Export' + # Import subpanel leads with the paste-qubit-list block (renamed, no "Or"). + import_panel = b._io_tabs.children[0] + first_html = next(c for c in import_panel.children if isinstance(c, HTML)) + assert 'Paste qubit list' in first_html.value + assert 'Or paste' not in first_html.value def test_error_subtab_survives_rebuild(monkeypatch): From b56f1d6f1ac75f23ee96992a23d9e431dcbf94df Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 15 Sep 2026 17:09:08 -0400 Subject: [PATCH 27/66] Remove leftover merge conflict markers from pyproject.toml --- pyproject.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 324050f..3030ef7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,11 +9,7 @@ description = "Interactive, noise-aware QPU layout mapper for Jupyter Lab" readme = "README.md" requires-python = ">=3.10" authors = [ -<<<<<<< HEAD { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com" }, -======= - { name = "Kenneth M. Merz Jr", email = "kmerz1@gmail.com"}, ->>>>>>> main { name = "Milana Bazayeva", email = "m.bazayeva@gmail.com" }, ] keywords = ["quantum", "qiskit", "qpu", "layout", "visualization"] From e32875d04c53e2be27babf04adeab1a8375ae7df Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Fri, 18 Sep 2026 16:30:34 -0400 Subject: [PATCH 28/66] Post-merge: rename residue sweep, dedupe helpers, version 0.1.0.dev0; drop requirements.txt --- CHANGELOG.md | 15 +++++++ CITATION.cff | 2 +- iqmapper/__init__.py | 2 +- iqmapper/ui/backend_switch.py | 31 -------------- iqmapper/ui/lucj_panel.py | 10 ++--- iqmapper/ui/png_export.py | 51 ----------------------- pyproject.toml | 8 ++-- requirements.txt | 2 +- tests/test_ancilla_sweep.py | 4 +- tests/test_async_util.py | 8 ++-- tests/test_auto_subpanels.py | 14 +++---- tests/test_calibration_epoch.py | 4 +- tests/test_cascade.py | 2 +- tests/test_diversity.py | 2 +- tests/test_error_tab_backend_switch.py | 18 ++++----- tests/test_floor_batch_ui.py | 36 ++++++++--------- tests/test_import_export_ui.py | 8 ++-- tests/test_inter_qpu_handoff.py | 44 ++++++++++---------- tests/test_inter_qpu_live_model.py | 10 ++--- tests/test_inter_qpu_resync.py | 16 ++++---- tests/test_multi_sweep.py | 4 +- tests/test_multi_sweep_ui.py | 20 ++++----- tests/test_plot_node_guard.py | 14 +++---- tests/test_png_colorbars.py | 6 +-- tests/test_props_shim.py | 16 ++++---- tests/test_qpu_scan.py | 14 +++---- tests/test_scan_notices.py | 20 ++++----- tests/test_scan_targets_line.py | 18 ++++----- tests/test_scan_ui.py | 56 +++++++++++++------------- tests/test_scan_ui_pass.py | 14 +++---- tests/test_scoring_core.py | 4 +- tests/test_shuffle_search.py | 2 +- tests/test_stability_filter.py | 6 +-- tests/test_stability_ui.py | 42 +++++++++---------- tests/test_subpanel_persistence.py | 16 ++++---- tests/test_sweep_notices.py | 24 +++++------ tests/test_sweep_ui.py | 34 ++++++++-------- tests/test_temporal_anchoring.py | 24 +++++------ tests/test_ui_cleanup.py | 16 ++++---- 39 files changed, 285 insertions(+), 352 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32d5f99..4be3e73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,21 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### Added +- Stratified ancilla sweep: a single VF2 solve at `k_max` feeding a + bridge-subtraction cascade down to `k_min`, with a hybrid mode, a shuffled + search for hard instances, and region-diversity selection across the chip. +- Stability filter with an always-on quality floor, so layouts that score well + on one calibration epoch but drift across neighbouring ones are rejected. +- Multi-circuit sweep: sequential orchestration over several circuits with + replan-from-step to recover a run without restarting it. +- Multi-QPU scan across the available backends, with one-click inter-QPU + handoff that reopens the chosen layout on the second QPU. +- Epoch-consistent scoring: fidelity and ranking read a single pinned + calibration epoch, so comparisons within a sweep stay commensurable. + ## [0.0.5] — 2026-08 First public-ready release. diff --git a/CITATION.cff b/CITATION.cff index 1ca6ced..4bbf857 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -4,7 +4,7 @@ title: "I-QMapper" authors: - family-names: "Bazayeva" given-names: "Milana" -version: 0.0.5 +version: 0.1.0.dev0 license: Apache-2.0 preferred-citation: type: article diff --git a/iqmapper/__init__.py b/iqmapper/__init__.py index a9a8396..f7a3a9f 100644 --- a/iqmapper/__init__.py +++ b/iqmapper/__init__.py @@ -15,7 +15,7 @@ def run(): - """Launch the QPU Mapper UI (sidebar layout).""" + """Launch the I-QMapper UI (sidebar layout).""" # Capture the kernel main loop HERE — run() is called from a notebook cell, # which is GUARANTEED to be the main thread with the kernel loop up. This is # the earliest, most reliable capture point; later build() calls are diff --git a/iqmapper/ui/backend_switch.py b/iqmapper/ui/backend_switch.py index 6d8ad2d..9506dc6 100644 --- a/iqmapper/ui/backend_switch.py +++ b/iqmapper/ui/backend_switch.py @@ -24,12 +24,6 @@ Public API: setup_backend_switch(ctx) -> on_backend_switch_handler -Optional ctx keys (absent → the corresponding refresh is skipped): - refresh_qpu1_label — single-element cell holding ui.inter_qpu's hook. - refresh_time_panel — zero-arg callable re-rendering the time/delta panel - so its "Showing:" header names the new backend. Called on the success - path (after the graph reload) and again on the rollback path. - The handler is returned so callers (e.g. tests) can invoke it explicitly. `ctx.switching_backend` is shared with `_load_device_graph` — both routines need to see the same flag for @@ -143,26 +137,6 @@ def setup_backend_switch(ctx): # [None] until inter-QPU is wired). Absent entirely in callers/tests that # don't build the inter-QPU panel — treat as "no hook". refresh_qpu1_label_cell = getattr(ctx, 'refresh_qpu1_label', None) - # Optional: zero-arg callable that re-renders the time/delta panel so its - # "Showing:" header stops naming the previous backend. Absent in callers - # and tests that don't build the time panel — treat as "no hook". - refresh_time_panel_hook = getattr(ctx, 'refresh_time_panel', None) - - def _refresh_time_panel(): - """Best-effort re-render of the time/delta panel after a switch. - - The panel's header caches the backend name it was last built with, so - without this it keeps showing the OLD backend after a switch. A header - refresh must NEVER break a backend switch, so failures are logged and - swallowed. No-op when no hook was supplied. - """ - if refresh_time_panel_hook is None: - return - try: - _log.debug("Rebuilding time/delta panel after backend switch") - refresh_time_panel_hook() - except Exception: - _log.exception("Time panel refresh after backend switch failed") def _refresh_qpu1_label(): """Best-effort refresh of the QPU-1 switcher label after a switch. @@ -286,11 +260,6 @@ def _on_backend_switch(change): # reject this call. load_device_graph(force=True) - # The graph reload has just reset the time state for the new - # backend; re-render the time/delta panel so its "Showing:" - # header names the new backend instead of the previous one. - _refresh_time_panel() - # ── Layout preservation ────────────────────────────────── layout_msg = "" if saved_layouts is not None: diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 3862b95..e044e3d 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -75,7 +75,7 @@ def _k_cap_phrase(norb, k_effective): class _ScanNoticeCapture(logging.Handler): - """Captures WARNING+ records off the 'qpu_mapper' logger during a + """Captures WARNING+ records off the 'iqmapper' logger during a scan, tagging each with the current backend context. emit() never raises out — a logging hiccup must not break the scan.""" @@ -93,7 +93,7 @@ def emit(self, record): @contextlib.contextmanager def _capture_qpu_notices(context_getter): - """Capture WARNING+ records off the 'qpu_mapper' logger for the duration of + """Capture WARNING+ records off the 'iqmapper' logger for the duration of a sweep and stop them leaking under the notebook cell (propagate=False). Attaches the handler in the try; restores BOTH the handler and propagate in finally, so a raising sweep can't leave the logger muted or double-handled. @@ -103,7 +103,7 @@ def _capture_qpu_notices(context_getter): Shared by every sweep path: the multi-QPU scan, the local single sweep, and the multi-circuit sweep + replan. Restoration is the try/finally guarantee the tests pin.""" - logger = logging.getLogger('qpu_mapper') + logger = logging.getLogger('iqmapper') orig_propagate = logger.propagate handler = _ScanNoticeCapture(context_getter) try: @@ -662,7 +662,7 @@ def _on_lucj_generate(b): lbl_lucj_notices.value = "" try: requested_ancillas = lucj_ancilla_dd.value - # Capture WARNING+ off 'qpu_mapper' for the sweep so bridge/VF2 + # Capture WARNING+ off 'iqmapper' for the sweep so bridge/VF2 # notices land in the loud notices bar, not under the cell. with _capture_qpu_notices( lambda: state.active_backend_name or 'local sweep') as handler: @@ -1308,7 +1308,7 @@ def _on_scan_click(b): and chk_scan_stability.value) def _work(): - # Capture WARNING+ off 'qpu_mapper' for the scan's duration and stop + # Capture WARNING+ off 'iqmapper' for the scan's duration and stop # them leaking under the cell — the same context every sweep uses. with _capture_qpu_notices( lambda: _scan.get('current') or 'general') as handler: diff --git a/iqmapper/ui/png_export.py b/iqmapper/ui/png_export.py index ca067e8..dad068a 100644 --- a/iqmapper/ui/png_export.py +++ b/iqmapper/ui/png_export.py @@ -17,8 +17,6 @@ import logging import os -import plotly.graph_objects as go - from .status import status_html from ipywidgets import ( @@ -101,55 +99,6 @@ def _classify_write_error(exc: BaseException) -> str: return f"PNG export failed ({type(exc).__name__}): {exc!s}" -# The colorbars render below the axes (y=-0.08 in plot._update_colorbars), -# so the export figure needs bottom margin for them or they get clipped. -_CB_EXPORT_MIN_BOTTOM_MARGIN = 120 - - -def _append_live_colorbars(export_fig, live_fig, plot_mod): - """Copy the interactive figure's visible error-map colorbars onto `export_fig`. - - The colorbars are not part of the static renderer: plot.build_static_figure - draws no colorbar of its own, because on the interactive figure the bars - live on two placeholder traces that plot._update_colorbars configures in - place. Exporting therefore has to carry those placeholders across, or the - PNG loses both scales. - - Returns the number of colorbars appended. A colorbar is cosmetic, so a - failure to copy one must never break the export — each is guarded - independently and the export continues without it. - """ - if export_fig is None or live_fig is None: - return 0 - - appended = 0 - for meta in (plot_mod._META_CB_QUBIT, plot_mod._META_CB_GATE): - try: - tr = plot_mod._trace_by_meta(live_fig, meta) - # showscale is False whenever the bar is not currently displayed - # (non-error mode, or an all-NaN array) — nothing to copy then. - if tr is None or not getattr(tr.marker, 'showscale', False): - continue - export_fig.add_trace(go.Scatter( - x=[None], y=[None], mode='markers', - hoverinfo='none', showlegend=False, - marker=tr.marker.to_plotly_json(), - )) - appended += 1 - except Exception: - _log.exception("Copying colorbar %r into the PNG export failed", meta) - - if appended: - try: - current = export_fig.layout.margin.b or 0 - if current < _CB_EXPORT_MIN_BOTTOM_MARGIN: - export_fig.layout.margin.b = _CB_EXPORT_MIN_BOTTOM_MARGIN - except Exception: - _log.exception("Raising the export figure's bottom margin failed") - - return appended - - def _ensure_png_extension(name: str) -> str: """Strip a trailing '.png' before re-adding it once. diff --git a/pyproject.toml b/pyproject.toml index 260298d..53864be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "i-qmapper" -version = "0.0.5" +version = "0.1.0.dev0" description = "Interactive, noise-aware QPU layout mapper for Jupyter Lab" readme = "README.md" requires-python = ">=3.10" @@ -44,9 +44,9 @@ timelapse = ["imageio", "imageio-ffmpeg"] dev = ["pytest>=7", "pytest-cov"] [project.urls] -Homepage = "https://github.com/mbazayeva/i-qmapper" -Issues = "https://github.com/mbazayeva/i-qmapper/issues" -Changelog = "https://github.com/mbazayeva/i-qmapper/blob/main/CHANGELOG.md" +Homepage = "https://github.com/MIQuLab/i-qmapper" +Issues = "https://github.com/MIQuLab/i-qmapper/issues" +Changelog = "https://github.com/MIQuLab/i-qmapper/blob/main/CHANGELOG.md" Paper = "https://arxiv.org/abs/2606.27508" [tool.setuptools.packages.find] diff --git a/requirements.txt b/requirements.txt index 2989105..0bbf01a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -# qpu_mapper (I-QMapper) — runtime dependencies. +# I-QMapper — runtime dependencies. # Mirrors [project.dependencies] in pyproject.toml (the source of truth). # Install with: pip install -r requirements.txt # Requires Python >= 3.10. diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index 252527d..3583cbe 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -1,4 +1,4 @@ -"""Tests for qpu_mapper.ancilla_sweep — the one-shot bridge-subtraction sweep. +"""Tests for iqmapper.ancilla_sweep — the one-shot bridge-subtraction sweep. Deterministic and fully offline (no qiskit, no network). A synthetic backend is built from two disconnected width-8 heavy-hex-like "ladder" blocks: @@ -30,7 +30,7 @@ from types import SimpleNamespace -from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.ancilla_sweep import sweep_ancilla_layouts GOOD_QUBITS = set(range(24)) # ids 0..23 are the low-error "good region" diff --git a/tests/test_async_util.py b/tests/test_async_util.py index 0daa5cb..d9951fd 100644 --- a/tests/test_async_util.py +++ b/tests/test_async_util.py @@ -1,4 +1,4 @@ -"""Regression tests for qpu_mapper.async_util. +"""Regression tests for iqmapper.async_util. Two invariants pinned here: @@ -257,9 +257,9 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): np.array([0.01 * (i + 1) for i in range(n)]), np.array([0.001 * (i + 1) for i in range(n - 1)])) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = 'stub' diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py index fcf76c5..becacac 100644 --- a/tests/test_auto_subpanels.py +++ b/tests/test_auto_subpanels.py @@ -34,9 +34,9 @@ def _canned(): def _build(monkeypatch): - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "ibm_here" @@ -96,11 +96,11 @@ def test_multi_subpanel_has_two_buttons_no_legacy(monkeypatch): # ── R3 t2: the legacy handler + engine stay defined (source pin) ──────────── def test_legacy_handler_and_engine_still_defined(): - panel = Path('qpu_mapper/ui/lucj_panel.py').read_text() + panel = Path('iqmapper/ui/lucj_panel.py').read_text() assert 'def _on_lucj_multi(' in panel # handler retained assert 'get_multi_circuit_layouts' in panel # engine path retained # And the widget object is still wired (clickable) for the pinned tests. - from qpu_mapper.ui.builder import MapperUIBuilder + from iqmapper.ui.builder import MapperUIBuilder assert hasattr(MapperUIBuilder, '_build_auto_lucj_view') @@ -108,7 +108,7 @@ def test_legacy_handler_and_engine_still_defined(): def test_detail_panel_counts_not_qubit_lists(monkeypatch): b, state = _build(monkeypatch) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned()) b.lucj_ancilla_dd.value = -1 # sweep mode b.btn_lucj_run.click() @@ -123,7 +123,7 @@ def test_detail_panel_counts_not_qubit_lists(monkeypatch): # ── t5: an applied batch (C1..Cn) is auto-reflected in the export ────────── def test_export_reads_applied_batch(): - from qpu_mapper.export.codegen import get_qiskit_layout_code + from iqmapper.export.codegen import get_qiskit_layout_code state = SimpleNamespace(layouts_data={ 0: {'alpha': ['0', '1'], 'beta': ['2', '3'], 'other': [], 'name': 'C1'}, 1: {'alpha': ['4', '5'], 'beta': ['6', '7'], 'other': [], 'name': 'C2'}, diff --git a/tests/test_calibration_epoch.py b/tests/test_calibration_epoch.py index 5bdfd44..360a43b 100644 --- a/tests/test_calibration_epoch.py +++ b/tests/test_calibration_epoch.py @@ -35,7 +35,7 @@ def t2(self, q): return 1e-9 def _build(monkeypatch, *, snapshot, ancilla=0): - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) captured = {} monkeypatch.setattr( "iqmapper.auto_lucj.get_all_zigzag_layouts", @@ -144,7 +144,7 @@ def _fake_sweep(norb, backend, props, **kw): 'mapping_cap': None, 'k_max_effective': None} monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", _fake_sweep) + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", _fake_sweep) b, state, _ = _build(monkeypatch, snapshot=True, ancilla=-1) b.btn_lucj_run.click() pr = swept['props'] diff --git a/tests/test_cascade.py b/tests/test_cascade.py index 013fab9..a8e9e7d 100644 --- a/tests/test_cascade.py +++ b/tests/test_cascade.py @@ -23,7 +23,7 @@ import rustworkx -from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.ancilla_sweep import sweep_ancilla_layouts NORB = 12 GOOD = set(range(100, 126)) # region G qubit ids diff --git a/tests/test_diversity.py b/tests/test_diversity.py index 2517b80..8ec17e0 100644 --- a/tests/test_diversity.py +++ b/tests/test_diversity.py @@ -7,7 +7,7 @@ import rustworkx -from qpu_mapper.ancilla_sweep import ( +from iqmapper.ancilla_sweep import ( _jaccard, _select_with_diversity, sweep_ancilla_layouts, ) diff --git a/tests/test_error_tab_backend_switch.py b/tests/test_error_tab_backend_switch.py index 0514c33..51000d0 100644 --- a/tests/test_error_tab_backend_switch.py +++ b/tests/test_error_tab_backend_switch.py @@ -42,8 +42,8 @@ def _export_stub(): # ── 1. header re-renders on api.rebuild() (the switch hook's effect) ───────── def test_header_updates_after_backend_switch(): - from qpu_mapper.ui.time_panel import build_time_panel - from qpu_mapper.state import SessionState + from iqmapper.ui.time_panel import build_time_panel + from iqmapper.state import SessionState state = SessionState() state.active_backend_name = 'ibm_old' @@ -87,7 +87,7 @@ def _switch_ctx(state, *, load_device_graph, refresh_time_panel): def _fresh_state(): - from qpu_mapper.state import SessionState + from iqmapper.state import SessionState state = SessionState() state.active_backend_name = 'ibm_old' state.active_chip = 'Heron r1' @@ -97,10 +97,10 @@ def _fresh_state(): def test_switch_invokes_time_panel_hook(monkeypatch): - from qpu_mapper.ui.backend_switch import setup_backend_switch - monkeypatch.setattr("qpu_mapper.connection._check_properties", + from iqmapper.ui.backend_switch import setup_backend_switch + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'Heron r1')) events = [] @@ -127,10 +127,10 @@ def _boom(): def test_switch_rollback_invokes_hook(monkeypatch): - from qpu_mapper.ui.backend_switch import setup_backend_switch - monkeypatch.setattr("qpu_mapper.connection._check_properties", + from iqmapper.ui.backend_switch import setup_backend_switch + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'Heron r1')) events = [] diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index 99c731b..99f6419 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -44,11 +44,11 @@ def _canned(**extra): def _build(monkeypatch, spawn=_sync_spawn): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_16) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_16) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "stub" @@ -77,7 +77,7 @@ def _build(monkeypatch, spawn=_sync_spawn): def test_floor_excludes_outlier_by_default(monkeypatch): b, state = _build(monkeypatch) cap = {} - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **k: cap.update(k) or _canned()) b.lucj_ancilla_dd.value = -1 # sweep mode b.btn_lucj_run.click() @@ -90,7 +90,7 @@ def test_floor_excludes_outlier_by_default(monkeypatch): def test_floor_off_at_sigma_zero(monkeypatch): b, state = _build(monkeypatch) cap = {} - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **k: cap.update(k) or _canned()) b.ft_stability_floor.value = 0 # off b.lucj_ancilla_dd.value = -1 @@ -106,13 +106,13 @@ def test_floor_and_filter_no_double(monkeypatch): state.cal_history = {'2026-07-01': {'qubit_props': {'readout_error': [0.01] * 16}, 'gate_props': {}}} sws = {} - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: sws.update(k) or _canned( stability={'available': True, 'relaxed': False, 'excluded_final': [5], 'window_days': 14, 'n_floor_excluded': 1, 'floor_qubits': [5]})) plain = [] - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: plain.append(k) or _canned()) b.chk_stability_filter.disabled = False # history available b.chk_stability_filter.value = True @@ -128,7 +128,7 @@ def test_floor_and_filter_no_double(monkeypatch): def test_scan_floor_per_backend(monkeypatch): b, state = _build(monkeypatch) - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) @@ -139,10 +139,10 @@ def test_scan_floor_per_backend(monkeypatch): 'ibm_b': SimpleNamespace(_readout=np.array([0.01] * 16), n_qubits=16, vintage='live', score_layout=lambda q: {'fidelity': 0.5})} - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: props[backend.name])) seen = {} - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **k: seen.setdefault(bk.name, k) or _canned()) b.btn_scan_qpus.click() assert 5 in (seen['ibm_a'].get('exclude_qubits') or set()) @@ -154,11 +154,11 @@ def test_scan_floor_per_backend(monkeypatch): def test_legacy_paths_untouched(monkeypatch): b, state = _build(monkeypatch) single = [] - monkeypatch.setattr("qpu_mapper.auto_lucj.get_all_zigzag_layouts", + monkeypatch.setattr("iqmapper.auto_lucj.get_all_zigzag_layouts", lambda **k: single.append(k) or ([{'rank': 1, 'score': 0.1, 'alpha': [0, 1], 'beta': [2, 3]}], 1)) multi = [] - monkeypatch.setattr("qpu_mapper.auto_lucj.get_multi_circuit_layouts", + monkeypatch.setattr("iqmapper.auto_lucj.get_multi_circuit_layouts", lambda **k: multi.append(k) or [ {'circuit_idx': 0, 'norb': 8, 'num_bridges': 2, 'all_candidates': [{'layout': [0, 1, 2, 3], @@ -192,7 +192,7 @@ def _batch_result_row(name, total_lqs, ks, failed_at=None): def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): b, state = _build(monkeypatch) - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: []) # scan_qpus returns a ready-ranked batch result (ibm_hi first). monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: {'results': [ @@ -225,11 +225,11 @@ def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): def test_batch_scan_sweep_fn_gets_multi_knobs(monkeypatch): b, state = _build(monkeypatch) - from qpu_mapper import qpu_scan as qs - from qpu_mapper import multi_sweep as ms + from iqmapper import qpu_scan as qs + from iqmapper import multi_sweep as ms monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: SimpleNamespace( _readout=np.array([0.01] * 16), n_qubits=16, vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) @@ -256,7 +256,7 @@ def test_batch_scan_sweep_fn_gets_multi_knobs(monkeypatch): def test_batch_selector_handoff_payload(monkeypatch): b, state = _build(monkeypatch) - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: []) monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: {'results': [ _batch_result_row('ibm_hi', 0.61, 2)], diff --git a/tests/test_import_export_ui.py b/tests/test_import_export_ui.py index 7c9debe..4efd02c 100644 --- a/tests/test_import_export_ui.py +++ b/tests/test_import_export_ui.py @@ -14,9 +14,9 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): def _build(monkeypatch): - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "ibm_here" @@ -70,7 +70,7 @@ def test_unified_io_tab(monkeypatch): # Import path still wired: firing the upload handler reaches its reader. up = [] - monkeypatch.setattr("qpu_mapper.ui.builder._read_upload", + monkeypatch.setattr("iqmapper.ui.builder._read_upload", lambda w: up.append(1) or None) b._on_unified_upload({'new': [object()]}) assert up diff --git a/tests/test_inter_qpu_handoff.py b/tests/test_inter_qpu_handoff.py index 905dffd..dd5ce12 100644 --- a/tests/test_inter_qpu_handoff.py +++ b/tests/test_inter_qpu_handoff.py @@ -88,11 +88,11 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): plot_h_slider=SimpleNamespace(value=0)) return (full_ui, fig, w2) if return_widgets else (full_ui, fig) - monkeypatch.setattr("qpu_mapper.connection._check_properties", + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'chip_label')) - monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) _CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} @@ -101,7 +101,7 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): # ── selection triggers connect once; staged→connecting→connected ──────── def test_selection_auto_connects_once(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu _stub_connect_deps(monkeypatch) calls = [] ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls) @@ -120,7 +120,7 @@ def test_selection_auto_connects_once(monkeypatch): # ── connect raising → staged fallback + error, trigger re-enabled ─────── def test_connect_failure_falls_back_to_staged(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu _stub_connect_deps(monkeypatch) calls = [] ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls, raise_connect=True) @@ -140,7 +140,7 @@ def test_connect_failure_falls_back_to_staged(monkeypatch): # ── in-flight guard — a second selection does not double-connect ──────── def test_in_flight_guard_no_double_connect(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu _stub_connect_deps(monkeypatch) calls = [] queued = [] @@ -166,10 +166,10 @@ def _manual_spawn(fn, on_done=None, on_error=None): # ── same backend already connected → apply + repaint, no reconnect ────── def test_same_backend_applies_without_reconnect(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu _stub_connect_deps(monkeypatch) repaints = [] - monkeypatch.setattr("qpu_mapper.plot.refresh_plot", + monkeypatch.setattr("iqmapper.plot.refresh_plot", lambda fig, st, w: repaints.append(st)) calls = [] ctx, state = _ctx(spawn=_sync_spawn, backend_calls=calls) @@ -192,7 +192,7 @@ def test_same_backend_applies_without_reconnect(monkeypatch): # ── batch handoff: a LIST of candidates applies to C1..Cn on QPU-2 ────────── def test_batch_handoff_applies_all_circuits(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu captured = {} def _fake_build(s2, is_secondary=False, return_widgets=False): @@ -207,11 +207,11 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): plot_h_slider=SimpleNamespace(value=0)) return (full_ui, fig, w2) if return_widgets else (full_ui, fig) - monkeypatch.setattr("qpu_mapper.connection._check_properties", + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'chip')) - monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) ctx, state = _ctx(spawn=_sync_spawn, backend_calls=[]) setup_inter_qpu(ctx) @@ -231,7 +231,7 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): # proves the candidate both LANDS on QPU-2 state AND reaches the figure. def _qubit_trace(fig): - from qpu_mapper.plot import _META_QUBITS + from iqmapper.plot import _META_QUBITS return next((tr for tr in fig.data if getattr(tr, 'meta', None) == _META_QUBITS), None) @@ -269,17 +269,17 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): np.array([0.01 * (i + 1) for i in range(n)]), np.array([0.001 * (i + 1) for i in range(n - 1)])) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - monkeypatch.setattr("qpu_mapper.connection._check_properties", + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([(i, 0) for i in range(8)], 'chip')) - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = 'ibm_here' @@ -296,7 +296,7 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): b = MapperUIBuilder(state) b.build() - import qpu_mapper.ui as ui_pkg + import iqmapper.ui as ui_pkg real = ui_pkg.build_mapper_ui cap = {} @@ -372,7 +372,7 @@ def test_batch_handoff_keeps_base_map_real_build(monkeypatch): def test_paint_runs_on_main_thread(monkeypatch): b, cap = _primary_with_stubs(monkeypatch) - import qpu_mapper.ui as ui_pkg + import iqmapper.ui as ui_pkg inner = ui_pkg.build_mapper_ui build_threads = [] @@ -390,7 +390,7 @@ def _wrap(s2, is_secondary=False, return_widgets=False): def test_continuation_failure_falls_back_to_staged(monkeypatch): b, cap = _primary_with_stubs(monkeypatch) - import qpu_mapper.ui as ui_pkg + import iqmapper.ui as ui_pkg def _boom_build(*a, **k): raise RuntimeError('build boom') diff --git a/tests/test_inter_qpu_live_model.py b/tests/test_inter_qpu_live_model.py index 70cbd8a..ae4823f 100644 --- a/tests/test_inter_qpu_live_model.py +++ b/tests/test_inter_qpu_live_model.py @@ -80,7 +80,7 @@ def _backend(n): def test_auto_connect_paints_on_main_thread(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu main_thread = threading.current_thread() build_threads = [] @@ -98,12 +98,12 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): plot_h_slider=SimpleNamespace(value=0)) return (full_ui, fig, w2) if return_widgets else (full_ui, fig) - monkeypatch.setattr("qpu_mapper.connection._check_properties", + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'chip_label')) - monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) - monkeypatch.setattr("qpu_mapper.plot.refresh_plot", + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.plot.refresh_plot", lambda fig, st, w: refresh_threads.append( threading.current_thread())) diff --git a/tests/test_inter_qpu_resync.py b/tests/test_inter_qpu_resync.py index dff9eb5..656a34c 100644 --- a/tests/test_inter_qpu_resync.py +++ b/tests/test_inter_qpu_resync.py @@ -18,7 +18,7 @@ def test_resync_helper_snapshots_state(): pytest.importorskip('plotly') import plotly.graph_objects as go - from qpu_mapper.ui.inter_qpu import _resync_widget_state + from iqmapper.ui.inter_qpu import _resync_widget_state fig = go.FigureWidget() fig.add_trace(go.Scatter(x=[1.0, 2.0, 3.0], y=[0.0, 0.0, 0.0], @@ -33,7 +33,7 @@ def test_resync_helper_snapshots_state(): def test_resync_helper_never_raises(): - from qpu_mapper.ui.inter_qpu import _resync_widget_state + from iqmapper.ui.inter_qpu import _resync_widget_state # Non-figure object → the plotly-private attribute access fails; the guard # swallows it and returns False (never fatal to the connect). assert _resync_widget_state(object()) is False @@ -97,14 +97,14 @@ def _sync_spawn(fn, on_done=None, on_error=None): def test_paint_resyncs_before_mount(monkeypatch): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu events = [] def _rec_resync(fig): events.append(('resync', fig)) return True - monkeypatch.setattr("qpu_mapper.ui.inter_qpu._resync_widget_state", + monkeypatch.setattr("iqmapper.ui.inter_qpu._resync_widget_state", _rec_resync) def _fake_build(s2, is_secondary=False, return_widgets=False): @@ -118,12 +118,12 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): plot_h_slider=SimpleNamespace(value=0)) return (full_ui, fig, w2) if return_widgets else (full_ui, fig) - monkeypatch.setattr("qpu_mapper.connection._check_properties", + monkeypatch.setattr("iqmapper.connection._check_properties", lambda b, n: (object(), None)) - monkeypatch.setattr("qpu_mapper.constants.resolve_coords", + monkeypatch.setattr("iqmapper.constants.resolve_coords", lambda b: ([], 'chip')) - monkeypatch.setattr("qpu_mapper.ui.build_mapper_ui", _fake_build) - monkeypatch.setattr("qpu_mapper.plot.refresh_plot", lambda fig, st, w: None) + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.plot.refresh_plot", lambda fig, st, w: None) state = SimpleNamespace( available_backends=['ibm_k'], active_backend_name='ibm_here', diff --git a/tests/test_multi_sweep.py b/tests/test_multi_sweep.py index 71b0e92..111745c 100644 --- a/tests/test_multi_sweep.py +++ b/tests/test_multi_sweep.py @@ -1,4 +1,4 @@ -"""Tests for qpu_mapper.multi_sweep — the sequential multi-circuit orchestrator. +"""Tests for iqmapper.multi_sweep — the sequential multi-circuit orchestrator. Offline, deterministic. Two synthetic hosts: * TWO-BLOCK: two disjoint width-8 ladder blocks (ids 0..23 and 24..47), the @@ -10,7 +10,7 @@ import rustworkx -from qpu_mapper.multi_sweep import sweep_multi_circuits, replan_from +from iqmapper.multi_sweep import sweep_multi_circuits, replan_from def _block(base, edges): diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py index 410ec61..95a17d0 100644 --- a/tests/test_multi_sweep_ui.py +++ b/tests/test_multi_sweep_ui.py @@ -67,11 +67,11 @@ def _result(failed_at=None): def _build(monkeypatch, spawn=_sync_spawn): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() # no .coords → Auto allowed state.active_backend_name = "stub" @@ -91,7 +91,7 @@ def _build(monkeypatch, spawn=_sync_spawn): def _patch_engine(monkeypatch, result): - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms seen = {} monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: seen.update(sweep_kwargs=k, sweep_args=a) or result) @@ -184,7 +184,7 @@ def test_multi_sweep_override(monkeypatch): b, state = _build(monkeypatch) result, c0_alt = _result() _patch_engine(monkeypatch, result) - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms calls = [] # replan returns a new result where C0 = the alt and C1 re-swept. new_c0 = _circuit(0, c0_alt, {1: [c0_alt]}) @@ -233,7 +233,7 @@ def qspawn(fn, on_done=None, on_error=None): b, state = _build(monkeypatch, spawn=qspawn) result, _ = _result() _patch_engine(monkeypatch, result) - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms monkeypatch.setattr(ms, 'replan_from', lambda res, i, choice: result) b.btn_lucj_multi_sweep.click() @@ -255,7 +255,7 @@ def test_multi_sweep_kwargs_parity(monkeypatch): result, _ = _result() seen = _patch_engine(monkeypatch, result) local = {} - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **k: local.update(k) or result['circuits'][0] and {'strata': {}, 'k_max_effective': 1, 'min_bridges': 1, 'vf2_truncated': False, 'n_raw_embeddings': 0, @@ -283,7 +283,7 @@ def test_multi_sweep_kwargs_parity(monkeypatch): def test_legacy_multi_button_unchanged(monkeypatch): b, state = _build(monkeypatch) calls = [] - monkeypatch.setattr("qpu_mapper.auto_lucj.get_multi_circuit_layouts", + monkeypatch.setattr("iqmapper.auto_lucj.get_multi_circuit_layouts", lambda **k: calls.append(k) or [ {'circuit_idx': 0, 'norb': 8, 'num_bridges': 2, 'all_candidates': [{'layout': [0, 1, 2, 3], @@ -291,7 +291,7 @@ def test_legacy_multi_button_unchanged(monkeypatch): 'score': 0.03, 'rank': 1, 'layout_full': [0, 1, 2, 3, 4]}]}]) ms_calls = [] - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: ms_calls.append(1) or _result()[0]) diff --git a/tests/test_plot_node_guard.py b/tests/test_plot_node_guard.py index 597545b..631c9db 100644 --- a/tests/test_plot_node_guard.py +++ b/tests/test_plot_node_guard.py @@ -18,9 +18,9 @@ def _fake_device(state, vendor, chip, date, prefetched_props=None): def _build(monkeypatch): - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "stub" @@ -40,13 +40,13 @@ def _build(monkeypatch): def _qubit_trace(fig): - from qpu_mapper.plot import _META_QUBITS + from iqmapper.plot import _META_QUBITS return next(t for t in fig.data if getattr(t, 'meta', None) == _META_QUBITS) def test_refresh_preserves_nodes_when_qubit_ids_empty(monkeypatch, caplog): b = _build(monkeypatch) - from qpu_mapper import plot + from iqmapper import plot qt = _qubit_trace(b.fig) assert len(qt.x) == 8 and len(qt.marker.color) == 8 # nodes present @@ -54,7 +54,7 @@ def test_refresh_preserves_nodes_when_qubit_ids_empty(monkeypatch, caplog): # Emptying qubit_ids while edges remain used to wipe the node colour/text # (positions kept) → invisible nodes, edges drawn. The guard must refuse. b.state.qubit_ids = [] - with caplog.at_level(logging.WARNING, logger='qpu_mapper.plot'): + with caplog.at_level(logging.WARNING, logger='iqmapper.plot'): plot.refresh_plot(b.fig, b.state, b.widgets_ref) assert len(qt.x) == 8 # positions intact @@ -65,7 +65,7 @@ def test_refresh_preserves_nodes_when_qubit_ids_empty(monkeypatch, caplog): def test_refresh_rewrites_node_positions_from_state(monkeypatch): b = _build(monkeypatch) - from qpu_mapper import plot + from iqmapper import plot # Move the device coordinates, then refresh: the node trace x/y must follow # the state (same source), so it can never diverge from what is painted. diff --git a/tests/test_png_colorbars.py b/tests/test_png_colorbars.py index 8ea2933..20745e7 100644 --- a/tests/test_png_colorbars.py +++ b/tests/test_png_colorbars.py @@ -12,8 +12,8 @@ pytest.importorskip('plotly') import plotly.graph_objects as go # noqa: E402 -from qpu_mapper import plot # noqa: E402 (constants + _trace_by_meta only) -from qpu_mapper.ui.png_export import _append_live_colorbars # noqa: E402 +from iqmapper import plot # noqa: E402 (constants + _trace_by_meta only) +from iqmapper.ui.png_export import _append_live_colorbars # noqa: E402 def _cb_trace(meta, *, showscale, cmin, cmax, title): @@ -85,7 +85,7 @@ def _walk(node): def test_export_site_invokes_helper(monkeypatch, tmp_path): from ipywidgets import Text, Button, HTML, Output, Layout - from qpu_mapper.ui import png_export as pe + from iqmapper.ui import png_export as pe events = [] diff --git a/tests/test_props_shim.py b/tests/test_props_shim.py index 7b22230..37df7f7 100644 --- a/tests/test_props_shim.py +++ b/tests/test_props_shim.py @@ -1,4 +1,4 @@ -"""Tests for qpu_mapper.props_shim — the cache-aware props adapter. +"""Tests for iqmapper.props_shim — the cache-aware props adapter. t1 (the crux): CachedPropsShim built from B0.a-shaped dicts answers readout_error(q) and gate_error(name, pair) for both edge orders, and @@ -10,7 +10,7 @@ import numpy as np import pytest -from qpu_mapper.props_shim import CachedPropsShim, make_scan_get_props +from iqmapper.props_shim import CachedPropsShim, make_scan_get_props def _fixtures(): @@ -98,7 +98,7 @@ def gate_error(self, gate_name, edge): def test_remote_scoring_is_live_never_cache_read(monkeypatch): from datetime import datetime - from qpu_mapper import data + from iqmapper import data reads, saves, fetched = [], [], [] monkeypatch.setattr(data, 'list_known_calibrations', lambda *a, **k: reads.append('list') or []) @@ -136,7 +136,7 @@ def test_active_backend_uses_state_props_not_cache(monkeypatch): properties=lambda: (_ for _ in ()).throw( AssertionError("must not fetch live for active backend"))) - from qpu_mapper import data + from iqmapper import data cache_calls = [] monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: cache_calls.append(name) or []) @@ -153,7 +153,7 @@ def test_active_backend_uses_state_props_not_cache(monkeypatch): assert props.vintage == 'live' # Score equals the C1 wrapper on the same fixture (identical data path). - from qpu_mapper.export.scoring import estimate_circuit_fidelity + from iqmapper.export.scoring import estimate_circuit_fidelity st = SimpleNamespace( layouts_data={0: {'alpha': ['0', '1'], 'beta': ['2', '3'], 'other': [], 'ancilla': []}}, @@ -166,7 +166,7 @@ def test_active_backend_uses_state_props_not_cache(monkeypatch): # ── a fetch failure raises (no cached fallback) ────────────────────── def test_remote_fetch_failure_raises_no_cache_fallback(monkeypatch): - from qpu_mapper import data + from iqmapper import data # A cached snapshot EXISTS, but it must NOT be used as a fallback. monkeypatch.setattr(data, 'list_known_calibrations', lambda *a, **k: [{'last_update': '2026-07-05 08:00:00'}]) @@ -216,7 +216,7 @@ def test_qubit_length_mismatch_raises(): # ── end-to-end pin — shim score == core hand-built from same snapshot ─ def test_shim_score_matches_core_handbuilt(): - from qpu_mapper.export.scoring import estimate_fidelity_core + from iqmapper.export.scoring import estimate_fidelity_core qp = {'readout_error': [0.01, 0.02, 0.03, 0.04]} gp = {'cz_error': [0.001, 0.002, 1.0]} # (2,3) dead edges = [(0, 1), (1, 2), (2, 3)] @@ -236,7 +236,7 @@ def test_shim_score_matches_core_handbuilt(): # ── SYM-1 t1: score_layout scores the FULL directed surface (== C1 core) ───── def test_score_layout_full_directed_surface(): - from qpu_mapper.export.scoring import estimate_fidelity_core + from iqmapper.export.scoring import estimate_fidelity_core # Bidirectional coupling map + an INCIDENTAL edge (0,2) among the set # (not on the chain path) carrying a large error. edges = [(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)] diff --git a/tests/test_qpu_scan.py b/tests/test_qpu_scan.py index 9f86f61..7eeb85f 100644 --- a/tests/test_qpu_scan.py +++ b/tests/test_qpu_scan.py @@ -1,4 +1,4 @@ -"""Tests for qpu_mapper.qpu_scan — the multi-QPU scan engine. +"""Tests for iqmapper.qpu_scan — the multi-QPU scan engine. Offline, deterministic, no qiskit, no network. Fake backends are SimpleNamespaces exposing exactly what family/size detection reads @@ -9,7 +9,7 @@ import pytest -from qpu_mapper.qpu_scan import list_scan_targets, scan_qpus +from iqmapper.qpu_scan import list_scan_targets, scan_qpus def _mk_backend(name, family, n_qubits): @@ -85,7 +85,7 @@ def test_scan_happy_path_sorted_and_progress(monkeypatch): def fake_sweep(norb, backend, props, **kw): return _canned_sweep({2: [_entry(scores[backend.name], 2)]}) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", fake_sweep) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", fake_sweep) backends = {'ibm_a': _mk_backend('ibm_a', 'Heron', 156), 'ibm_b': _mk_backend('ibm_b', 'Heron', 156)} @@ -113,7 +113,7 @@ def fake_sweep(norb, backend, props, **kw): def test_scan_isolation_on_props_failure(monkeypatch): monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, backend, props, **kw: _canned_sweep({2: [_entry(0.4, 2)]})) backends = {'ibm_a': _mk_backend('ibm_a', 'Heron', 156), @@ -149,7 +149,7 @@ def test_best_lqs_extraction(monkeypatch): 1: [_entry(0.90, 1)], } monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, backend, props, **kw: _canned_sweep(strata)) out = scan_qpus( @@ -174,7 +174,7 @@ def test_scan_skips_ineligible_targets(monkeypatch): """Ineligible targets are skipped (never swept), counted in n_skipped.""" called = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: called.append(1) or _canned_sweep({2: [_entry(0.4, 2)]})) targets = [{'name': 'ibm_x', 'family': 'Nighthawk', 'eligible': False, @@ -220,7 +220,7 @@ def test_sweep_fn_none_uses_sweep_ancilla_layouts(monkeypatch): """sweep_fn=None (default) is byte-compatible: the built-in sweep runs.""" seen = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, b, p, **k: seen.append(k) or _canned_sweep({1: [{'product_score': 0.4}]})) out = scan_qpus([{'name': 'a', 'family': 'H', 'eligible': True}], 6, get_backend=lambda n: SimpleNamespace(name=n), diff --git a/tests/test_scan_notices.py b/tests/test_scan_notices.py index 30c835d..e3c0c5b 100644 --- a/tests/test_scan_notices.py +++ b/tests/test_scan_notices.py @@ -38,12 +38,12 @@ def _sweep(k_max_effective=1): def _build(monkeypatch): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "stub" @@ -63,7 +63,7 @@ def _build(monkeypatch): def _patch_targets(monkeypatch, names=('ibm_a',)): - import qpu_mapper.qpu_scan as qs + import iqmapper.qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} for n in names]) @@ -71,8 +71,8 @@ def _patch_targets(monkeypatch, names=('ibm_a',)): def _patch_engine(monkeypatch, sweep_fn): """Drive _scan_backends: per-target sweep + a stub props factory.""" - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", sweep_fn) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", sweep_fn) + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: SimpleNamespace( vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) @@ -117,8 +117,8 @@ def test_k_not_capped_no_note(monkeypatch): def test_notices_capture_and_dedup(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - import qpu_mapper.qpu_scan as qs - lg = logging.getLogger('qpu_mapper') + import iqmapper.qpu_scan as qs + lg = logging.getLogger('iqmapper') def sweep_warns(norb, backend, props, **kw): # Runs while _scan['current'] == 'ibm_a' (set by the 'start' event). @@ -142,7 +142,7 @@ def sweep_warns(norb, backend, props, **kw): def test_logger_restored_after_scan(monkeypatch): b = _build(monkeypatch) _patch_targets(monkeypatch) - lg = logging.getLogger('qpu_mapper') + lg = logging.getLogger('iqmapper') h0, p0 = list(lg.handlers), lg.propagate _patch_engine(monkeypatch, lambda *a, **k: _sweep()) diff --git a/tests/test_scan_targets_line.py b/tests/test_scan_targets_line.py index 1d031a2..0d8caaa 100644 --- a/tests/test_scan_targets_line.py +++ b/tests/test_scan_targets_line.py @@ -18,12 +18,12 @@ def _noop_spawn(fn, on_done=None, on_error=None): def _build(monkeypatch, active='ibm_boston'): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _noop_spawn) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - monkeypatch.setattr("qpu_mapper.qpu_scan._detect_family", lambda b: 'Heron') - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + monkeypatch.setattr("iqmapper.qpu_scan._detect_family", lambda b: 'Heron') + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = active @@ -50,7 +50,7 @@ def _targets_html(b): def test_targets_line_compact_mixed(monkeypatch): b, state = _build(monkeypatch, active='ibm_boston') - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_pittsburgh', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_fez', 'family': 'Heron', 'eligible': True, 'reason': None}, @@ -74,7 +74,7 @@ def test_targets_line_compact_mixed(monkeypatch): def test_short_reasons_mapped(monkeypatch): b, state = _build(monkeypatch, active='none') - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_ok', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_small', 'family': 'Heron', 'eligible': False, @@ -96,7 +96,7 @@ def test_short_reasons_mapped(monkeypatch): def test_targets_line_none(monkeypatch): b, state = _build(monkeypatch, active='none') - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Nighthawk', 'eligible': False, 'reason': 'different family (Nighthawk)'}, @@ -113,7 +113,7 @@ def test_targets_line_none(monkeypatch): def test_targets_line_escapes_name(monkeypatch): b, state = _build(monkeypatch, active='none') - from qpu_mapper import qpu_scan as qs + from iqmapper import qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': '', 'family': 'Heron', 'eligible': True, 'reason': None}]) diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index faf7f2e..2e32ff3 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -10,7 +10,7 @@ import numpy as np -from qpu_mapper.ui.lucj_panel import _format_sweep_status +from iqmapper.ui.lucj_panel import _format_sweep_status def _fake_device_data(state, vendor, chip, date, prefetched_props=None): @@ -72,14 +72,14 @@ def _targets(): def _build(monkeypatch, spawn=_sync_spawn, marshal=None): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) if marshal is not None: monkeypatch.setattr(au, 'marshal_to_main', marshal) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() @@ -102,9 +102,9 @@ def _build(monkeypatch, spawn=_sync_spawn, marshal=None): def _patch_scan(monkeypatch, sweeps=None, props=None, targets=None): """Drive _scan_backends: canned per-target sweep + stub props factory.""" - import qpu_mapper.qpu_scan as qs - import qpu_mapper.ancilla_sweep as asw - import qpu_mapper.props_shim as ps + import iqmapper.qpu_scan as qs + import iqmapper.ancilla_sweep as asw + import iqmapper.props_shim as ps monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: targets or _targets()) sweeps = sweeps or {'ibm_b': _sweep(0.60, 0.50), 'ibm_a': _sweep(0.40, 0.30), @@ -290,10 +290,10 @@ def test_scan_live_vintage(monkeypatch): def test_scan_fetch_failure_error_row(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _sweep(0.6, 0.5)) def get_props(state): @@ -302,7 +302,7 @@ def gp(backend): raise RuntimeError("network down fetching calibration") return _StubProps(0.6, 'live · 09:30') return gp - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", get_props) + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", get_props) b.btn_scan_qpus.click() assert 'network down' in _detail_by_name(b, 'ibm_a') # honest error row @@ -312,7 +312,7 @@ def gp(backend): # ── stability filter still reads the cache for HISTORY ──────────────── def test_stability_history_reads_cache(monkeypatch): - from qpu_mapper.state import SessionState + from iqmapper.state import SessionState b = _build(monkeypatch, marshal=lambda cb: cb()) # Enable the filter (needs local history available) + the scan sub-filter. b.state.cal_history_dates = ['2026-07-01'] @@ -322,18 +322,18 @@ def test_stability_history_reads_cache(monkeypatch): b.chk_stability_filter.value = True b.chk_scan_stability.value = True - from qpu_mapper import data + from iqmapper import data loads = [] monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: [{'last_update': '2026-07-05 08:00:00'}]) monkeypatch.setattr(data, '_load_calibration', lambda name, ts: loads.append(name) or ({'readout_error': [0.01] * 8}, {'cz_error': [0.001] * 7})) - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: {**_sweep(0.6, 0.5), 'stability': {'available': True}}) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: _StubProps(0.6, 'live · 09:30'))) b.btn_scan_qpus.click() @@ -347,11 +347,11 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) calls = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: _targets()) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: _StubProps(0.6))) b.chk_deep_search.value = False # a non-default value @@ -381,12 +381,12 @@ def test_active_backend_skipped_with_reference(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) swept = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **kw: swept.append(bk.name) or _sweep(0.6, 0.5)) - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'stub', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: _StubProps(0.6))) b.btn_scan_qpus.click() @@ -403,11 +403,11 @@ def test_scan_honors_hybrid_checkbox(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) calls = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: _targets()) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: _StubProps(0.6))) b.chk_deep_search.value = True @@ -424,11 +424,11 @@ def _scan_html(b): def _patch_one_target(monkeypatch, sweep, props_obj): - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: sweep) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: props_obj)) diff --git a/tests/test_scan_ui_pass.py b/tests/test_scan_ui_pass.py index 24cb211..593adfc 100644 --- a/tests/test_scan_ui_pass.py +++ b/tests/test_scan_ui_pass.py @@ -64,12 +64,12 @@ def score_layout(self, qubits): def _build(monkeypatch, spawn=_sync_spawn, marshal=lambda cb: cb()): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) monkeypatch.setattr(au, 'marshal_to_main', marshal) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "stub" # NOT a target → no ref row @@ -89,11 +89,11 @@ def _build(monkeypatch, spawn=_sync_spawn, marshal=lambda cb: cb()): def _patch_one(monkeypatch, sweep, props_obj, name='ibm_a'): - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': name, 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: sweep) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: props_obj)) diff --git a/tests/test_scoring_core.py b/tests/test_scoring_core.py index ea87c69..c7fe868 100644 --- a/tests/test_scoring_core.py +++ b/tests/test_scoring_core.py @@ -8,10 +8,10 @@ import numpy as np import pytest -from qpu_mapper.export.scoring import ( +from iqmapper.export.scoring import ( estimate_circuit_fidelity, estimate_fidelity_core, ) -from qpu_mapper.props_shim import CachedPropsShim +from iqmapper.props_shim import CachedPropsShim # ── C1 pin — behaviour unchanged across the refactor-extract ──────────── diff --git a/tests/test_shuffle_search.py b/tests/test_shuffle_search.py index 40f1c07..8bc7673 100644 --- a/tests/test_shuffle_search.py +++ b/tests/test_shuffle_search.py @@ -14,7 +14,7 @@ import rustworkx -from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.ancilla_sweep import sweep_ancilla_layouts NORB = 8 CAP = 2 # smaller than block A's embedding count → truncates diff --git a/tests/test_stability_filter.py b/tests/test_stability_filter.py index 3c3fe99..44f9f96 100644 --- a/tests/test_stability_filter.py +++ b/tests/test_stability_filter.py @@ -1,4 +1,4 @@ -"""Tests for qpu_mapper.stability_filter — the stability-aware sweep. +"""Tests for iqmapper.stability_filter — the stability-aware sweep. Offline, deterministic. Two disconnected width-8 heavy-hex-like blocks (the norb=8 host from the sweep tests): block A = ids 0..23, block B = @@ -10,8 +10,8 @@ import rustworkx -from qpu_mapper.ancilla_sweep import sweep_ancilla_layouts -from qpu_mapper.stability_filter import ( +from iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.stability_filter import ( compute_qubit_volatility, select_excluded, select_quality_floor, sweep_with_stability, ) diff --git a/tests/test_stability_ui.py b/tests/test_stability_ui.py index 887184f..f7cc7af 100644 --- a/tests/test_stability_ui.py +++ b/tests/test_stability_ui.py @@ -59,13 +59,13 @@ def _detail_by_name(b, name): def _build(monkeypatch, *, history=False, spawn=_sync_spawn, marshal=lambda cb: cb()): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', spawn) monkeypatch.setattr(au, 'marshal_to_main', marshal) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() @@ -118,9 +118,9 @@ def fake_sws(norb, backend, props, hist, **kw): return _canned_res({'available': True, 'relaxed': False, 'excluded_final': [1, 2, 3], 'window_days': kw.get('window_days')}) - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", fake_sws) + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", fake_sws) plain = [] - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: plain.append(1) or _canned_res(None)) b.chk_stability_filter.value = True @@ -138,7 +138,7 @@ def fake_sws(norb, backend, props, hist, **kw): def test_banner_states(monkeypatch): b = _build(monkeypatch, history=True) holder = {} - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: _canned_res(holder['stab'])) b.chk_stability_filter.value = True @@ -166,11 +166,11 @@ def test_scan_stability_badges(monkeypatch): b.chk_stability_filter.value = True # enabled (history available) b.chk_scan_stability.value = True # filter the scan too - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) # ibm_a has CACHED history, ibm_b does not. - from qpu_mapper import data + from iqmapper import data monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: [{'last_update': '2026-07-05 08:00:00'}] if name == 'ibm_a' else []) monkeypatch.setattr(data, '_load_calibration', lambda name, ts: @@ -178,11 +178,11 @@ def test_scan_stability_badges(monkeypatch): # ibm_a → filtered (excluded_final); ibm_b → plain sweep. filt = dict(_canned_res({'available': True, 'relaxed': False, 'excluded_final': [3, 4], 'window_days': 14})) - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: filt) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned_res(None)) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: SimpleNamespace( vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) @@ -197,10 +197,10 @@ def test_filter_off_uses_plain_sweep(monkeypatch): b = _build(monkeypatch, history=True) plain = [] - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: plain.append(1) or _canned_res(None)) sws = [] - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: sws.append(1) or _canned_res({'available': True})) assert b.chk_stability_filter.value is False # default OFF @@ -215,7 +215,7 @@ def test_filter_off_uses_plain_sweep(monkeypatch): def test_banner_counts_volatile_and_outlier(monkeypatch): b = _build(monkeypatch, history=True) monkeypatch.setattr( - "qpu_mapper.stability_filter.sweep_with_stability", + "iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: _canned_res({ 'available': True, 'relaxed': False, 'excluded_final': [1, 2, 3, 4, 5], # 5 total @@ -230,7 +230,7 @@ def test_banner_counts_volatile_and_outlier(monkeypatch): def test_banner_no_outlier_suffix_when_floor_empty(monkeypatch): b = _build(monkeypatch, history=True) monkeypatch.setattr( - "qpu_mapper.stability_filter.sweep_with_stability", + "iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: _canned_res({ 'available': True, 'relaxed': False, 'excluded_final': [1, 2], 'n_floor_excluded': 0, @@ -249,11 +249,11 @@ def test_scan_filtered_per_backend_isolation(monkeypatch): b.chk_scan_stability.value = True # ibm_c (the MIDDLE target) blows up during history assembly; the loop # must survive so ibm_b (after it) still completes. - monkeypatch.setattr("qpu_mapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_c', 'family': 'Heron', 'eligible': True, 'reason': None}, {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) - from qpu_mapper import data + from iqmapper import data monkeypatch.setattr(data, 'list_known_calibrations', lambda name, date=None: [{'last_update': '2026-07-05 08:00:00'}] if name in ('ibm_a', 'ibm_c') else []) @@ -266,11 +266,11 @@ def _load(name, ts): filt = dict(_canned_res({'available': True, 'relaxed': False, 'excluded_final': [3, 4], 'window_days': 14})) - monkeypatch.setattr("qpu_mapper.stability_filter.sweep_with_stability", + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", lambda *a, **k: filt) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned_res(None)) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state: (lambda backend: SimpleNamespace( vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) diff --git a/tests/test_subpanel_persistence.py b/tests/test_subpanel_persistence.py index e2f42f4..e6de83d 100644 --- a/tests/test_subpanel_persistence.py +++ b/tests/test_subpanel_persistence.py @@ -55,12 +55,12 @@ def _mresult(): def _build(monkeypatch): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() # no .coords → Auto allowed state.active_backend_name = "ibm_here" @@ -83,7 +83,7 @@ def _build(monkeypatch): def test_multi_generate_keeps_multi_subpanel(monkeypatch): b, state = _build(monkeypatch) - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) b.intra_qpu_mode.value = True # reveal the Multi subpanel @@ -188,7 +188,7 @@ def _on_multi(b): def test_multi_generate_no_rebuild(monkeypatch): b, state = _build(monkeypatch) - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) tab_before = _on_multi(b) content_before = b.content_box.children[0] @@ -207,7 +207,7 @@ def test_multi_generate_no_rebuild(monkeypatch): def test_multi_generate_targeted_widgets_refreshed(monkeypatch): b, state = _build(monkeypatch) - import qpu_mapper.multi_sweep as ms + import iqmapper.multi_sweep as ms monkeypatch.setattr(ms, 'sweep_multi_circuits', lambda *a, **k: _mresult()) _on_multi(b) @@ -242,7 +242,7 @@ def test_checkbox_toggle_still_rebuilds(monkeypatch): def test_legacy_multi_generate_no_rebuild(monkeypatch): b, state = _build(monkeypatch) monkeypatch.setattr( - "qpu_mapper.auto_lucj.get_multi_circuit_layouts", + "iqmapper.auto_lucj.get_multi_circuit_layouts", lambda **k: [ {'circuit_idx': i, 'norb': 8, 'num_bridges': 0, 'all_candidates': [{'layout': [0, 1, 2, 3], 'alpha': [0, 1], diff --git a/tests/test_sweep_notices.py b/tests/test_sweep_notices.py index 2fa2d49..20bbb73 100644 --- a/tests/test_sweep_notices.py +++ b/tests/test_sweep_notices.py @@ -1,6 +1,6 @@ """NOTICE CAPTURE FOR ALL SWEEP PATHS. -The scan already captured qpu_mapper WARNING+ into its loud '⚠ notices' bar via +The scan already captured iqmapper WARNING+ into its loud '⚠ notices' bar via a scoped handler. These tests pin the SAME capture for the LOCAL sweep and the MULTI sweep + replan: warnings render into the respective notices widget, deduplicate (message ×count), and NEVER leak to the root logger (propagate is @@ -11,7 +11,7 @@ import numpy as np -_QLOG = 'qpu_mapper' +_QLOG = 'iqmapper' def _fake_device_data(state, vendor, chip, date, prefetched_props=None): @@ -58,12 +58,12 @@ def _multi_result(): def _build(monkeypatch): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "ibm_here" @@ -94,7 +94,7 @@ def emit(self, record): def _capture_handlers(): - from qpu_mapper.ui.lucj_panel import _ScanNoticeCapture + from iqmapper.ui.lucj_panel import _ScanNoticeCapture return [h for h in logging.getLogger(_QLOG).handlers if isinstance(h, _ScanNoticeCapture)] @@ -111,7 +111,7 @@ def test_local_sweep_notice_captured_not_leaked(monkeypatch): def warn_sweep(norb, backend, props, **kw): lg.warning("Requested 6 bridges does not fit; falling back") return _sweep() - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", warn_sweep) b.lucj_ancilla_dd.value = -1 # Auto → stratified sweep path @@ -140,7 +140,7 @@ def warn_sweep(norb, backend, props, **kw): lg.warning("vf2 truncating to 2000") lg.warning("bridge fallback") return _sweep() - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", warn_sweep) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", warn_sweep) b.lucj_ancilla_dd.value = -1 b.btn_lucj_run.click() @@ -165,7 +165,7 @@ def test_local_sweep_restores_on_error(monkeypatch): def boom_sweep(norb, backend, props, **kw): lg.warning("partial notice before the crash") raise RuntimeError("sweep exploded") - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", boom_sweep) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", boom_sweep) b.lucj_ancilla_dd.value = -1 b.btn_lucj_run.click() # handler catches → error banner @@ -183,7 +183,7 @@ def test_multi_sweep_restores_on_error(monkeypatch): def boom_multi(*a, **k): lg.warning("multi partial notice") raise RuntimeError("multi exploded") - monkeypatch.setattr("qpu_mapper.multi_sweep.sweep_multi_circuits", boom_multi) + monkeypatch.setattr("iqmapper.multi_sweep.sweep_multi_circuits", boom_multi) b.lucj_multi_norbs.value = "8" b.btn_lucj_multi_sweep.click() @@ -203,7 +203,7 @@ def warn_multi(*a, **k): lg.warning("Requested 6 bridges does not fit; falling back") lg.warning("Requested 6 bridges does not fit; falling back") return _multi_result() - monkeypatch.setattr("qpu_mapper.multi_sweep.sweep_multi_circuits", warn_multi) + monkeypatch.setattr("iqmapper.multi_sweep.sweep_multi_circuits", warn_multi) b.lucj_multi_norbs.value = "8" b.btn_lucj_multi_sweep.click() diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index 39350d8..9bc6574 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -24,9 +24,9 @@ def _fake_device_data(state, vendor, chip, date, prefetched_props=None): @pytest.fixture def builder(monkeypatch): - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() # non-None, and NO .coords attr @@ -86,7 +86,7 @@ def entry(anc, prod, add, src): # ── label/status formatters prefer circuit-level LQS ───────────────── def test_formatters_use_lqs_circuit(): - from qpu_mapper.ui.lucj_panel import _entry_lqs_pct, _format_best_per_k + from iqmapper.ui.lucj_panel import _entry_lqs_pct, _format_best_per_k circ = {'product_score': 0.30, 'lqs_circuit': 0.42, 'ancillas': [4]} pct, is_tmpl = _entry_lqs_pct(circ) @@ -107,7 +107,7 @@ def test_formatters_use_lqs_circuit(): def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): calls = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: (calls.append((a, k)) or _fake_sweep_result())) b = builder @@ -152,7 +152,7 @@ def entry(kk, rank): # numbers were taken at different moments), not a bug. def test_local_sweep_status_shows_live_vintage(builder, monkeypatch): - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _fake_sweep_result()) b = builder b.btn_lucj_run.click() @@ -164,7 +164,7 @@ def test_local_sweep_status_shows_live_vintage(builder, monkeypatch): def test_local_sweep_status_vintage_uses_past_date(builder, monkeypatch): - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _fake_sweep_result()) b = builder # A selected PAST date → the vintage names that date, not live. @@ -178,7 +178,7 @@ def test_local_sweep_status_vintage_uses_past_date(builder, monkeypatch): def test_top_n_field_controls_dropdown_entries(builder, monkeypatch): - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", _fake_sweep_topn) b = builder b.lucj_top_n.value = 7 # Show top = 7 @@ -195,14 +195,14 @@ def test_top_n_field_controls_dropdown_entries(builder, monkeypatch): def test_legacy_mode_skips_sweep(builder, monkeypatch): sweep_calls, legacy_calls = [], [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: sweep_calls.append(1) or _fake_sweep_result()) def fake_legacy(*a, **k): legacy_calls.append((a, k)) return ([{'alpha': [0, 1], 'beta': [2, 3], 'score': 0.05, 'rank': 1}], 2) monkeypatch.setattr( - "qpu_mapper.auto_lucj.get_all_zigzag_layouts", fake_legacy) + "iqmapper.auto_lucj.get_all_zigzag_layouts", fake_legacy) b = builder b.lucj_ancilla_dd.value = 2 # exact count → legacy @@ -218,7 +218,7 @@ def fake_legacy(*a, **k): def test_apply_derived_candidate_places_chains_and_ancillas(builder, monkeypatch): monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _fake_sweep_result()) b = builder @@ -243,7 +243,7 @@ def test_apply_derived_candidate_places_chains_and_ancillas(builder, monkeypatch def test_truncation_banner(builder, monkeypatch): monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _fake_sweep_result(vf2_truncated=True)) b = builder b.btn_lucj_run.click() @@ -254,7 +254,7 @@ def test_truncation_banner(builder, monkeypatch): # False → hidden (empty). monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _fake_sweep_result(vf2_truncated=False)) b.btn_lucj_run.click() assert b.lbl_lucj_trunc.value == "" @@ -267,7 +267,7 @@ def boom(*a, **k): raise ValueError("min_bridges=99 out of range; must satisfy " "1 <= min_bridges <= k_max_effective (3).") monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", boom) + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", boom) b = builder b.lucj_min_ancilla.value = 99 @@ -284,7 +284,7 @@ def boom(*a, **k): def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): calls = [] monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: (calls.append(k) or _fake_sweep_result())) b = builder b.chk_deep_search.value = False @@ -296,7 +296,7 @@ def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): def test_sweep_mode_label(): - from qpu_mapper.ui.lucj_panel import _sweep_mode_label + from iqmapper.ui.lucj_panel import _sweep_mode_label hy = {'k_max_effective': 3, 'per_stratum': {3: {'n_direct': 5, 'n_derived': 0}, 2: {'n_direct': 2, 'n_derived': 3}, @@ -328,7 +328,7 @@ def e(anc, prod, diverse): 'truncated': False, 'shuffled': False}}, 'mapping_cap': 2000, } - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", _fake) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", _fake) b = builder b.btn_lucj_run.click() labels = _labels(b.dd_lucj_layout) diff --git a/tests/test_temporal_anchoring.py b/tests/test_temporal_anchoring.py index cf8b2ff..cc7bbaa 100644 --- a/tests/test_temporal_anchoring.py +++ b/tests/test_temporal_anchoring.py @@ -13,7 +13,7 @@ import numpy as np import rustworkx -from qpu_mapper.stability_filter import ( +from iqmapper.stability_filter import ( compute_qubit_volatility, sweep_with_stability, ) @@ -127,12 +127,12 @@ def _canned(): def _build(monkeypatch, *, past_date=None): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = SimpleNamespace(name='ibm_here') state.active_backend_name = "ibm_here" @@ -170,7 +170,7 @@ def test_prerank_uses_selected_date_not_live_props(monkeypatch): b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') captured = {} monkeypatch.setattr( - "qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda norb, bk, pr, **kw: captured.update(props=pr) or _canned()) b.btn_lucj_run.click() @@ -187,15 +187,15 @@ def test_prerank_uses_selected_date_not_live_props(monkeypatch): def test_scan_header_notes_epoch_mix_on_past_date(monkeypatch): b, state = _build(monkeypatch, past_date='2026-07-01 08:00:00') - import qpu_mapper.qpu_scan as qs + import iqmapper.qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state, **k: (lambda backend: SimpleNamespace( vintage='live · 09:30', score_layout=lambda q: {'fidelity': 0.5}))) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned()) b.btn_scan_qpus.click() @@ -207,15 +207,15 @@ def test_scan_header_notes_epoch_mix_on_past_date(monkeypatch): def test_scan_header_absent_in_live_mode(monkeypatch): b, state = _build(monkeypatch, past_date=None) # live - import qpu_mapper.qpu_scan as qs + import iqmapper.qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, 'reason': None}]) - monkeypatch.setattr("qpu_mapper.props_shim.make_scan_get_props", + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", lambda state, **k: (lambda backend: SimpleNamespace( vintage='live · 09:30', score_layout=lambda q: {'fidelity': 0.5}))) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned()) b.btn_scan_qpus.click() diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py index afdaa46..33ccb72 100644 --- a/tests/test_ui_cleanup.py +++ b/tests/test_ui_cleanup.py @@ -42,12 +42,12 @@ def _canned(): def _build(monkeypatch): - import qpu_mapper.async_util as au + import iqmapper.async_util as au monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) - monkeypatch.setattr("qpu_mapper.data.generate_device_data", _fake_device_data) - from qpu_mapper.state import SessionState - from qpu_mapper.ui.builder import MapperUIBuilder + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder state = SessionState() state.active_backend = object() state.active_backend_name = "ibm_here" @@ -84,7 +84,7 @@ def test_local_block_above_scan(monkeypatch): def test_clear_scan_results(monkeypatch): b = _build(monkeypatch) - import qpu_mapper.qpu_scan as qs + import iqmapper.qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, 'reason': None}]) @@ -106,7 +106,7 @@ def test_clear_scan_results(monkeypatch): def test_new_scan_auto_clears(monkeypatch): b = _build(monkeypatch) - import qpu_mapper.qpu_scan as qs + import iqmapper.qpu_scan as qs monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ {'name': 'ibm_other', 'family': 'Heron', 'eligible': True, 'reason': None}]) @@ -165,7 +165,7 @@ def _inter_ctx(): def test_staged_banner_then_cleared_on_connect(): - from qpu_mapper.ui.inter_qpu import setup_inter_qpu + from iqmapper.ui.inter_qpu import setup_inter_qpu ctx, state = _inter_ctx() setup_inter_qpu(ctx) stage = ctx.handoff_cell[0] @@ -185,7 +185,7 @@ def test_staged_banner_then_cleared_on_connect(): def test_label_disambiguation(monkeypatch): b = _build(monkeypatch) - monkeypatch.setattr("qpu_mapper.ancilla_sweep.sweep_ancilla_layouts", + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", lambda *a, **k: _canned()) b.lucj_ancilla_dd.value = -1 # sweep mode b.btn_lucj_run.click() From 81c79fbffc4d0a1d26fe76a05965d53fe0ef89c4 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Fri, 18 Sep 2026 16:35:36 -0400 Subject: [PATCH 29/66] Inter-QPU: dispose the previous QPU-2 widget tree on reconnect (fix leak) --- iqmapper/ui/inter_qpu.py | 10 ++ tests/test_inter_qpu_dispose.py | 213 ++++++++++++++++++++++++++++++++ 2 files changed, 223 insertions(+) create mode 100644 tests/test_inter_qpu_dispose.py diff --git a/iqmapper/ui/inter_qpu.py b/iqmapper/ui/inter_qpu.py index 3624eeb..780b510 100644 --- a/iqmapper/ui/inter_qpu.py +++ b/iqmapper/ui/inter_qpu.py @@ -434,6 +434,16 @@ def _connect_qpu2_paint(backend_name, fetched): _w2[0] = w2 # kept for same-backend repaint _sidebar2[0] = sidebar2 _zoom2[0] = zoom2_bar + # Reconnect: release the PREVIOUS QPU-2 widget tree before installing + # the new disposer. Overwriting without disposing leaked the entire + # prior UI + FigureWidget on every re-connect (observers keep the + # tree alive in ipywidgets' handler lists). + if _dispose2[0] is not None: + try: + _dispose2[0]() + except Exception: # noqa: BLE001 - logged, never fatal + _log.exception( + "QPU2 disposer raised on reconnect; observers may be leaked") _dispose2[0] = lambda: _walk_unobserve_all(full_ui_2) if _qpu2_content_box[0] is not None: diff --git a/tests/test_inter_qpu_dispose.py b/tests/test_inter_qpu_dispose.py new file mode 100644 index 0000000..158afcc --- /dev/null +++ b/tests/test_inter_qpu_dispose.py @@ -0,0 +1,213 @@ +"""Regression tests for the QPU-2 disposer leak on reconnect. + +`_connect_qpu2_paint` installs a disposer (`_dispose2[0]`) that unobserves the +whole secondary widget tree so it can be garbage collected. The toggle-OFF +branch invokes it correctly, but a RECONNECT (QPU-2 already connected, user +picks a different backend) used to overwrite `_dispose2[0]` with the new +disposer WITHOUT invoking the previous one — so the prior UI + FigureWidget +stayed alive in ipywidgets' handler lists and memory grew on every reconnect. + +Observing the fix +----------------- +`_walk_unobserve_all` is a closure defined inside `setup_inter_qpu`, not a +module-level function, so it cannot be monkeypatched directly. Instead the +fake `build_mapper_ui` returns a tree built from `_RecWidget` nodes that record +their own `unobserve_all()` calls. That is the boundary the disposer actually +acts on, so the assertions below exercise the real disposer end to end rather +than a stand-in: "tree N was disposed" is read off the very objects handed to +the connect that built them, which pins the identity the spec asks for. +""" +from types import SimpleNamespace + + +class _RecLabel: + def __init__(self): + self.history = [] + + @property + def value(self): + return self.history[-1] if self.history else '' + + @value.setter + def value(self, v): + self.history.append(v) + + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._handlers = [] + + def observe(self, fn, names=None): + self._handlers.append(fn) + + def on_click(self, fn): + self._click = fn + + +class _RecWidget: + """Widget-shaped node that counts the disposer's unobserve_all() calls.""" + + def __init__(self, children=()): + self.children = list(children) + self.unobserved = 0 + + def unobserve_all(self): + self.unobserved += 1 + + +class _PoisonWidget(_RecWidget): + """A node whose `children` access raises, so the failure escapes + `_walk_unobserve_all` (which only guards the `unobserve_all()` call) and + reaches the reconnect guard under test.""" + + @property + def children(self): + raise RuntimeError("disposer boom") + + @children.setter + def children(self, v): + self._children = v + + +def _ctx(*, spawn): + def _backend(n): + return SimpleNamespace(name=n) + + state = SimpleNamespace( + available_backends=['ibm_a', 'ibm_b'], active_backend_name='ibm_here', + active_service=SimpleNamespace(backend=_backend), + active_ansatz='lucj', current_colorscale='Viridis') + return SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_RecLabel(), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), + full_ui=_Stub(children=[]), + handoff_cell=[None], + spawn_bg=spawn, + ) + + +def _sync_spawn(fn, on_done=None, on_error=None): + """Inline stand-in for default_spawn_bg: fetch and completion both run + here, so a connect is finished by the time the call returns.""" + try: + result = fn() + except Exception as e: # pragma: no cover + if on_error: + on_error(e) + return None + if on_done: + on_done(result) + return None + + +_CAND = {'alpha': [0], 'beta': [1], 'ancillas': [2]} + + +def _install_fakes(monkeypatch, builds, *, sidebar_extra=()): + """Patch the device fetch + UI build out. Every built tree is appended to + `builds`, so a test can point at the exact objects a given connect made.""" + def _fake_build(s2, is_secondary=False, return_widgets=False): + s2.qubit_ids = ['0', '1', '2'] + s2.edges_list = [(0, 1), (1, 2)] + fig = SimpleNamespace() + # Shape mirrors the real build: full_ui.children == [sidebar2, fig_box2] + # and fig_box2.children[1] is the zoom bar. + sidebar2 = _RecWidget(children=list(sidebar_extra)) + fig_box2 = _RecWidget(children=[_RecWidget(), _RecWidget(), fig]) + full_ui = _RecWidget(children=[sidebar2, fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + builds.append(full_ui) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("iqmapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("iqmapper.constants.resolve_coords", + lambda b: ([], 'chip_label')) + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.plot.refresh_plot", + lambda fig, st, w: None) + + +def test_reconnect_disposes_previous_tree(monkeypatch): + """Connecting QPU-2 to a second backend must dispose the FIRST tree.""" + from iqmapper.ui.inter_qpu import setup_inter_qpu + + builds = [] + _install_fakes(monkeypatch, builds) + ctx = _ctx(spawn=_sync_spawn) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_a', _CAND) + assert len(builds) == 1, "first connect did not build a QPU-2 UI" + first_tree = builds[0] + assert first_tree.unobserved == 0, "first connect disposed its own tree" + + ctx.handoff_cell[0]('ibm_b', _CAND) # reconnect, new backend + assert len(builds) == 2, "reconnect did not build a second QPU-2 UI" + second_tree = builds[1] + + # Exactly one disposal, of the FIRST connect's tree (identity: the counter + # lives on that very object), and the live tree is left untouched. + assert first_tree.unobserved == 1, ( + f"previous QPU-2 tree was not disposed on reconnect " + f"(unobserve_all calls: {first_tree.unobserved})") + assert second_tree.unobserved == 0, "reconnect disposed the NEW tree" + assert first_tree is not second_tree + # The walk is recursive, so the children of the dead tree went too. + assert all(c.unobserved == 1 for c in first_tree.children) + assert 'Connected' in ctx.lbl_qpu2_status.value + + +def test_first_connect_does_not_dispose(monkeypatch): + """With no previous tree the guard must not fire (nothing to dispose).""" + from iqmapper.ui.inter_qpu import setup_inter_qpu + + builds = [] + _install_fakes(monkeypatch, builds) + ctx = _ctx(spawn=_sync_spawn) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_a', _CAND) + + assert len(builds) == 1 + assert builds[0].unobserved == 0, "a first connect must dispose nothing" + assert all(c.unobserved == 0 for c in builds[0].children) + assert 'Connected' in ctx.lbl_qpu2_status.value + + +def test_raising_disposer_does_not_break_reconnect(monkeypatch, caplog): + """A disposer that raises is logged, never fatal: the reconnect completes.""" + from iqmapper.ui.inter_qpu import setup_inter_qpu + + builds = [] + # The poison node sits inside sidebar2, which the paint path never walks — + # only the disposer descends that far, so it breaks disposal and nothing else. + _install_fakes(monkeypatch, builds, sidebar_extra=(_PoisonWidget(),)) + ctx = _ctx(spawn=_sync_spawn) + setup_inter_qpu(ctx) + + ctx.handoff_cell[0]('ibm_a', _CAND) + assert len(builds) == 1 + + with caplog.at_level('ERROR', logger='iqmapper.ui.inter_qpu'): + ctx.handoff_cell[0]('ibm_b', _CAND) # disposer raises in here + + # The reconnect still completed: second tree built, figure mounted, status OK. + assert len(builds) == 2, "a raising disposer aborted the reconnect" + assert 'Connected' in ctx.lbl_qpu2_status.value, ( + f"reconnect did not report success: {ctx.lbl_qpu2_status.value!r}") + assert ctx.qpu2_fig_box.children, "new QPU-2 figure was not mounted" + # …and the failure was logged rather than swallowed or propagated. + assert any('disposer raised on reconnect' in r.message + for r in caplog.records), ( + f"disposer failure was not logged: {[r.message for r in caplog.records]}") From b8235cbe60eb9e22c6fa4d6abcf0a31899a98234 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Fri, 18 Sep 2026 17:11:52 -0400 Subject: [PATCH 30/66] Auto panel: Advanced section, diversity on by default, score checkbox only in legacy mode (own Layout) --- iqmapper/ui/builder.py | 34 ++++-- iqmapper/ui/lucj_panel.py | 13 ++- tests/test_auto_panel_ui_polish.py | 170 +++++++++++++++++++++++++++++ tests/test_floor_batch_ui.py | 4 +- tests/test_multi_sweep_ui.py | 4 +- tests/test_scan_ui.py | 5 +- 6 files changed, 211 insertions(+), 19 deletions(-) create mode 100644 tests/test_auto_panel_ui_polish.py diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index fb3b6cd..af9af25 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -1260,25 +1260,42 @@ def _build_auto_lucj_widgets(self, W): description='Search cap:', layout=Layout(width='220px'), style={'description_width': '110px'}, - tooltip='max VF2 mappings enumerated per search — higher = more ' - 'exhaustive, slower') + tooltip='Max VF2 embeddings enumerated per search (default 2000). ' + 'When the cap truncates, the notices bar says so; raise it ' + 'for a more exhaustive (slower) search.') self.lucj_chk_score = Checkbox( value=True, description='Score layouts (pick lowest error)', - layout=W) + # Its OWN Layout, not the shared `W` instance: lucj_panel toggles + # .layout.display on this widget to hide it in sweep mode, and a + # shared Layout would hide every other widget built with W. + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width)) self.chk_deep_search = Checkbox( value=True, description='Deep search per ancilla count', layout=W, tooltip='adds a direct search per k — complete but slower; ' 'off = fast derivation from k_max only') - # Region diversity in the top-N slice. Default OFF. + # Region diversity in the top-N slice. Default ON: it never costs + # quality (ancilla_sweep._select_with_diversity keeps the first + # ceil(top_n/2) slots as the absolute best) and it widens the choice. self.chk_lucj_diverse = Checkbox( - value=False, + value=True, description='Prefer diverse regions', layout=W, - tooltip='reserve top-N slots for layouts from different chip ' - 'regions (Jaccard > 0.8 = same region)') + tooltip="Second half of each stratum's list favors layouts on " + "different chip regions (Jaccard ≤ 0.8). The top half " + "is always the absolute best — diversity never " + "demotes it.") + # Expert knobs, collapsed out of the primary flow (ancilla dropdown + # -> Run). The defaults are right for nearly everyone, and the notices + # bar already reports when the cap truncated a search. + self.lucj_advanced_acc = Accordion( + children=[VBox([self.lucj_search_cap, self.chk_deep_search])], + layout=W) + self.lucj_advanced_acc.set_title(0, '⚙️ Advanced') + self.lucj_advanced_acc.selected_index = None # collapsed on open self.btn_lucj_run = Button( description='🤖 Generate LUCJ Layout', button_style='success', layout=W) @@ -1798,9 +1815,7 @@ def _build_auto_lucj_view(self): self.lucj_ancilla_dd, self.lucj_min_ancilla, self.lucj_top_n, - self.lucj_search_cap, self.lucj_chk_score, - self.chk_deep_search, self.chk_lucj_diverse, self.ft_stability_floor, self.chk_stability_filter, @@ -1810,6 +1825,7 @@ def _build_auto_lucj_view(self): self.lbl_lucj_trunc, self.lbl_lucj_status, self.lbl_lucj_notices, + self.lucj_advanced_acc, HTML("
"), HTML(f"
📍 This backend ({name})
"), diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index e044e3d..4dc0fd3 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -684,17 +684,22 @@ def _on_lucj_generate(b): btn_lucj_run.on_click(_on_lucj_generate) - # ── sweep mode always scores → grey out the score checkbox ──── + # ── sweep mode always scores → hide the score checkbox ─────── def _on_ancilla_mode_change(change=None): # 'Auto' (-1) == sweep mode; the engine always computes LQS there, # so the legacy "Score layouts" toggle is meaningless. sweep_mode = (lucj_ancilla_dd.value is not None and lucj_ancilla_dd.value < 0) lucj_chk_score.disabled = sweep_mode - lucj_chk_score.tooltip = ('Sweep always scores' if sweep_mode - else 'Score layouts (pick lowest error)') + # Hide rather than grey out. 'Auto' is the default, so a permanently + # disabled checkbox was the first thing every user saw. The widget + # stays in the tree (the legacy path still reads .value on run) and + # only its display is toggled. + lucj_chk_score.layout.display = 'none' if sweep_mode else '' + if not sweep_mode: + lucj_chk_score.tooltip = 'Score layouts (pick lowest error)' lucj_ancilla_dd.observe(_on_ancilla_mode_change, names='value') - _on_ancilla_mode_change() # set initial state (default -1 → disabled) + _on_ancilla_mode_change() # set initial state (default -1 → hidden) # ── Multi-QPU scan ───────────────────────────────── btn_scan_qpus = ctx.btn_scan_qpus diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py new file mode 100644 index 0000000..87e1cae --- /dev/null +++ b/tests/test_auto_panel_ui_polish.py @@ -0,0 +1,170 @@ +"""Auto (LUCJ) panel usability polish. + +Three UI-only changes, none of which touch the sweep engines: + + * the expert knobs (search cap + deep search) live in a collapsed + "Advanced" accordion instead of the primary ancilla-dropdown -> Run flow; + * "Prefer diverse regions" ships ON, because diversity only shapes the + second half of each stratum's list (ancilla_sweep._select_with_diversity + keeps the first ceil(top_n/2) slots as the absolute best); + * the legacy "Score layouts" checkbox is hidden in Auto/sweep mode rather + than shown greyed out, since Auto is the default the user lands on. +""" +import numpy as np + + +def _fake_device(state, vendor, chip, date, prefetched_props=None): + n = 8 + return (list(range(n)), [0.0] * n, [(i, i + 1) for i in range(n - 1)], + [str(i) for i in range(n)], + np.array([0.01 * (i + 1) for i in range(n)]), + np.array([0.001 * (i + 1) for i in range(n - 1)])) + + +def _build(monkeypatch): + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + state = SessionState() + state.active_backend = object() + state.active_backend_name = "ibm_here" + state.active_chip = "stub_chip" + state.active_service = None + state.available_backends = [] + state.props_warning = None + state.initial_props = object() + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] + b = MapperUIBuilder(state) + b.build() + return b, state + + +def _descendants(node, seen=None): + """Every widget reachable through .children, root included.""" + if seen is None: + seen = [] + if any(n is node for n in seen): + return seen + seen.append(node) + for c in getattr(node, 'children', ()) or (): + _descendants(c, seen) + return seen + + +def _empty_sweep(): + return {'strata': {}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 0, + 'n_candidates_scored': 0, 'excluded_qubits': [], + 'per_stratum': {}, 'mapping_cap': None} + + +# ── t1: the expert knobs are collapsed out of the primary flow ────────────── + +def test_search_cap_and_deep_search_live_in_advanced_accordion(monkeypatch): + b, _ = _build(monkeypatch) + + acc = b.lucj_advanced_acc + assert acc.get_title(0) == '⚙️ Advanced' + assert acc.selected_index is None, "Advanced must render collapsed" + + inside = _descendants(acc) + assert any(w is b.lucj_search_cap for w in inside), "cap not in Advanced" + assert any(w is b.chk_deep_search for w in inside), "deep search not in Advanced" + + # The Auto controls box mounts the accordion, not the two widgets directly. + b._build_auto_lucj_view() + single = b._auto_single_panel + assert any(c is acc for c in single.children), "Advanced not mounted" + assert not any(c is b.lucj_search_cap for c in single.children) + assert not any(c is b.chk_deep_search for c in single.children) + # The primary flow is untouched. + assert any(c is b.lucj_ancilla_dd for c in single.children) + assert any(c is b.btn_lucj_run for c in single.children) + # Defaults unchanged by the move. + assert b.lucj_search_cap.value == 2000 + assert b.chk_deep_search.value is True + + +# ── t2: diversity ships ON and still reaches the engine both ways ─────────── + +def test_diverse_default_on(monkeypatch): + b, _ = _build(monkeypatch) + assert b.chk_lucj_diverse.value is True, "diversity must default ON" + + seen = {} + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **k: (seen.update(k), _empty_sweep())[1]) + + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() + assert seen['diversity_threshold'] == 0.8, ( + f"default-on diversity did not reach the engine: {seen.get('diversity_threshold')!r}") + + seen.clear() + b.chk_lucj_diverse.value = False + b.btn_lucj_run.click() + assert seen['diversity_threshold'] is None, ( + f"unticking diversity did not disable it: {seen.get('diversity_threshold')!r}") + + +# ── t3: the score checkbox belongs to legacy mode only ────────────────────── + +def test_score_checkbox_hidden_in_auto_visible_in_legacy(monkeypatch): + b, _ = _build(monkeypatch) + chk = b.lucj_chk_score + + # Auto (-1) is the default the panel opens on. + assert b.lucj_ancilla_dd.value == -1 + assert chk.layout.display == 'none', "score checkbox visible in Auto mode" + + b.lucj_ancilla_dd.value = 1 # explicit count -> legacy + assert chk.layout.display == '' + assert chk.disabled is False + assert chk.tooltip == 'Score layouts (pick lowest error)' + + b.lucj_ancilla_dd.value = -1 # back to Auto + assert chk.layout.display == 'none' + assert chk.disabled is True + + # Hidden, not removed: the legacy run path still reads .value. + b._build_auto_lucj_view() + assert any(w is chk for w in _descendants(b._auto_single_panel)), ( + "the checkbox must stay in the tree, only hidden") + + +# ── t4: the hidden checkbox must not drag other widgets down with it ──────── + +def test_score_checkbox_owns_its_layout(monkeypatch): + """Regression: `W` is ONE shared Layout instance handed to ~86 widgets, so + toggling `.layout.display` on a widget built with `layout=W` hid every one + of them (the I/O paste box, the Run button, ...). The score checkbox must + own its Layout so the sweep-mode toggle is local to it.""" + b, _ = _build(monkeypatch) + chk = b.lucj_chk_score + + assert chk.layout is not b.txt_auto.layout, ( + "score checkbox shares its Layout instance with txt_auto — " + "hiding it would hide every widget built with W") + + b.lucj_ancilla_dd.value = -1 # Auto -> checkbox hidden + assert chk.layout.display == 'none' + # …and nothing else moved. + assert b.txt_auto.layout.display != 'none' + assert b.btn_auto.layout.display != 'none' + assert b.btn_lucj_run.layout.display != 'none' + assert b.chk_lucj_diverse.layout.display != 'none' + + # No other widget in the tree shares that Layout object. + b._build_auto_lucj_view() + sharers = [w for w in _descendants(b._auto_single_panel) + if getattr(w, 'layout', None) is chk.layout] + assert sharers == [chk], f"Layout shared with {len(sharers) - 1} other widget(s)" + + # The visual properties W supplied are preserved on the private copy. + assert (chk.layout.width, chk.layout.margin) == \ + (b.chk_lucj_diverse.layout.width, b.chk_lucj_diverse.layout.margin) diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index 99f6419..99ec8b9 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -242,14 +242,14 @@ def test_batch_scan_sweep_fn_gets_multi_knobs(monkeypatch): b.lucj_top_n.value = 7 b.lucj_search_cap.value = 5000 b.chk_deep_search.value = False - b.chk_lucj_diverse.value = True + b.chk_lucj_diverse.value = False # non-default (default is ON) b.lucj_multi_norbs.value = '8, 6' b.btn_scan_batch.click() assert seen['norbs'] == [8, 6] k = seen['kwargs'] assert k['top_n'] == 7 and k['mapping_cap'] == 5000 - assert k['hybrid'] is False and k['diversity_threshold'] == 0.8 + assert k['hybrid'] is False and k['diversity_threshold'] is None # ── batch handoff fires from the selector's open button (right payload) ────── diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py index 95a17d0..8d4259a 100644 --- a/tests/test_multi_sweep_ui.py +++ b/tests/test_multi_sweep_ui.py @@ -265,7 +265,7 @@ def test_multi_sweep_kwargs_parity(monkeypatch): b.lucj_top_n.value = 7 b.lucj_search_cap.value = 5000 b.chk_deep_search.value = False - b.chk_lucj_diverse.value = True + b.chk_lucj_diverse.value = False # non-default (default is ON) b.lucj_ancilla_dd.value = -1 # sweep mode b.btn_lucj_run.click() # local sweep @@ -275,7 +275,7 @@ def test_multi_sweep_kwargs_parity(monkeypatch): for key in ('top_n', 'hybrid', 'mapping_cap', 'diversity_threshold'): assert mk[key] == local[key], key assert mk['top_n'] == 7 and mk['mapping_cap'] == 5000 - assert mk['hybrid'] is False and mk['diversity_threshold'] == 0.8 + assert mk['hybrid'] is False and mk['diversity_threshold'] is None # ── legacy Generate untouched — still calls the old engine ────────────── diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index 2e32ff3..afd35b3 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -358,7 +358,7 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): b.lucj_min_ancilla.value = 2 b.lucj_top_n.value = 7 # non-default top_n b.lucj_search_cap.value = 5000 # non-default cap - b.chk_lucj_diverse.value = True # non-default diversity + b.chk_lucj_diverse.value = False # non-default diversity b.btn_lucj_run.click() # local sweep local_kw = calls[-1] @@ -372,7 +372,8 @@ def test_local_and_scan_identical_sweep_kwargs(monkeypatch): # Show-top, Search-cap, diversity reach BOTH paths — parity. assert local_kw['top_n'] == 7 and scan_kw['top_n'] == 7 assert local_kw['mapping_cap'] == 5000 and scan_kw['mapping_cap'] == 5000 - assert local_kw['diversity_threshold'] == 0.8 and scan_kw['diversity_threshold'] == 0.8 + assert (local_kw['diversity_threshold'] is None + and scan_kw['diversity_threshold'] is None) # ── active backend skipped-with-reference (never re-searched) ─────────── From 7e8c0e589b333f0e09d062ed4cee6b682b2d4955 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Fri, 18 Sep 2026 17:45:52 -0400 Subject: [PATCH 31/66] =?UTF-8?q?Benchmark:=20opt-in=20tiered=20real-time?= =?UTF-8?q?=20benchmarking=20producing=20a=20measured=20calibration=20epoc?= =?UTF-8?q?h=20=E2=80=94=20sidebar=20section=205=20with=20target/QPU=20sel?= =?UTF-8?q?ectors,=20runtime=20Session=20contract=20tests,=20main-thread?= =?UTF-8?q?=20import=20preload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 + README.md | 64 ++ TUTORIAL.md | 57 +- iqmapper/benchmark.py | 1176 ++++++++++++++++++++++ iqmapper/ui/benchmark_panel.py | 414 ++++++++ iqmapper/ui/builder.py | 120 +++ iqmapper/ui/inter_qpu.py | 23 + iqmapper/ui/lucj_panel.py | 55 + pyproject.toml | 1 + tests/test_auto_panel_ui_polish.py | 62 +- tests/test_benchmark.py | 542 ++++++++++ tests/test_benchmark_runtime_contract.py | 291 ++++++ tests/test_benchmark_ui.py | 694 +++++++++++++ 13 files changed, 3501 insertions(+), 7 deletions(-) create mode 100644 iqmapper/benchmark.py create mode 100644 iqmapper/ui/benchmark_panel.py create mode 100644 tests/test_benchmark.py create mode 100644 tests/test_benchmark_runtime_contract.py create mode 100644 tests/test_benchmark_ui.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4be3e73..40153b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Added +- Opt-in real-time benchmarking (`iqmapper.benchmark`, extra + `pip install "i-qmapper[benchmark]"`): three tiers that re-measure the + candidate qubits and edges with `qiskit-experiments` and feed the result + back as a "measured" calibration epoch, so the heatmap, LQS, re-ranking and + export all read fresh numbers. Never automatic, never inside the multi-QPU + scan, and the QPU cost estimate is shown before the run can be started. + Lives in the sidebar as "5. Benchmark" with selectable targets (current + layouts / sweep candidates / whole QPU / a custom qubit list) and, in + inter-QPU mode, a QPU 1 | QPU 2 selector. - Stratified ancilla sweep: a single VF2 solve at `k_max` feeding a bridge-subtraction cascade down to `k_min`, with a hybrid mode, a shuffled search for hard instances, and region-diversity selection across the chip. diff --git a/README.md b/README.md index d4bf104..10eb606 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,10 @@ inspectable, and reproducible**. publication-ready PNGs, time-lapse GIF/MP4 of calibration history, full session save/restore, and generated Qiskit code for your chosen layout. +- 📡 **Real-time benchmarking (optional)** — re-measure your candidate qubits and + edges on the live device and re-rank against what the hardware is doing *now*, + not what it reported this morning. Opt-in, tiered and costed up front; see + [Real-time benchmarking](#real-time-benchmarking-optional). - 🔒 **Local-first** — your IBM Quantum credentials never leave your machine; the tool talks to IBM through your own locally saved `QiskitRuntimeService` account. @@ -75,6 +79,7 @@ Install from [PyPI](https://pypi.org/project/i-qmapper/): pip install i-qmapper pip install "i-qmapper[png]" pip install "i-qmapper[png,timelapse]" +pip install "i-qmapper[benchmark]" ``` ### From source (development) @@ -183,6 +188,65 @@ live in your own `qiskit-ibm-runtime` account store.
+## Real-time benchmarking (optional) + +I-QMapper normally ranks layouts on the calibration IBM *reports*, which is +refreshed about once a day. Qubits drift inside that window, so a layout chosen +at 14:00 can sit on a qubit that degraded at 11:00. The Benchmark section in the +**Auto** tab re-measures the hardware and feeds the result back as a "measured" +calibration epoch — the heatmap, LQS, candidate ranking and exports all read it +exactly as they read the reported one. + +It lives in the sidebar as **5. Benchmark** — beside Hardware rather than inside +the Auto search, because benchmarking is a property of the backend: it serves +hand-placed layouts as readily as swept ones, every circuit slot, the whole QPU, +and the second panel in inter-QPU mode. + +Install the extra first: + +```bash +pip install "i-qmapper[benchmark]" +``` + +Three levels, each measuring only what it needs to: + +| Level | What it measures | Scope | Rough QPU cost | +|-------|------------------|-------|----------------| +| **1 Quick readout** | Readout assignment error | Candidate qubits | Seconds | +| **2 Targeted** | Level 1 + two-qubit RB | Candidate qubits and edges | Tens of seconds | +| **3 Full chip** | T1, T2 (Hahn), readout, 1Q RB, 2Q RB | Whole device | ~4 minutes | + +Pick what to measure with **Targets**: the currently placed layout(s) across +every circuit slot, the last sweep's top candidates, the whole QPU, or an +explicit qubit list. Levels 1 and 2 are targeted, which is why they are cheap; +Level 3 reproduces the full-chip suite from IBM's "Real-time benchmarking for +qubit selection" tutorial. + +Worth knowing: **Level 1 does not get more expensive as you measure more +qubits** — readout is two circuits whatever the width — so `Whole QPU` x Level 1 +is the cheap way to refresh the readout heatmap across the device. Levels 2 and +3 scale with the number of edges and are not cheap. + +In inter-QPU mode a **QPU 1 | QPU 2** selector appears; everything — targets, +cost, run, the resulting epoch and its cache file — then applies to whichever +device is selected. + +**It is never automatic.** Nothing benchmarks on connect, on a timer, or inside +the multi-QPU scan. A run happens only when you click **Run benchmark**, and the +estimated cost is on screen before you can click it. + +**Mind your plan.** The cost estimates are wall-clock QPU seconds, and on an +Open-plan account a Level 3 run can consume a large part of a monthly +allowance. I-QMapper detects your plan where it can and assumes the Open plan +when it cannot, so Level 2 warns and Level 3 requires an explicit +acknowledgement. The estimate itself is calibrated from a single published +figure — treat it as the right order of magnitude, not a quote. + +Measured values replace reported ones only for the elements actually measured; +everything else keeps its reported value, and the calibration label tells you +which epoch you are looking at. Any experiment or fit that fails falls back to +the reported value for that element with a notice, never a crash. + ## Extending to other vendors
diff --git a/TUTORIAL.md b/TUTORIAL.md index 8fa9f27..642cf4c 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -11,9 +11,10 @@ Prerequisites: [Installation](README.md#installation) and [4. Score & compare](#4-score--compare) · [5. Travel in time](#5-travel-in-time) · [6. Check stability](#6-check-stability) · -[7. Import & export](#7-import--export) · -[8. Save your session](#8-save-your-session) · -[9. Where your data lives](#9-where-your-data-lives) +[7. Benchmark the live device](#7-benchmark-the-live-device-optional) · +[8. Import & export](#8-import--export) · +[9. Save your session](#9-save-your-session) · +[10. Where your data lives](#10-where-your-data-lives) --- @@ -117,7 +118,51 @@ tells you (fetch more from the Time panel's Multi-day mode). ![Stability check flags volatile qubits](docs/img/stability-report.png) -## 7. Import & export +## 7. Benchmark the live device (optional) + +Everything so far has ranked layouts on the calibration IBM *reported* — good +numbers, but up to a day old. Sidebar section **5. Benchmark** measures the +hardware right now instead. + +It needs one extra install (`pip install "i-qmapper[benchmark]"`); without it +the section shows the install hint and stays disabled. + +1. Pick **Targets** — what to measure: + - **Current layout(s)** — every qubit placed on the map, across all circuit + slots, however it got there. The default when something is placed. + - **Sweep candidates (top-K)** — the last sweep's best candidates. Offered + only once a sweep has run. + - **Whole QPU** — the entire device. + - **Custom** — type a qubit list, same format as the paste box. +2. Pick a **Level**. Start with **1 Quick readout** — seconds, and its cost does + not grow with the number of qubits, so `Whole QPU` x Level 1 is a cheap way + to refresh the readout heatmap across the whole device. **2 Targeted** adds + two-qubit randomized benchmarking on the target edges (tens of seconds, and + this one does scale with edges). **3 Full chip** takes about four minutes. +3. Read the summary line before clicking. It tells you how many qubits and + edges will be measured, the estimated QPU time, and the plan it detected. +4. On the Open plan (or when the plan cannot be detected) Level 2 warns you and + Level 3 requires you to tick **I understand this uses QPU time**. +5. Click **📡 Run benchmark**. + +In inter-QPU mode a **QPU 1 | QPU 2** selector appears above Targets. Everything +then applies to the selected device — including layouts handed over from a scan, +which show up under **Current layout(s)** on QPU 2. + +When it finishes, the calibration label changes to `measured HH:MM (L2, 38q/44e)` +and the candidate dropdown re-ranks under the fresh numbers — a layout that +looked best this morning may not be best now, which is the whole point. Only the +elements actually measured are updated; the rest keep their reported values. If +an individual fit fails, that element keeps its reported value and the notices +bar says so. + +Re-running the sweep within the hour? The section offers **Reuse** for the last +measurement instead of spending the QPU time again. + +Nothing here is automatic: no benchmark runs on connect, on a timer, or during a +multi-QPU scan. + +## 8. Import & export From the **Export** tab: @@ -135,7 +180,7 @@ From the **Export** tab: ![Publication-ready PNG export with legend](docs/img/hero.png) -## 8. Save your session +## 9. Save your session **Session save/restore** captures everything — layouts, colors, zoom, the backend context — into a single file, so you can close the notebook and pick @@ -143,7 +188,7 @@ up exactly where you left off, or share a session file with a colleague. Style presets (palettes, color settings) can be saved and reused independently of sessions. -## 9. Where your data lives +## 10. Where your data lives | What | Where | |---|---| diff --git a/iqmapper/benchmark.py b/iqmapper/benchmark.py new file mode 100644 index 0000000..8d75b9f --- /dev/null +++ b/iqmapper/benchmark.py @@ -0,0 +1,1176 @@ +""" +benchmark.py — opt-in, tiered, candidate-targeted real-time benchmarking. + +I-QMapper normally scores layouts on the QPU's *reported* calibration, which +IBM refreshes about once a day. Qubits drift inside that window (transient +two-level-system defects, heating, spectator effects), so a layout chosen at +14:00 can sit on a qubit that degraded at 11:00. IBM's "Real-time benchmarking +for qubit selection" tutorial re-measures T1/T2/readout/1Q-RB/2Q-RB with +`qiskit-experiments` and feeds the fresh numbers back into the properties. + +This module packages that idea as a feature that is safe to ship: + +Why targeted, not full-chip + The tutorial's whole-chip suite costs roughly four minutes of QPU time per + run. That is unaffordable on the Open plan and wasteful even on Premium, + since a sweep only ever cares about a few dozen qubits. Levels 1 and 2 + measure ONLY the candidate qubits and edges that the sweep actually + proposed, which is seconds to tens of seconds. Level 3 reproduces the + tutorial suite for people who want the full-chip diagnostic and know what + it costs. + +Why never automatic + Benchmarking spends real quantum-computer time and money. Nothing here + runs on connect, on a timer, or inside the multi-QPU scan — the scan + touches dozens of backends and an implicit benchmark per backend would be + catastrophic. A run happens only when a human clicks the button, having + been shown the cost estimate first. `plan_gate` additionally refuses + Level 3 (and warns on Level 2) unless the user acknowledges the cost, and + treats an unknown plan as Open, the conservative case. + +What the masks mean + A benchmark measures *some* elements, not all. `MeasuredEpoch` therefore + carries `measured_qubit_mask` / `measured_edge_mask`: booleans, one per + qubit / per edge, True where the value in `qubit_props`/`gate_props` came + from this run and False where it is still the reported value. Everything + downstream (heatmap, LQS, re-ranking, export) reads the arrays exactly as + it reads a reported epoch; the masks exist so the UI can say which numbers + are fresh, and so a partial failure is visible rather than silent. + +On comparing RB error to reported gate error + Randomized benchmarking returns an error-per-gate averaged over random + Clifford sequences; the reported `cz_error` is the provider's own + per-gate estimate from its calibration routine. Both are per-gate error + rates on the same footing for ranking purposes, and the tutorial swaps one + for the other exactly this way — but they are different estimators, so an + absolute value may shift slightly even on a qubit that has not drifted. + Treat a measured epoch as a better ordering, not as a recalibration. + +State mutation note + `apply_measured_epoch` attaches the epoch to the session as + `state._measured_epoch` with `setattr`. `SessionState` is a frozen engine + in this project, so the field is deliberately NOT declared there; it is + created at runtime and every reader must use `getattr(state, + '_measured_epoch', None)`. Session save/restore ignores it by design — a + measured epoch is a live, perishable thing and should not survive a + reload as if it were calibration. + +Failure policy + Nothing in this module raises on a per-element measurement or fit failure. + `results_to_epoch` keeps the reported value for that element, leaves its + mask False, and appends a human-readable notice. Only a missing + `qiskit-experiments` install (an install-time problem) raises, from + `make_runtime_runner`. + +Import policy + The heavy runtime imports are main-thread-only by design — see + `preload_runtime`. +""" +import json as _json +import logging +import os +import tempfile +import time +from collections import namedtuple +from types import SimpleNamespace + +import numpy as np + +_log = logging.getLogger(__name__) + + +# ── Levels ────────────────────────────────────────────────────────── + +#: Level 0 is "use the reported calibration" — the default, and not a plan: +#: it is simply the absence of a benchmark, so no code path corresponds to it. +LEVEL_REPORTED = 0 +LEVEL_QUICK_READOUT = 1 +LEVEL_TARGETED = 2 +LEVEL_FULL = 3 + +LevelInfo = namedtuple('LevelInfo', 'level name description scope') + +LEVELS = { + LEVEL_QUICK_READOUT: LevelInfo( + LEVEL_QUICK_READOUT, 'Quick readout', + 'Readout assignment error on the candidate qubits only.', + 'candidate qubits'), + LEVEL_TARGETED: LevelInfo( + LEVEL_TARGETED, 'Targeted', + 'Quick readout plus two-qubit randomized benchmarking on the ' + 'candidate edges.', + 'candidate qubits + edges'), + LEVEL_FULL: LevelInfo( + LEVEL_FULL, 'Full chip', + 'The tutorial suite: T1, T2 (Hahn), readout, 1Q RB and 2Q RB over ' + 'the whole device.', + 'whole chip'), +} + +#: Dropdown-ready (label, level) pairs. +LEVEL_OPTIONS = [(f'{i} {LEVELS[i].name}', i) + for i in (LEVEL_QUICK_READOUT, LEVEL_TARGETED, LEVEL_FULL)] + +# Tutorial parameters, kept verbatim so a Level-3 run reproduces its figures. +DEFAULT_SHOTS = 1000 +T1T2_DELAYS = [1e-6, 20e-6, 40e-6, 80e-6, 200e-6, 400e-6] +RB_1Q_LENGTHS = [10, 100, 500] +RB_1Q_SAMPLES = 10 +RB_2Q_LENGTHS = [10, 50, 100] +RB_2Q_SAMPLES = 10 + +#: A saved epoch older than this is offered as history rather than as "reuse". +REUSE_TTL_MINUTES = 60 + + +# ── Cost model ────────────────────────────────────────────────────── +# +# Deliberately a transparent formula over circuit counts rather than a fitted +# model: the point is that a user can read it and see where the number came +# from. The per-circuit constants are back-solved so that the tutorial's +# full-chip suite on a 127-qubit device lands near its quoted ~240 s, which +# makes them accurate to roughly a factor of two and no better. They are +# wall-clock seconds per circuit including the provider's own overhead, not +# pure quantum-execution time. + +_SEC_PER_CIRCUIT_1Q = 0.012 +_SEC_PER_CIRCUIT_2Q = 0.035 +_SEC_PER_T1T2 = 0.030 +_SESSION_OVERHEAD_S = 8.0 + +# The model charges two-qubit RB per EDGE, not per layer, even though +# `build_plan` groups disjoint edges into layers that a provider can execute +# together. That makes the estimate an upper bound rather than a best case, +# which is the right direction to err in when the number is being shown to +# someone about to spend their allowance. The per-qubit scaling on the +# parallel experiments is there for the same reason: transpilation and +# analysis cost really does grow with qubit count even when execution does +# not. Calibration check lives in tests/test_benchmark.py. + + +# ── Data types ────────────────────────────────────────────────────── + +Targets = namedtuple('Targets', 'qubits edges') +ExperimentSpec = namedtuple('ExperimentSpec', 'kind qubits params layer') +BenchmarkPlan = namedtuple('BenchmarkPlan', 'level specs targets shots') +CostEstimate = namedtuple('CostEstimate', 'circuits qpu_seconds text') +Gate = namedtuple('Gate', 'allowed warning') + + +class MeasuredEpoch: + """A calibration epoch whose measured elements came from a benchmark run. + + `qubit_props` / `gate_props` are full-width dict-of-arrays in exactly the + shape `state.qubit_props_data` / `state.gate_props_data` use, so the epoch + drops into the existing channel untouched. The masks say which entries are + measured; everything else is the reported value carried through. + """ + + __slots__ = ('qubit_props', 'gate_props', 'measured_qubit_mask', + 'measured_edge_mask', 'level', 'when', 'notices') + + def __init__(self, qubit_props, gate_props, measured_qubit_mask, + measured_edge_mask, level, when, notices=None): + self.qubit_props = qubit_props + self.gate_props = gate_props + self.measured_qubit_mask = np.asarray(measured_qubit_mask, dtype=bool) + self.measured_edge_mask = np.asarray(measured_edge_mask, dtype=bool) + self.level = int(level) + self.when = when # epoch seconds (time.time()) + self.notices = list(notices or []) + + # ── convenience ──────────────────────────────────────────── + @property + def n_measured_qubits(self): + return int(self.measured_qubit_mask.sum()) + + @property + def n_measured_edges(self): + return int(self.measured_edge_mask.sum()) + + def age_minutes(self, now=None): + return ((time.time() if now is None else now) - self.when) / 60.0 + + def younger_than(self, minutes, now=None): + """True when this epoch is fresh enough to offer for reuse.""" + return self.age_minutes(now) < minutes + + def time_label(self): + return time.strftime('%H:%M', time.localtime(self.when)) + + def __repr__(self): # pragma: no cover - debug aid + return (f'') + + +# ── Target selection ──────────────────────────────────────────────── + +def _normalize_edge(a, b, coupling_edges): + """Return the edge oriented as the backend's coupling map lists it. + + The sweep works on an undirected view, but the reported gate arrays are + indexed by `state.edges_list`, whose orientation comes from the device. + Writing a measured value against the wrong orientation would silently + update the wrong edge, so every edge goes through here. + """ + if (a, b) in coupling_edges: + return (a, b) + if (b, a) in coupling_edges: + return (b, a) + return None + + +#: Target-selection modes, in the order the UI lists them. +TARGET_CURRENT = 'current' +TARGET_SWEEP = 'sweep' +TARGET_WHOLE = 'whole' +TARGET_CUSTOM = 'custom' + +TARGET_LABELS = { + TARGET_CURRENT: 'Current layout(s)', + TARGET_SWEEP: 'Sweep candidates (top-K)', + TARGET_WHOLE: 'Whole QPU', + TARGET_CUSTOM: 'Custom', +} + + +def parse_qubit_list(text): + """Qubit indices out of free text, by the paste box's own rules. + + Deliberately NOT `export.autodetect.parse_auto_text`: that function maps + the parsed qubits onto circuit layouts as a side effect, which is exactly + wrong for choosing what to measure. The token rules are the same ones it + uses — strip brackets, split on commas and whitespace, accept + non-negative integers, drop everything else — so a list that works in the + paste box works here. + """ + if not text: + return [] + cleaned = (str(text).replace('[', ' ').replace(']', ' ') + .replace(',', ' ').replace('\n', ' ')) + out = [] + for token in cleaned.split(): + if token.isdigit(): + value = int(token) + if value not in out: + out.append(value) + return out + + +def _edges_within(qubits, coupling): + """Coupling edges with BOTH endpoints in `qubits`, device orientation.""" + wanted = set(qubits) + seen = set() + edges = [] + for (a, b) in coupling: + if a in wanted and b in wanted: + edge = _normalize_edge(a, b, set(coupling)) + if edge is not None and edge not in seen: + seen.add(edge) + edges.append(edge) + return edges + + +def select_targets(state, sweep_result=None, top_k=5, mode=None, custom=None): + """Qubits and edges worth measuring, as a `Targets`. + + `mode` picks what "worth measuring" means: + + `current` — every qubit placed on the map, across ALL circuit slots, + however it got there: hand-placed, auto-placed, or handed over from + a scan. This is the default, because the thing a user is about to + run is the thing worth measuring. + `sweep` — the union over the top-K candidates of the last sweep, for + choosing BETWEEN candidates rather than validating one. + `whole` — the entire device. Worth knowing: Level 1 does not scale + with qubit count (readout is two circuits whatever the width), so + whole-QPU Level 1 is the cheap way to refresh the readout heatmap. + Levels 2 and 3 scale with edge count and are not cheap. + `custom` — an explicit qubit list; edges are the coupling edges with + both endpoints in it. + + With no `mode`, falls back to the original behaviour: sweep candidates if + there are any, else the current layout, else empty — and empty means the + UI disables the button rather than quietly measuring the whole chip. + + Edges always come back in the device's own orientation, because the gate + arrays are indexed by `state.edges_list` and writing a measured value + against a flipped edge would silently update the wrong one. + """ + coupling = [tuple(e) for e in (getattr(state, 'edges_list', None) or [])] + + if mode == TARGET_WHOLE: + n_q = len(getattr(state, 'qubit_ids', None) or []) + return Targets(list(range(n_q)), list(coupling)) + + if mode == TARGET_CUSTOM: + qubits = [q for q in parse_qubit_list(custom) + if 0 <= q < len(getattr(state, 'qubit_ids', None) or [])] + return Targets(sorted(qubits), _edges_within(qubits, coupling)) + + if mode == TARGET_CURRENT: + qubits = _qubits_from_current_layout(state) + return Targets(sorted(qubits), _edges_within(qubits, coupling)) + + if mode == TARGET_SWEEP: + qubits = _qubits_from_sweep(sweep_result, top_k) + return Targets(sorted(qubits), _edges_within(qubits, coupling)) + + # Legacy/auto: sweep candidates, else the current layout, else nothing. + qubits = _qubits_from_sweep(sweep_result, top_k) \ + or _qubits_from_current_layout(state) + if not qubits: + return Targets([], []) + return Targets(sorted(qubits), _edges_within(qubits, coupling)) + + +def available_target_modes(state, sweep_result=None): + """The modes the UI should offer, in order, for this session. + + `sweep` appears only once a sweep has actually produced candidates, so the + dropdown never offers a mode that would resolve to nothing. + """ + modes = [TARGET_CURRENT] + if _qubits_from_sweep(sweep_result, 5): + modes.append(TARGET_SWEEP) + modes.append(TARGET_WHOLE) + modes.append(TARGET_CUSTOM) + return modes + + +def default_target_mode(state, sweep_result=None): + """`current` when something is placed, else `sweep`, else `current`.""" + if _qubits_from_current_layout(state): + return TARGET_CURRENT + if _qubits_from_sweep(sweep_result, 5): + return TARGET_SWEEP + return TARGET_CURRENT + + +def _qubits_from_sweep(sweep_result, top_k): + """Union of the top-K sweep candidates' qubits.""" + qubits = set() + for entry in _flatten_candidates(sweep_result, top_k): + for key in ('alpha', 'beta', 'ancillas'): + for q in (entry.get(key) or []): + try: + qubits.add(int(q)) + except (TypeError, ValueError): + continue + return qubits + + +def _flatten_candidates(sweep_result, top_k): + """Top-K entries out of either candidate-list or raw-sweep-dict form.""" + if not sweep_result: + return [] + if isinstance(sweep_result, dict): + flat = [] + for _k, entries in sorted((sweep_result.get('strata') or {}).items()): + flat.extend(entries or []) + else: + flat = list(sweep_result) + return [e for e in flat[:max(0, int(top_k))] if isinstance(e, dict)] + + +def _qubits_from_current_layout(state): + """Physical qubits painted on the map right now (all circuits).""" + out = set() + for d in (getattr(state, 'layouts_data', None) or {}).values(): + if not isinstance(d, dict): + continue + for role in ('alpha', 'beta', 'ancilla', 'other'): + for q in (d.get(role) or []): + try: + out.add(int(q)) + except (TypeError, ValueError): + continue + return out + + +# ── Plan construction ─────────────────────────────────────────────── + +def _layer_edges(edges): + """Group edges into layers that share no qubit, via edge colouring. + + Two-qubit RB on disjoint pairs runs in parallel, which is where most of + the saving in Level 2 comes from. `rustworkx.graph_bipartite_edge_color` + gives a proper edge colouring of the TARGET subgraph (not the whole chip), + so each colour class is a set of vertex-disjoint pairs. Falls back to a + greedy pass if rustworkx is unavailable or the call fails, and in the + worst case to one edge per layer, which is correct but slower. + """ + if not edges: + return [] + try: + import rustworkx + + graph = rustworkx.PyGraph() + index = {} + for (a, b) in edges: + for q in (a, b): + if q not in index: + index[q] = graph.add_node(q) + handles = {} + for (a, b) in edges: + handles[graph.add_edge(index[a], index[b], None)] = (a, b) + coloring = rustworkx.graph_bipartite_edge_color(graph) + layers = {} + for edge_handle, color in dict(coloring).items(): + edge = handles.get(edge_handle) + if edge is not None: + layers.setdefault(color, []).append(edge) + if layers: + return [layers[c] for c in sorted(layers)] + except Exception: + _log.debug("edge colouring unavailable; falling back to greedy", + exc_info=True) + return _greedy_layers(edges) + + +def _greedy_layers(edges): + """First-fit layering: correct for any graph, just not always minimal.""" + layers = [] + for (a, b) in edges: + for layer in layers: + if all(a not in pair and b not in pair for pair in layer): + layer.append((a, b)) + break + else: + layers.append([(a, b)]) + return layers + + +def build_plan(level, targets, n_qubits, coupling_edges): + """The experiment specs a run at `level` would execute. + + Returns a `BenchmarkPlan` of provider-agnostic `ExperimentSpec`s — no + qiskit objects are constructed here, which is what lets the whole planning + and costing path be tested offline with no quantum stack installed. + + Level 1 measures readout on the target qubits. Level 2 adds layered 2Q RB + over the target edges. Level 3 ignores the targets and covers the device: + T1, T2 Hahn, readout, 1Q RB over all qubits, 2Q RB over all coupling + edges — the tutorial suite, at the tutorial's parameters. + """ + level = int(level) + coupling = [tuple(e) for e in (coupling_edges or [])] + + if level == LEVEL_FULL: + qubits = list(range(int(n_qubits))) + edges = list(coupling) + targets = Targets(qubits, edges) + else: + qubits = list(targets.qubits) + edges = list(targets.edges) + + specs = [] + + if level == LEVEL_FULL: + specs.append(ExperimentSpec('t1', tuple(qubits), + {'delays': list(T1T2_DELAYS)}, 0)) + specs.append(ExperimentSpec('t2hahn', tuple(qubits), + {'delays': list(T1T2_DELAYS)}, 0)) + + if qubits: + specs.append(ExperimentSpec('readout', tuple(qubits), {}, 0)) + + if level == LEVEL_FULL and qubits: + specs.append(ExperimentSpec( + 'rb1q', tuple(qubits), + {'lengths': list(RB_1Q_LENGTHS), 'num_samples': RB_1Q_SAMPLES}, 0)) + + if level in (LEVEL_TARGETED, LEVEL_FULL) and edges: + for layer_idx, layer in enumerate(_layer_edges(edges)): + for pair in layer: + specs.append(ExperimentSpec( + 'rb2q', tuple(pair), + {'lengths': list(RB_2Q_LENGTHS), + 'num_samples': RB_2Q_SAMPLES}, layer_idx)) + + return BenchmarkPlan(level, specs, targets, DEFAULT_SHOTS) + + +# ── Cost estimation ───────────────────────────────────────────────── + +def _spec_circuits(spec): + """Circuit count for one spec, at the tutorial's parameterisation.""" + params = spec.params + if spec.kind in ('t1', 't2hahn'): + return len(params.get('delays') or []) + if spec.kind == 'readout': + return 2 # |0...0> and |1...1> preparations + if spec.kind == 'rb1q': + return (len(params.get('lengths') or []) + * int(params.get('num_samples') or 0)) + if spec.kind == 'rb2q': + return (len(params.get('lengths') or []) + * int(params.get('num_samples') or 0)) + return 1 + + +def estimate_cost(plan, shots=DEFAULT_SHOTS): + """Wall-clock QPU seconds a plan is expected to consume. + + An ESTIMATE, and a coarse one: the constants are back-solved from the + tutorial's single published figure (~240 s for the full suite on 127 + qubits) and take no account of queueing, of how busy the device is, or of + the provider's batching. Treat it as an order of magnitude that is right, + not a quote. It is monotonic in plan size, which is the property the UI + actually depends on. + """ + circuits = 0 + seconds = 0.0 + for spec in plan.specs: + n = _spec_circuits(spec) + circuits += n + if spec.kind == 'readout': + # LocalReadoutError prepares |0...0> and |1...1> across every + # target qubit at once: two circuits, whatever the width. So a + # whole-QPU Level 1 costs the same as a three-qubit one, which is + # what makes it the cheap way to refresh the readout heatmap. + seconds += n * _SEC_PER_CIRCUIT_1Q + elif spec.kind in ('t1', 't2hahn'): + # One sequence per delay per qubit, run in parallel across qubits. + seconds += n * _SEC_PER_T1T2 * max(1, len(spec.qubits)) + elif spec.kind == 'rb2q': + seconds += n * _SEC_PER_CIRCUIT_2Q + else: + seconds += n * _SEC_PER_CIRCUIT_1Q * max(1, len(spec.qubits)) + + seconds *= (shots / float(DEFAULT_SHOTS)) if DEFAULT_SHOTS else 1.0 + seconds += _SESSION_OVERHEAD_S if plan.specs else 0.0 + + return CostEstimate(circuits, seconds, _format_cost(seconds)) + + +def _format_cost(seconds): + if seconds < 90: + return f'~{seconds:.0f} s QPU (estimate)' + return f'~{seconds / 60.0:.1f} min QPU (estimate)' + + +# ── Plan (subscription) gating ────────────────────────────────────── + +# Substrings that mark a subscription with no per-run allowance to protect. +# 'on-prem' joined the list after a live run reported `plan: on-prem` and was +# needlessly gated as if it were Open. Matched case-insensitively as a +# substring, so 'On-Prem', 'premium-plan' and 'IBM Dedicated' all land here. +_UNMETERED_PLANS = ('premium', 'dedicated', 'internal', 'on-prem', 'onprem') + + +def plan_gate(plan_name, level): + """Whether `level` may run under subscription `plan_name`. + + An unknown plan is treated as Open. That is the conservative direction: + the worst case of guessing Open on a Premium account is one extra + acknowledgement click, whereas guessing Premium on an Open account can + burn a monthly allowance in a single run. + """ + level = int(level) + name = (plan_name or '').strip().lower() + unmetered = any(p in name for p in _UNMETERED_PLANS) + + if unmetered: + return Gate(True, None) + + if level == LEVEL_QUICK_READOUT: + return Gate(True, None) + if level == LEVEL_TARGETED: + return Gate(True, + 'Level 2 spends QPU time from your monthly allowance — ' + 'tick the acknowledgement to continue.') + if level == LEVEL_FULL: + return Gate(False, + 'Level 3 measures the whole chip (~4 min of QPU time). ' + 'On an Open-plan account this can consume a large part of ' + 'your monthly allowance in one run.') + return Gate(True, None) + + +def requires_acknowledgement(plan_name, level): + """True when the UI must see the cost checkbox ticked before running.""" + level = int(level) + if level == LEVEL_FULL: + return True # always, on every plan + gate = plan_gate(plan_name, level) + return gate.warning is not None or not gate.allowed + + +# ── Execution ─────────────────────────────────────────────────────── + +_INSTALL_HINT = ('Real-time benchmarking needs qiskit-experiments. ' + 'Install it with: pip install "i-qmapper[benchmark]"') + + +def have_qiskit_experiments(): + """Cheap availability probe for the UI, with no import side effects.""" + try: + import importlib.util + return importlib.util.find_spec('qiskit_experiments') is not None + except Exception: # pragma: no cover - defensive + return False + + +def run_plan(plan, runner): + """Execute `plan` through the injected `runner` and return raw results. + + `runner` is any callable taking the plan and returning a mapping of raw + per-experiment results. Everything that touches a network or a quantum + stack lives behind it, which is what makes the rest of this module — and + every test — offline. `make_runtime_runner` builds the production one. + """ + if not plan.specs: + return {} + return runner(plan) + + +def _runtime_api(): + """Resolve the quantum stack, late and in one place. + + Every class the production runner needs comes through here, for two + reasons. It keeps the imports lazy, so `import iqmapper.benchmark` stays + free for the majority of users who never benchmark. And it gives the + contract tests a single seam to monkeypatch, so the runner's call shapes + can be pinned offline — which is exactly what was missing when the + `Session(service=...)` signature drifted underneath us and the failure + only surfaced on a live device. + """ + try: + # pandas is pulled in transitively by qiskit_experiments, but it is + # named explicitly here so that preloading this module genuinely + # finishes importing it. See preload_runtime() for why that matters. + import pandas # noqa: F401 + from qiskit_experiments.framework import (BatchExperiment, + ParallelExperiment) + from qiskit_experiments.library import (LocalReadoutError, StandardRB, + T1, T2Hahn) + except ImportError as exc: + raise ImportError(_INSTALL_HINT) from exc + + from qiskit_ibm_runtime import Session, SamplerV2 + + return SimpleNamespace( + Session=Session, SamplerV2=SamplerV2, + BatchExperiment=BatchExperiment, ParallelExperiment=ParallelExperiment, + LocalReadoutError=LocalReadoutError, StandardRB=StandardRB, + T1=T1, T2Hahn=T2Hahn) + + +#: Resolved runtime stack, cached after the first successful preload. +_RUNTIME_CACHE = [None] + + +def runtime_ready(): + """True once the quantum stack has been imported in this process. + + The UI uses it to decide whether to show "Loading benchmark libraries…" + before the first run; later runs skip the message because the preload is + a no-op. + """ + return _RUNTIME_CACHE[0] is not None + + +def preload_runtime(): + """Import the quantum stack now, on the calling thread. Idempotent. + + This exists because of a live crash. `make_runtime_runner` used to resolve + its imports lazily inside the background worker, so the first benchmark + run imported qiskit_experiments — and transitively pandas and scipy — on a + worker thread while the kernel's main thread was still serving widget + events. Plotly's click handler (`_handler_js2py_pointsCallback`) probes + `sys.modules['pandas']`, found the half-initialised module the worker had + just put there, and raised: + + AttributeError: partially initialized module 'pandas' + + Clicking the map during a benchmark was enough to trigger it. Python's + import machinery publishes a module into `sys.modules` before executing + it, so any thread reading `sys.modules` mid-import sees a shell — this is + inherent to importing a large package off the main thread while the main + thread is live, not a plotly or pandas bug. + + The fix is to do the import on the MAIN thread before the worker starts. + The UI calls this from its run handler ahead of `spawn_bg`; it blocks for a + second or two on first use and returns instantly thereafter. The worker + then only ever finds an already-populated cache and never triggers a + first-time import. + + Raises ImportError with the install hint when the extra is missing. + """ + if _RUNTIME_CACHE[0] is None: + _RUNTIME_CACHE[0] = _runtime_api() + return _RUNTIME_CACHE[0] + + +def _reset_runtime_cache(): + """Drop the cached stack. For tests that swap `_runtime_api` out.""" + _RUNTIME_CACHE[0] = None + + +def _build_experiment(spec, api): + """One `ExperimentSpec` → the qiskit-experiments object that runs it.""" + physical = list(spec.qubits) + if spec.kind == 't1': + return api.ParallelExperiment( + [api.T1((q,), delays=spec.params['delays']) for q in physical]) + if spec.kind == 't2hahn': + return api.ParallelExperiment( + [api.T2Hahn((q,), delays=spec.params['delays']) + for q in physical]) + if spec.kind == 'readout': + return api.LocalReadoutError(physical) + if spec.kind == 'rb1q': + return api.ParallelExperiment( + [api.StandardRB((q,), lengths=spec.params['lengths'], + num_samples=spec.params['num_samples']) + for q in physical]) + if spec.kind == 'rb2q': + return api.StandardRB(tuple(physical), + lengths=spec.params['lengths'], + num_samples=spec.params['num_samples']) + raise ValueError(f'unknown experiment kind: {spec.kind}') + + +def make_runtime_runner(backend): + """The production runner: qiskit-experiments against a real backend. + + The session is opened as `Session(backend=backend)`. Older + qiskit-ibm-runtime took a `service=` kwarg as well; 0.48 removed it, + because a backend object already carries its own service. Passing it now + raises `TypeError: Session.__init__() got an unexpected keyword argument + 'service'`, which is what the first live run hit. The call shape is pinned + by tests/test_benchmark_runtime_contract.py so the next such drift fails + offline instead of on a device. + + The session is entered with `with`, so it closes on the way out whether + the run succeeds or raises — a leaked session keeps holding a reservation. + + Resolves through `preload_runtime`, so if the UI already preloaded on the + main thread this is a cache read. Calling it from a worker without that + preload would import the stack off-thread — see `preload_runtime` for the + crash that causes. + """ + api = preload_runtime() + + def _runner(plan): + experiments = [(spec, _build_experiment(spec, api)) + for spec in plan.specs] + batch = api.BatchExperiment([exp for _s, exp in experiments], + flatten_results=False) + + with api.Session(backend=backend) as session: + sampler = api.SamplerV2(mode=session) + data = batch.run(sampler=sampler, shots=plan.shots) + data.block_for_results() + + out = {} + for idx, (spec, _exp) in enumerate(experiments): + try: + out[idx] = data.child_data(idx).analysis_results() + except Exception as exc: # noqa: BLE001 - per-experiment + _log.warning("benchmark: no results for %s %s: %s", + spec.kind, spec.qubits, exc) + out[idx] = None + return out + + return _runner + + +# ── Results → epoch ───────────────────────────────────────────────── + +def _readout_error_from_matrix(matrix): + """Symmetrised assignment error, as the tutorial computes it.""" + m = np.asarray(matrix, dtype=float) + if m.shape != (2, 2): + raise ValueError(f'assignment matrix must be 2x2, got {m.shape}') + return float((m[0, 1] + m[1, 0]) / 2.0) + + +def _result_value(item): + """Pull a scalar out of whatever shape the analysis result carries.""" + value = getattr(item, 'value', item) + for attr in ('nominal_value', 'n', 'value'): + inner = getattr(value, attr, None) + if inner is not None and not callable(inner): + value = inner + break + return float(value) + + +def _lookup(results, idx): + entry = results.get(idx) if isinstance(results, dict) else None + return entry + + +def results_to_epoch(raw, plan, reported_qubit_props, reported_gate_props, + edges_list, *, when=None): + """Fold raw runner output into a full `MeasuredEpoch`. + + Starts from copies of the reported arrays, so any element the benchmark + did not measure — or measured and failed to fit — keeps exactly the value + it had. Only successfully-fitted elements are overwritten and marked in + the masks. Every failure becomes a notice; none becomes an exception. + + Units follow the reported arrays: T1/T2 are stored in microseconds (see + `data.fetch_qubit_prop`), while the experiments report seconds, so those + are converted here. Readout and gate errors are dimensionless in both. + """ + when = time.time() if when is None else when + qubit_props = {k: np.array(v, dtype=float, copy=True) + for k, v in (reported_qubit_props or {}).items()} + gate_props = {k: np.array(v, dtype=float, copy=True) + for k, v in (reported_gate_props or {}).items()} + + n_q = len(next(iter(qubit_props.values()), [])) + n_e = len(next(iter(gate_props.values()), [])) + q_mask = np.zeros(n_q, dtype=bool) + e_mask = np.zeros(n_e, dtype=bool) + notices = [] + + edge_index = {tuple(e): i for i, e in enumerate(edges_list or [])} + two_q_key = _two_qubit_key(gate_props) + + for idx, spec in enumerate(plan.specs): + entry = _lookup(raw, idx) + # An empty sequence counts as "nothing came back" just as None does: + # a runner that returns no analysis results must produce a visible + # notice, never a silent no-op that looks like a successful run. + if entry is None or (isinstance(entry, (list, tuple)) and not entry): + notices.append(f'{spec.kind} {list(spec.qubits)}: no results ' + f'returned, kept reported values') + continue + try: + if spec.kind == 'readout': + _apply_readout(entry, spec, qubit_props, q_mask, n_q, notices) + elif spec.kind in ('t1', 't2hahn'): + _apply_coherence(entry, spec, qubit_props, q_mask, n_q, + notices) + elif spec.kind == 'rb2q': + _apply_rb2q(entry, spec, gate_props, e_mask, edge_index, + two_q_key, notices) + # rb1q is measured at Level 3 for the diagnostic view; it has no + # single reported counterpart to overwrite (the reported arrays + # carry per-gate sx/x/rz errors separately), so it is recorded in + # the notices rather than written into an array. + elif spec.kind == 'rb1q': + _note_rb1q(entry, spec, notices) + except Exception as exc: # noqa: BLE001 - never fatal + _log.warning("benchmark: folding %s %s failed: %s", + spec.kind, spec.qubits, exc, exc_info=True) + notices.append(f'{spec.kind} {list(spec.qubits)}: ' + f'{exc}; kept reported values') + + return MeasuredEpoch(qubit_props, gate_props, q_mask, e_mask, + plan.level, when, notices) + + +def _two_qubit_key(gate_props): + """Which gate array the 2Q RB result should overwrite.""" + for key in ('cz_error', 'rzz_error'): + if key in gate_props: + return key + return None + + +def _apply_readout(entry, spec, qubit_props, q_mask, n_q, notices): + arr = qubit_props.get('readout_error') + if arr is None: + notices.append('readout: no reported readout_error array to update') + return + matrices = _readout_matrices(entry, spec) + if not matrices: + notices.append(f'readout {list(spec.qubits)}: no assignment matrix in ' + f'the results, kept reported values') + return + for qubit, matrix in matrices.items(): + if not (0 <= qubit < n_q): + continue + try: + arr[qubit] = _readout_error_from_matrix(matrix) + q_mask[qubit] = True + except Exception as exc: # noqa: BLE001 - per element + notices.append(f'q{qubit}: readout fit failed ({exc}), ' + f'kept reported value') + + +def _readout_matrices(entry, spec): + """Map physical qubit → 2x2 assignment matrix from a readout result.""" + out = {} + items = entry if isinstance(entry, (list, tuple)) else [entry] + for item in items: + value = getattr(item, 'value', item) + matrix = getattr(value, 'assignment_matrix', None) + if matrix is None and isinstance(value, dict): + matrix = value.get('assignment_matrix') + if matrix is None: + continue + qubits = (getattr(item, 'qubits', None) + or getattr(value, 'qubits', None) or spec.qubits) + matrix = np.asarray(matrix, dtype=float) + if matrix.shape == (2, 2) and len(qubits) == 1: + out[int(qubits[0])] = matrix + elif matrix.ndim == 3: # one 2x2 per qubit, stacked + for pos, q in enumerate(qubits): + if pos < matrix.shape[0]: + out[int(q)] = matrix[pos] + return out + + +def _apply_coherence(entry, spec, qubit_props, q_mask, n_q, notices): + """T1/T2 in seconds from the experiment → microseconds in the arrays.""" + key = 't1' if spec.kind == 't1' else 't2' + arr = qubit_props.get(key) + if arr is None: + notices.append(f'{key}: no reported {key} array to update') + return + items = entry if isinstance(entry, (list, tuple)) else [entry] + if not items: + notices.append(f'{key.upper()} {list(spec.qubits)}: no results, ' + f'kept reported values') + return + for item in items: + qubits = getattr(item, 'qubits', None) or spec.qubits + if not qubits: + continue + qubit = int(qubits[0]) + if not (0 <= qubit < n_q): + continue + try: + seconds = _result_value(item) + if not np.isfinite(seconds) or seconds <= 0: + raise ValueError(f'implausible {key}={seconds}') + arr[qubit] = seconds * 1e6 # data.py stores µs + q_mask[qubit] = True + except Exception as exc: # noqa: BLE001 - per element + notices.append(f'q{qubit}: {key.upper()} fit failed ({exc}), ' + f'kept reported value') + + +def _apply_rb2q(entry, spec, gate_props, e_mask, edge_index, two_q_key, + notices): + """Two-qubit EPG from RB → the backend's 2Q error array for that edge.""" + pair = tuple(spec.qubits) + if two_q_key is None: + notices.append(f'{list(pair)}: no two-qubit error array to update') + return + arr = gate_props.get(two_q_key) + idx = edge_index.get(pair) + if idx is None: + idx = edge_index.get((pair[1], pair[0])) + if idx is None or arr is None or not (0 <= idx < len(arr)): + notices.append(f'{list(pair)}: edge not in the device map, skipped') + return + try: + epg = _epg_from_rb(entry) + if not np.isfinite(epg) or epg < 0: + raise ValueError(f'implausible EPG={epg}') + arr[idx] = epg + e_mask[idx] = True + except Exception as exc: # noqa: BLE001 - per element + notices.append(f'{list(pair)}: RB fit failed ({exc}), ' + f'kept reported value') + + +def _epg_from_rb(entry): + """Error-per-gate out of an RB analysis result set.""" + items = entry if isinstance(entry, (list, tuple)) else [entry] + for item in items: + name = getattr(item, 'name', None) + if name and str(name).upper().startswith('EPG'): + return _result_value(item) + for item in items: # fall back to EPC + name = getattr(item, 'name', None) + if name and str(name).upper().startswith('EPC'): + return _result_value(item) + raise ValueError('no EPG/EPC in RB results') + + +def _note_rb1q(entry, spec, notices): + """Record 1Q RB as a notice: diagnostic, with no single array to own.""" + try: + items = entry if isinstance(entry, (list, tuple)) else [entry] + values = [] + for item in items: + name = getattr(item, 'name', None) + if name and str(name).upper().startswith(('EPG', 'EPC')): + values.append(_result_value(item)) + if values: + notices.append(f'1Q RB: median EPG {np.median(values):.2e} over ' + f'{len(values)} qubit(s)') + except Exception as exc: # noqa: BLE001 - informational + notices.append(f'1Q RB: could not summarise ({exc})') + + +# ── Applying an epoch to the session ──────────────────────────────── + +def apply_measured_epoch(state, epoch): + """Install `epoch` as the session's active calibration. True on success. + + Mirrors `data.apply_history_snapshot`: same shape check, same arrays, same + `delta_mode` reset (a stale delta would render against the previous + epoch). Also attaches the epoch itself as `state._measured_epoch` so the + UI can badge measured elements — see the module docstring on why that is a + runtime attribute rather than a `SessionState` field. + """ + if epoch is None: + return False + n_q = len(state.qubit_ids) if state.qubit_ids else 0 + n_e = len(state.edges_list) if state.edges_list else 0 + qp, gp = epoch.qubit_props, epoch.gate_props + if len(next(iter(qp.values()), [])) != n_q or \ + len(next(iter(gp.values()), [])) != n_e: + return False + + state.qubit_props_data = qp + state.gate_props_data = gp + state.calibration_data_label = ( + f'{state.active_backend_name} — measured {epoch.time_label()} ' + f'(L{epoch.level}, {epoch.n_measured_qubits}q/' + f'{epoch.n_measured_edges}e)') + state.delta_mode = False + setattr(state, '_measured_epoch', epoch) + return True + + +def measured_badge(state, *, qubit=None, edge=None): + """`" (measured)"` when this element came from a benchmark, else `""`. + + Hover-text helper for the UI. Safe to call on a session that has never + benchmarked, which is the common case. + """ + epoch = getattr(state, '_measured_epoch', None) + if epoch is None: + return '' + try: + if qubit is not None: + if 0 <= int(qubit) < len(epoch.measured_qubit_mask) \ + and epoch.measured_qubit_mask[int(qubit)]: + return ' (measured)' + if edge is not None: + if 0 <= int(edge) < len(epoch.measured_edge_mask) \ + and epoch.measured_edge_mask[int(edge)]: + return ' (measured)' + except (TypeError, ValueError): + return '' + return '' + + +# ── Persistence ───────────────────────────────────────────────────── + +_MEASURED_PREFIX = 'measured_' + + +def _measured_dir(backend_name): + from .data import _backend_cache_dir + return _backend_cache_dir(backend_name) + + +def _measured_path(backend_name, when): + stamp = time.strftime('%Y%m%dT%H%M%S', time.localtime(when)) + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{stamp}.json') + + +def save_measured_epoch(backend_name, epoch): + """Write `epoch` beside the reported calibrations. Path, or None. + + Same atomic temp-file-then-rename dance `data._save_calibration` uses, and + the same array-of-lists JSON shape plus the benchmark-specific level, + masks and notices. A save failure is logged and swallowed: losing the + on-disk copy must not lose the epoch the user just paid for, which is + already live on `state`. + """ + try: + path = _measured_path(backend_name, epoch.when) + payload = { + 'when': epoch.when, + 'level': epoch.level, + 'notices': list(epoch.notices), + 'qubit_props': {k: np.asarray(v).tolist() + for k, v in epoch.qubit_props.items()}, + 'gate_props': {k: np.asarray(v).tolist() + for k, v in epoch.gate_props.items()}, + 'measured_qubit_mask': epoch.measured_qubit_mask.tolist(), + 'measured_edge_mask': epoch.measured_edge_mask.tolist(), + } + dirn = _measured_dir(backend_name) + fd, tmp = tempfile.mkstemp(dir=dirn, suffix='.tmp') + try: + with os.fdopen(fd, 'w', encoding='utf-8') as fh: + _json.dump(payload, fh) + os.replace(tmp, path) + except Exception: + try: + os.remove(tmp) + except OSError: + pass + raise + return path + except Exception as exc: # noqa: BLE001 - never fatal + _log.warning("Failed to save measured epoch for %s: %s", + backend_name, exc) + return None + + +def list_measured_epochs(backend_name): + """Saved epoch timestamps for a backend, newest first.""" + try: + dirn = _measured_dir(backend_name) + out = [] + for name in os.listdir(dirn): + if not (name.startswith(_MEASURED_PREFIX) + and name.endswith('.json')): + continue + try: + with open(os.path.join(dirn, name), 'r', encoding='utf-8') as f: + out.append(float(_json.load(f).get('when'))) + except Exception: + _log.debug("skipping unreadable measured epoch %s", name) + return sorted(out, reverse=True) + except Exception: # pragma: no cover - defensive + return [] + + +def load_measured_epoch(backend_name, when): + """Read back a saved epoch by its `when`, or None.""" + try: + path = _measured_path(backend_name, when) + if not os.path.exists(path): + return None + with open(path, 'r', encoding='utf-8') as fh: + data = _json.load(fh) + return MeasuredEpoch( + {k: np.array(v, dtype=float) + for k, v in data['qubit_props'].items()}, + {k: np.array(v, dtype=float) + for k, v in data['gate_props'].items()}, + data['measured_qubit_mask'], data['measured_edge_mask'], + data['level'], float(data['when']), data.get('notices')) + except Exception as exc: # noqa: BLE001 - corrupt file + _log.warning("Failed to load measured epoch %s/%s: %s", + backend_name, when, exc) + return None + + +def latest_reusable_epoch(backend_name, ttl_minutes=REUSE_TTL_MINUTES, + now=None): + """The newest saved epoch still inside the reuse TTL, or None. + + Lets the UI offer "reuse the 14:32 measurement" instead of spending QPU + time again on a sweep the user re-ran two minutes later. + """ + for when in list_measured_epochs(backend_name): + epoch = load_measured_epoch(backend_name, when) + if epoch is not None and epoch.younger_than(ttl_minutes, now): + return epoch + return None + + +# ── Summary line for the UI ───────────────────────────────────────── + +def summary_line(targets, cost, plan_name=None): + """The one-line "what this will cost" string shown before the click.""" + plan_txt = (plan_name or 'unknown').lower() + return (f'Targets: {len(targets.qubits)} qubits · {len(targets.edges)} ' + f'edges · {cost.text} · plan: {plan_txt}') diff --git a/iqmapper/ui/benchmark_panel.py b/iqmapper/ui/benchmark_panel.py new file mode 100644 index 0000000..2d4acd6 --- /dev/null +++ b/iqmapper/ui/benchmark_panel.py @@ -0,0 +1,414 @@ +""" +ui.benchmark_panel.py — sidebar section "5. Benchmark". + +Wires `iqmapper.benchmark` to widgets. The engine stays pure and injectable; +everything network-, thread- or widget-shaped lives here. + +It sits in the sidebar rather than in the Auto tab because benchmarking is a +property of the BACKEND, not of the auto search: it has to serve hand-placed +layouts as readily as swept ones, every circuit slot rather than one, the whole +QPU, and — via the QPU selector — the inter-QPU second panel. + +Three rules this module exists to enforce, and which its tests pin: + + * A benchmark runs only from `btn_bench_run`. Nothing on the connect path, + the refresh path or the multi-QPU scan path reaches into `benchmark`. + * The cost is on screen before the click. The summary line re-computes on + every change to the level, the target mode, the QPU or the candidate + list, and the button stays disabled while the plan is empty or an + acknowledgement the plan gate demands is unticked. + * Everything operates on the SELECTED QPU. With QPU 2 chosen, the targets, + the plan, the run, the epoch, the cache file and the figure refresh all + belong to the secondary session — nothing may leak into the primary. + +Threading follows `ui.inter_qpu`: the QPU work goes to a background worker via +`spawn_bg`, and every widget touch happens on the main thread in the +completion callback, because mutating a widget off the kernel thread silently +drops its comm messages. +""" +import logging + +from ..html_safe import esc + +_log = logging.getLogger(__name__) + + +def setup_benchmark_panel(ctx): + """Wire the benchmark section. Returns a dict of helpers for tests.""" + from .. import benchmark as bench + + primary_state = ctx.state + dd_bench_target = ctx.dd_bench_target + txt_bench_custom = ctx.txt_bench_custom + tb_bench_qpu = ctx.tb_bench_qpu + dd_bench_level = ctx.dd_bench_level + lbl_bench_summary = ctx.lbl_bench_summary + chk_bench_ack = ctx.chk_bench_ack + btn_bench_run = ctx.btn_bench_run + lbl_bench_status = ctx.lbl_bench_status + lbl_bench_reuse = ctx.lbl_bench_reuse + btn_bench_reuse = ctx.btn_bench_reuse + + lucj_all_layouts = ctx.lucj_all_layouts + refresh = ctx.refresh + spawn_bg = getattr(ctx, 'bench_spawn_bg', None) + rescore_cell = getattr(ctx, 'rescore_cell', None) + notices_label = getattr(ctx, 'lbl_lucj_notices', None) + # Filled by ui.inter_qpu once QPU 2 exists; None until then. + qpu2_handles_cell = getattr(ctx, 'qpu2_handles_cell', None) + chk_inter_qpu = getattr(ctx, 'chk_inter_qpu', None) + # Injected for tests; production passes None and the real runner is built + # from the live backend at click time. + runner_factory = getattr(ctx, 'bench_runner_factory', None) + + _last_epoch = [None] + + # ── which QPU are we acting on ────────────────────────────── + def _qpu2(): + """QPU 2's live handles, or None when it is not connected.""" + if qpu2_handles_cell is None or qpu2_handles_cell[0] is None: + return None + try: + return qpu2_handles_cell[0]() + except Exception: + _log.debug("QPU 2 handles unavailable", exc_info=True) + return None + + def _qpu2_available(): + return bool(getattr(chk_inter_qpu, 'value', False)) and \ + _qpu2() is not None + + def active_target(): + """(state, refresh_callable) for the QPU the selector points at. + + Everything downstream goes through this, which is what keeps a QPU-2 + benchmark out of the primary session: there is one place that decides + whose state is being measured. + """ + if tb_bench_qpu.value == 2: + handles = _qpu2() + if handles is not None: + return handles.state, _make_qpu2_refresh(handles) + return primary_state, refresh + + def _make_qpu2_refresh(handles): + """Repaint QPU 2's own figure, not QPU 1's.""" + def _refresh2(): + from .. import plot as _plot + if handles.fig is not None and handles.widgets is not None: + _plot.refresh_plot(handles.fig, handles.state, handles.widgets) + return _refresh2 + + def _sync_qpu_selector(): + """Show the QPU toggle only while QPU 2 is actually there.""" + available = _qpu2_available() + tb_bench_qpu.layout.display = '' if available else 'none' + if not available and tb_bench_qpu.value != 1: + tb_bench_qpu.value = 1 + + # ── plan (subscription) detection ─────────────────────────── + def _plan_name(): + """Best-effort subscription name, cached on state for the session. + + Read-only and never blocking: qiskit-ibm-runtime has moved this around + between versions, so every lookup is attempted defensively and any + failure simply yields None, which `plan_gate` treats as Open. + """ + state, _r = active_target() + cached = getattr(state, '_plan_name_cache', None) + if cached is not None: + return None if cached == '__none__' else cached + name = None + try: + service = getattr(state, 'active_service', None) + if service is not None: + for attr in ('active_account', 'instance'): + try: + got = getattr(service, attr, None) + got = got() if callable(got) else got + except Exception: + continue + if isinstance(got, dict): + name = got.get('plan') or got.get('plan_name') + elif isinstance(got, str): + name = got + if name: + break + if not name: + try: + instances = service.instances() + if instances: + first = instances[0] + name = (first.get('plan') + if isinstance(first, dict) else None) + except Exception: + pass + except Exception: + _log.debug("plan detection failed; assuming Open", exc_info=True) + setattr(state, '_plan_name_cache', name or '__none__') + return name + + # ── target modes ──────────────────────────────────────────── + def _sweep_result(): + """Sweep candidates belong to QPU 1's Auto tab; QPU 2 has none.""" + return list(lucj_all_layouts) if tb_bench_qpu.value == 1 else [] + + def _sync_target_options(): + """Offer only the modes that would resolve to something.""" + state, _r = active_target() + modes = bench.available_target_modes(state, _sweep_result()) + options = [(bench.TARGET_LABELS[m], m) for m in modes] + if list(dd_bench_target.options) != options: + previous = dd_bench_target.value + dd_bench_target.options = options + dd_bench_target.value = ( + previous if previous in modes + else bench.default_target_mode(state, _sweep_result())) + txt_bench_custom.layout.display = ( + '' if dd_bench_target.value == bench.TARGET_CUSTOM else 'none') + + def _current_plan(): + state, _r = active_target() + targets = bench.select_targets( + state, _sweep_result(), mode=dd_bench_target.value, + custom=txt_bench_custom.value) + n_qubits = len(getattr(state, 'qubit_ids', None) or []) + coupling = getattr(state, 'edges_list', None) or [] + level = dd_bench_level.value or bench.LEVEL_QUICK_READOUT + return targets, bench.build_plan(level, targets, n_qubits, coupling) + + # ── summary + gating ──────────────────────────────────────── + def refresh_summary(*_a): + """Recompute the cost line and the button's enabled state.""" + try: + _sync_qpu_selector() + if not bench.have_qiskit_experiments(): + lbl_bench_summary.value = ( + "
" + "Install the benchmark extra: " + "pip install \"i-qmapper[benchmark]\"
") + btn_bench_run.disabled = True + return + _sync_target_options() + targets, plan = _current_plan() + cost = bench.estimate_cost(plan) + level = dd_bench_level.value or bench.LEVEL_QUICK_READOUT + plan_name = _plan_name() + gate = bench.plan_gate(plan_name, level) + needs_ack = bench.requires_acknowledgement(plan_name, level) + + extra = '' + if dd_bench_target.value == bench.TARGET_WHOLE: + if level == bench.LEVEL_QUICK_READOUT: + extra = ("
Readout is two " + "circuits whatever the width — whole-QPU Level 1 " + "is the cheap heatmap refresh.") + elif level == bench.LEVEL_FULL: + extra = ("
Full-chip suite " + "≈ 4 min of QPU") + needs_ack = True + warn = (f"
⚠ " + f"{esc(gate.warning)}") if gate.warning else '' + + lbl_bench_summary.value = ( + f"
{esc(bench.summary_line(targets, cost, plan_name))}" + f"{extra}{warn}
") + + chk_bench_ack.layout.display = '' if needs_ack else 'none' + btn_bench_run.disabled = bool( + (not plan.specs) or (needs_ack and not chk_bench_ack.value)) + _refresh_reuse_offer() + except Exception: + _log.exception("Benchmark summary refresh failed") + btn_bench_run.disabled = True + + def _refresh_reuse_offer(): + """Offer a saved epoch — per backend — instead of re-spending QPU.""" + try: + state, _r = active_target() + name = getattr(state, 'active_backend_name', None) + epoch = bench.latest_reusable_epoch(name) if name else None + _last_epoch[0] = epoch + if epoch is None: + lbl_bench_reuse.value = '' + btn_bench_reuse.disabled = True + btn_bench_reuse.layout.display = 'none' + return + lbl_bench_reuse.value = ( + f"
" + f"Reuse (measured {esc(epoch.time_label())}, " + f"L{epoch.level})
") + btn_bench_reuse.disabled = False + btn_bench_reuse.layout.display = '' + except Exception: + _log.debug("reuse offer unavailable", exc_info=True) + + # ── applying an epoch ─────────────────────────────────────── + def _install_epoch(epoch, *, source): + """Apply, refresh, re-rank, surface notices. Main thread only.""" + state, refresh_fn = active_target() + if not bench.apply_measured_epoch(state, epoch): + lbl_bench_status.value = _err( + 'Measured epoch does not match the current device ' + '(qubit/edge count changed) — reported calibration kept.') + return False + try: + refresh_fn() + except Exception: + _log.exception("plot refresh after benchmark failed") + + n_ranked = 0 + # The Auto candidate list belongs to QPU 1; re-ranking it against a + # QPU-2 epoch would be meaningless (different device, different props). + if tb_bench_qpu.value == 1 and rescore_cell is not None \ + and rescore_cell[0] is not None: + try: + n_ranked = rescore_cell[0]() or 0 + except Exception: + _log.exception("candidate re-ranking after benchmark failed") + + if notices_label is not None and epoch.notices: + notices_label.value = ( + "
⚠ " + + "
".join(esc(n) for n in epoch.notices) + "
") + + rank_txt = f" · {n_ranked} candidate(s) re-ranked" if n_ranked else '' + qpu_txt = f"QPU {tb_bench_qpu.value} · " if _qpu2_available() else '' + lbl_bench_status.value = ( + f"
✅ {esc(qpu_txt)}{esc(source)}: measured " + f"epoch applied ({epoch.n_measured_qubits}q/" + f"{epoch.n_measured_edges}e, L{epoch.level}){rank_txt}
") + _refresh_reuse_offer() + return True + + def _err(msg): + return (f"
❌ {esc(str(msg))}
") + + # ── run ───────────────────────────────────────────────────── + def _on_run(_b=None): + state, _refresh_fn = active_target() + try: + _targets, plan = _current_plan() + except Exception as exc: # noqa: BLE001 - reported + lbl_bench_status.value = _err(exc) + return + if not plan.specs: + lbl_bench_status.value = _err( + 'No qubits to measure for this target selection.') + return + + level = plan.level + plan_name = _plan_name() + needs_ack = (bench.requires_acknowledgement(plan_name, level) + or (dd_bench_target.value == bench.TARGET_WHOLE + and level == bench.LEVEL_FULL)) + if needs_ack and not chk_bench_ack.value: + lbl_bench_status.value = _err( + 'Tick "I understand this uses QPU time" to run this level.') + return + + cost = bench.estimate_cost(plan) + btn_bench_run.disabled = True + + # Import the quantum stack HERE, on the main thread, before any worker + # starts. Importing it from the worker publishes half-built modules + # into sys.modules while the kernel thread is still serving widget + # events, and a map click mid-import then dies on "partially + # initialized module 'pandas'". See benchmark.preload_runtime. + if runner_factory is None: + if not bench.runtime_ready(): + lbl_bench_status.value = ( + "
" + "⏳ Loading benchmark libraries…
") + try: + bench.preload_runtime() + except Exception as exc: # noqa: BLE001 - reported + btn_bench_run.disabled = False + lbl_bench_status.value = _err(exc) + return + + lbl_bench_status.value = ( + f"
⏳ Running L{level} " + f"benchmark ({esc(cost.text)})…
") + + reported_q = dict(getattr(state, 'qubit_props_data', {}) or {}) + reported_g = dict(getattr(state, 'gate_props_data', {}) or {}) + edges = list(getattr(state, 'edges_list', None) or []) + backend_name = getattr(state, 'active_backend_name', None) + + def _work(): + """Background: build the runner and spend the QPU time.""" + if runner_factory is not None: + runner = runner_factory(state) + else: + runner = bench.make_runtime_runner( + getattr(state, 'active_backend', None)) + return bench.run_plan(plan, runner) + + def _done(raw): + """Main thread: fold, apply, persist.""" + btn_bench_run.disabled = False + try: + epoch = bench.results_to_epoch(raw, plan, reported_q, + reported_g, edges) + except Exception as exc: # noqa: BLE001 - reported + _log.exception("folding benchmark results failed") + lbl_bench_status.value = _err(exc) + return + if _install_epoch(epoch, source=f'L{level} benchmark') \ + and backend_name: + bench.save_measured_epoch(backend_name, epoch) + + def _failed(exc): + """Main thread: the reported epoch is left exactly as it was.""" + btn_bench_run.disabled = False + _log.exception("benchmark run failed: %s", exc) + lbl_bench_status.value = _err(exc) + + if spawn_bg is None: # no runner injected: inline + try: + _done(_work()) + except Exception as exc: # noqa: BLE001 - reported + _failed(exc) + return + spawn_bg(_work, on_done=_done, on_error=_failed) + + def _on_reuse(_b=None): + epoch = _last_epoch[0] + if epoch is None: + lbl_bench_status.value = _err('No recent measurement to reuse.') + return + _install_epoch(epoch, source='Reused measurement') + + btn_bench_run.on_click(_on_run) + btn_bench_reuse.on_click(_on_reuse) + for widget in (dd_bench_level, dd_bench_target, chk_bench_ack, + tb_bench_qpu, txt_bench_custom): + widget.observe(refresh_summary, names='value') + if chk_inter_qpu is not None: + chk_inter_qpu.observe(refresh_summary, names='value') + refresh_summary() + + return { + 'refresh_summary': refresh_summary, + 'run': _on_run, + 'reuse': _on_reuse, + 'plan_name': _plan_name, + 'current_plan': _current_plan, + 'active_target': active_target, + 'qpu2_available': _qpu2_available, + } diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index af9af25..a18c84d 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -309,6 +309,14 @@ def _run_pipeline(self): # (reveal QPU-2 + prefill dropdown + stage candidate). Same # deferred-wiring pattern as the QPU-1 title-refresh cell. self._inter_qpu_handoff = [None] + # Shared cell: ui.lucj_panel populates [0] with the candidate + # re-ranking hook, which ui.benchmark_panel calls after installing a + # measured epoch. Same deferred-wiring pattern as the handoff cell. + self._bench_rescore = [None] + # Shared cell: ui.inter_qpu publishes a read-only accessor for QPU 2's + # live state/figure here, so the benchmark panel — built before + # setup_inter_qpu runs — can reach QPU 2 once it connects. + self._qpu2_handles = [None] _lucj_ctx = _NS( state=state, out=self.out, W=W, lucj_norb_slider=self.lucj_norb_slider, lucj_ancilla_dd=self.lucj_ancilla_dd, @@ -333,6 +341,7 @@ def _run_pipeline(self): num_circuits=self.num_circuits, intra_qpu_mode=self.intra_qpu_mode, dd_mode=self.dd_mode, set_num_circuits=self._set_num_circuits_silent, lucj_all_layouts=self._lucj_all_layouts, + rescore_cell=self._bench_rescore, lucj_multi_results=self._lucj_multi_results, lucj_multi_norbs_list=self._lucj_multi_norbs, lucj_multi_ancillas_list=self._lucj_multi_ancillas, @@ -360,6 +369,34 @@ def _run_pipeline(self): setup_lucj_callbacks(_lucj_ctx) self._refresh_stability_filter_availability() + # ── 📡 Benchmark section (ui.benchmark_panel) ──────────────── + # After setup_lucj_callbacks, so the re-ranking hook cell is filled + # by the time the panel could call it. Opt-in only: nothing here + # runs unless the user clicks Run benchmark. + from .benchmark_panel import setup_benchmark_panel + _bench_ctx = _NS( + state=state, + dd_bench_target=self.dd_bench_target, + txt_bench_custom=self.txt_bench_custom, + tb_bench_qpu=self.tb_bench_qpu, + dd_bench_level=self.dd_bench_level, + lbl_bench_summary=self.lbl_bench_summary, + chk_bench_ack=self.chk_bench_ack, + btn_bench_run=self.btn_bench_run, + lbl_bench_status=self.lbl_bench_status, + lbl_bench_reuse=self.lbl_bench_reuse, + btn_bench_reuse=self.btn_bench_reuse, + lbl_lucj_notices=self.lbl_lucj_notices, + lucj_all_layouts=self._lucj_all_layouts, + rescore_cell=self._bench_rescore, + refresh=self._refresh, + chk_inter_qpu=self.chk_inter_qpu, + qpu2_handles_cell=self._qpu2_handles, + bench_spawn_bg=default_spawn_bg, + bench_runner_factory=None, # production: built at click time + ) + self._bench_api = setup_benchmark_panel(_bench_ctx) + # ── PNG save popup ─────────────────────────────────────────── # ui.png_export builds the popup + sliders + checkbox and wires # btn_save_img.on_click. We capture png_popup so the export tab @@ -557,6 +594,7 @@ def _run_pipeline(self): qpu2_fig_box=_qpu2_fig_box, full_ui=full_ui, handoff_cell=self._inter_qpu_handoff, + qpu2_handles_cell=self._qpu2_handles, )) return full_ui, self.fig @@ -1288,6 +1326,79 @@ def _build_auto_lucj_widgets(self, W): "different chip regions (Jaccard ≤ 0.8). The top half " "is always the absolute best — diversity never " "demotes it.") + # ── 📡 Benchmark widgets (mounted as sidebar section 5) ─── + # Never automatic: see iqmapper/benchmark.py. The target dropdown, + # level dropdown, cost line and acknowledgement all exist so the QPU + # cost is on screen before the button can be clicked. + # + # Benchmarking is a property of the BACKEND, not of the auto search, + # so this lives in the sidebar rather than in the Auto tab: it has to + # serve hand-placed layouts, every circuit slot, the whole QPU, and + # the inter-QPU second panel. + from .. import benchmark as _bench + # Its OWN Layout: benchmark_panel toggles .layout.display on this to + # hide the field unless Custom is selected, and the shared `W` + # instance would hide every widget built with W. + _own = lambda: Layout(width=W.width, margin=W.margin, + min_width=W.min_width) + self.dd_bench_target = Dropdown( + options=[(_bench.TARGET_LABELS[_bench.TARGET_CURRENT], + _bench.TARGET_CURRENT)], + value=_bench.TARGET_CURRENT, + description='Targets:', + layout=Layout(width='280px'), + style={'description_width': '110px'}, + tooltip='What to measure: the placed layout(s), the last sweep\'s ' + 'top candidates, the whole QPU, or an explicit qubit list.') + _custom_layout = _own() + _custom_layout.display = 'none' # revealed only for Targets=Custom + self.txt_bench_custom = Text( + value='', description='Qubits:', placeholder='0, 1, 2, 5, 8', + layout=_custom_layout, style={'description_width': '110px'}) + _qpu_layout = _own() + _qpu_layout.display = 'none' # revealed only when QPU 2 is up + self.tb_bench_qpu = ToggleButtons( + options=[('QPU 1', 1), ('QPU 2', 2)], value=1, + layout=_qpu_layout) + self.dd_bench_level = Dropdown( + options=_bench.LEVEL_OPTIONS, + value=_bench.LEVEL_QUICK_READOUT, + description='Level:', + layout=Layout(width='280px'), + style={'description_width': '110px'}, + tooltip='1 = readout (2 circuits, cost does not grow with qubit ' + 'count); 2 = adds 2Q RB on the target edges; ' + '3 = the full-chip tutorial suite (~4 min).') + self.lbl_bench_summary = HTML("") + self.chk_bench_ack = Checkbox( + value=False, + description='I understand this uses QPU time', + layout=_own()) + self.btn_bench_run = Button( + description='📡 Run benchmark', + button_style='warning', layout=W, disabled=True) + self.lbl_bench_reuse = HTML("") + self.btn_bench_reuse = Button( + description='Reuse', button_style='info', disabled=True, + layout=Layout(width='120px', margin='2px 0px')) + self.lbl_bench_status = HTML("") + self.bench_box = VBox([ + HTML("
Re-measure the live device and re-rank " + "against what the hardware is doing now. Opt-in: nothing " + "runs until you click.
"), + self.tb_bench_qpu, + self.dd_bench_target, + self.txt_bench_custom, + self.dd_bench_level, + self.lbl_bench_summary, + self.chk_bench_ack, + self.btn_bench_run, + HBox([self.lbl_bench_reuse, self.btn_bench_reuse], + layout=Layout(align_items='center')), + self.lbl_bench_status, + ], layout=W) + # Expert knobs, collapsed out of the primary flow (ancilla dropdown # -> Run). The defaults are right for nearly everyone, and the notices # bar already reports when the cap truncated a search. @@ -3530,11 +3641,20 @@ def _assemble_sidebar(self): self.chk_inter_qpu, self.dd_backend_qpu2, self.btn_connect_qpu2, self.lbl_qpu2_status] )), + # 5th section: benchmarking. A property of the backend, so it + # belongs beside Hardware rather than inside the Auto search. + VBox([ + HTML("
📡 Real-time benchmarking" + "
"), + self.bench_box, + ]), ]) acc_settings.set_title(0, '1. Hardware') acc_settings.set_title(1, '2. Display') acc_settings.set_title(2, '3. Colors') acc_settings.set_title(3, '4. Multi-Programming') + acc_settings.set_title(4, '5. Benchmark') sidebar_title = HTML( f"

🎛️ QPU Map Editor

" diff --git a/iqmapper/ui/inter_qpu.py b/iqmapper/ui/inter_qpu.py index 780b510..19a2f1a 100644 --- a/iqmapper/ui/inter_qpu.py +++ b/iqmapper/ui/inter_qpu.py @@ -33,6 +33,7 @@ """ import contextlib import logging +from types import SimpleNamespace from ipywidgets import VBox, HTML, ToggleButtons @@ -615,6 +616,28 @@ def _error(exc): # the worker fetch itself raised _spawn_bg(lambda: _connect_qpu2_fetch(backend_name), on_done=_paint, on_error=_error) + def qpu2_handles(): + """Read-only view of QPU 2's live objects, for other panels. + + `ui.benchmark_panel` needs the secondary state, figure and widget-ref + to benchmark QPU 2, and these live in closure cells with no other + handle. Returns a snapshot namespace (or None when QPU 2 is not + connected) rather than the cells themselves, so a caller can read the + current objects but cannot rebind them and desynchronise the panel. + """ + if _state2[0] is None: + return None + return SimpleNamespace( + state=_state2[0], fig=_fig2[0], widgets=_w2[0], + backend_name=getattr(_state2[0], 'active_backend_name', None), + connected=True) + + # Publish the accessor on the shared cell so the benchmark panel — built + # before this function runs — can reach QPU 2 once it exists. + _qpu2_handles_cell = getattr(ctx, 'qpu2_handles_cell', None) + if _qpu2_handles_cell is not None: + _qpu2_handles_cell[0] = qpu2_handles + # Expose the label-refresh hook so ui.backend_switch can call it after a # backend switch (the switcher has no other handle on this closure). return refresh_qpu1_label diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 4dc0fd3..90e8e98 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -684,6 +684,61 @@ def _on_lucj_generate(b): btn_lucj_run.on_click(_on_lucj_generate) + # ── re-score the current candidates under a new epoch ───────── + def _rescore_current_candidates(): + """Re-rank the candidate dropdown against the CURRENT epoch. + + Called after `benchmark` installs a measured epoch: the entries were + ranked on the reported calibration, and the whole point of measuring + is that the ordering may now be different. Re-scores through the same + `_circuit_score` path the sweep itself uses, so the numbers stay + comparable, then re-seeds the dropdown in the sweep's own label + format. Legacy (explicit-count) entries carry 'score' instead of + 'lqs_circuit' and are left alone — they are not LQS-ranked. + + Returns the number of entries re-scored. Never raises: a benchmark + that succeeded must not be undone by a re-ranking problem. + """ + entries = list(_lucj_all_layouts) + if not entries or not any('lqs_circuit' in e for e in entries): + return 0 + try: + for entry in entries: + if 'lqs_circuit' in entry: + try: + entry['lqs_circuit'] = _circuit_score(entry) + except Exception: + entry['lqs_circuit'] = None + ranked = sorted( + entries, + key=lambda e: (e.get('lqs_circuit') is not None, + e.get('lqs_circuit') or 0.0), + reverse=True) + dd_opts = [] + for i, entry in enumerate(ranked): + pct, is_tmpl = _entry_lqs_pct(entry) + suffix = " (template)" if is_tmpl else "" + alt = " · alt region" if entry.get('diverse') else "" + k = entry.get('n_ancillas', len(entry.get('ancillas') or [])) + dd_opts.append(( + f"k={k} · #{entry.get('rank_in_stratum', i + 1)} · " + f"LQS {pct}{suffix}{alt} · measured", i)) + _seed_layout_dropdown(ranked, dd_opts) + circ = [e['lqs_circuit'] for e in ranked + if e.get('lqs_circuit') is not None] + _local_best_lqs[0] = max(circ) if circ else None + return len(ranked) + except Exception: + _log.exception("Re-ranking candidates under the measured epoch " + "failed; the epoch itself is applied") + return 0 + + # Deferred wiring: ui.benchmark_panel calls this after applying a measured + # epoch. Same single-element-cell pattern as the inter-QPU handoff hook. + _rescore_cell = getattr(ctx, 'rescore_cell', None) + if _rescore_cell is not None: + _rescore_cell[0] = _rescore_current_candidates + # ── sweep mode always scores → hide the score checkbox ─────── def _on_ancilla_mode_change(change=None): # 'Auto' (-1) == sweep mode; the engine always computes LQS there, diff --git a/pyproject.toml b/pyproject.toml index 53864be..e24fee8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = [ ] [project.optional-dependencies] +benchmark = ["qiskit-experiments>=0.12"] png = ["kaleido"] timelapse = ["imageio", "imageio-ffmpeg"] dev = ["pytest>=7", "pytest-cov"] diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 87e1cae..ca94d71 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -39,7 +39,9 @@ def _build(monkeypatch): state.custom_colors = [] state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) - b.build() + # build() returns the assembled tree rather than storing it; keep it so + # tests can walk the real sidebar/figure widget graph. + b._test_full_ui, _fig = b.build() return b, state @@ -168,3 +170,61 @@ def test_score_checkbox_owns_its_layout(monkeypatch): # The visual properties W supplied are preserved on the private copy. assert (chk.layout.width, chk.layout.margin) == \ (b.chk_lucj_diverse.layout.width, b.chk_lucj_diverse.layout.margin) + + +# ── t5: benchmark lives in the sidebar, not the Auto tab ─────────────────── + +def _sidebar_accordion(b): + """The numbered settings accordion from the assembled sidebar.""" + from ipywidgets import Accordion + for w in _descendants(b._test_full_ui): + if isinstance(w, Accordion) and w.get_title(0) == '1. Hardware': + return w + raise AssertionError('numbered settings accordion not found') + + +def test_benchmark_is_sidebar_section_5_not_an_auto_tab_block(monkeypatch): + """Benchmarking is a property of the BACKEND, so it belongs beside + Hardware — it has to serve hand-placed layouts, every circuit slot, the + whole QPU and the inter-QPU second panel, none of which the Auto tab + covers.""" + b, _ = _build(monkeypatch) + + acc = _sidebar_accordion(b) + assert acc.get_title(3) == '4. Multi-Programming' + assert acc.get_title(4) == '5. Benchmark', 'section 5 missing' + assert any(w is b.bench_box for w in _descendants(acc.children[4])), \ + 'the benchmark controls are not inside section 5' + + # ...and gone from the Auto tab. + b._build_auto_lucj_view() + auto = _descendants(b._auto_single_panel) + for widget, name in ((b.bench_box, 'bench_box'), + (b.btn_bench_run, 'btn_bench_run'), + (b.dd_bench_target, 'dd_bench_target')): + assert not any(w is widget for w in auto), \ + f'{name} still mounted in the Auto tab' + + +def test_benchmark_widgets_do_not_share_a_mutated_layout(monkeypatch): + """Same bug class as the score checkbox: `W` is ONE shared Layout, so a + widget whose .layout.display is toggled at runtime must own its own.""" + b, _ = _build(monkeypatch) + mutated = [('txt_bench_custom', b.txt_bench_custom), + ('tb_bench_qpu', b.tb_bench_qpu), + ('chk_bench_ack', b.chk_bench_ack), + ('btn_bench_reuse', b.btn_bench_reuse)] + + everything = _descendants(b._test_full_ui) + for name, widget in mutated: + assert widget.layout is not b.txt_auto.layout, ( + f'{name} shares the shared W Layout — toggling its display ' + f'would hide every widget built with W') + sharers = [w for w in everything + if getattr(w, 'layout', None) is widget.layout] + assert len(set(id(w) for w in sharers)) <= 1, ( + f'{name} shares its Layout with {len(sharers) - 1} other widget(s)') + + # Hidden-by-default widgets really do start hidden. + assert b.txt_bench_custom.layout.display == 'none' + assert b.tb_bench_qpu.layout.display == 'none' diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py new file mode 100644 index 0000000..db4bdc5 --- /dev/null +++ b/tests/test_benchmark.py @@ -0,0 +1,542 @@ +"""Engine tests for iqmapper.benchmark — target selection, planning, costing, +result folding, persistence and plan gating. + +Entirely offline: the runner is injected, so nothing imports qiskit_experiments +or touches a network. That is the same discipline qpu_scan.py's tests use, and +it is what makes a feature that spends QPU time safe to develop. +""" +from types import SimpleNamespace + +import numpy as np +import pytest + +from iqmapper import benchmark as bench + + +# ── fixtures / helpers ────────────────────────────────────────────── + +def _line_edges(n): + return [(i, i + 1) for i in range(n - 1)] + + +def _state(n_qubits=8, edges=None, layouts=None): + edges = _line_edges(n_qubits) if edges is None else edges + return SimpleNamespace( + qubit_ids=[str(i) for i in range(n_qubits)], + edges_list=list(edges), + layouts_data=layouts or {}, + active_backend_name='ibm_test', + qubit_props_data={}, gate_props_data={}, + calibration_data_label='', delta_mode=True) + + +def _entry(alpha, beta, ancillas): + return {'alpha': list(alpha), 'beta': list(beta), + 'ancillas': list(ancillas)} + + +def _reported(n_q=8, n_e=7): + return ({'readout_error': np.full(n_q, 0.05), + 't1': np.full(n_q, 100.0), # microseconds, as data.py stores + 't2': np.full(n_q, 80.0)}, + {'cz_error': np.full(n_e, 0.01)}) + + +class _Res: + """Stand-in for a qiskit-experiments AnalysisResult.""" + + def __init__(self, name=None, value=None, qubits=None, + assignment_matrix=None): + self.name = name + self.qubits = qubits + if assignment_matrix is not None: + self.value = SimpleNamespace(assignment_matrix=assignment_matrix) + else: + self.value = value + + +# ── 1. select_targets ─────────────────────────────────────────────── + +def test_select_targets_unions_top_k_entries(): + state = _state(8) + entries = [_entry([0, 1], [2], [3]), + _entry([4, 5], [6], []), + _entry([7], [], [])] # outside top_k=2 + targets = bench.select_targets(state, entries, top_k=2) + + assert targets.qubits == [0, 1, 2, 3, 4, 5, 6] + assert 7 not in targets.qubits, "top_k must bound the union" + # Every coupling edge whose BOTH endpoints are targets, including (3, 4), + # which bridges the two candidates: the union is what gets measured, so an + # edge inside it counts even though no single candidate contains it. + assert targets.edges == [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] + # ...and nothing touching the excluded qubit 7. + assert all(7 not in e for e in targets.edges) + + +def test_select_targets_accepts_raw_sweep_dict(): + state = _state(8) + raw = {'strata': {1: [_entry([0, 1], [2], [3])], + 2: [_entry([4], [5], [])]}} + targets = bench.select_targets(state, raw, top_k=5) + assert set(targets.qubits) == {0, 1, 2, 3, 4, 5} + + +def test_select_targets_falls_back_to_current_layout(): + state = _state(8, layouts={0: {'alpha': ['1', '2'], 'beta': ['3'], + 'ancilla': [], 'other': []}}) + targets = bench.select_targets(state, None) + assert targets.qubits == [1, 2, 3] + assert targets.edges == [(1, 2), (2, 3)] + + +def test_select_targets_empty_when_nothing_to_measure(): + targets = bench.select_targets(_state(8), None) + assert targets == bench.Targets([], []) + + +def test_select_targets_normalizes_edge_orientation(): + """An edge the device lists as (5, 4) must not be emitted as (4, 5).""" + state = _state(6, edges=[(1, 0), (2, 1), (3, 2), (5, 4), (4, 3)]) + targets = bench.select_targets(state, [_entry([0, 1, 2], [3, 4], [5])]) + for edge in targets.edges: + assert edge in state.edges_list, f'{edge} not in device orientation' + + +# ── 2. build_plan ─────────────────────────────────────────────────── + +def test_level1_is_readout_on_target_qubits_only(): + targets = bench.Targets([0, 1, 2], [(0, 1), (1, 2)]) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, targets, 8, + _line_edges(8)) + assert [s.kind for s in plan.specs] == ['readout'] + assert plan.specs[0].qubits == (0, 1, 2) + + +def test_level2_adds_layered_2q_rb_over_target_edges_only(): + targets = bench.Targets([0, 1, 2, 3], [(0, 1), (1, 2), (2, 3)]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, 8, _line_edges(8)) + + kinds = [s.kind for s in plan.specs] + assert kinds.count('readout') == 1 + rb = [s for s in plan.specs if s.kind == 'rb2q'] + assert {s.qubits for s in rb} == {(0, 1), (1, 2), (2, 3)}, \ + 'only TARGET edges may be benchmarked' + assert all(s.params['lengths'] == bench.RB_2Q_LENGTHS for s in rb) + assert all(s.params['num_samples'] == bench.RB_2Q_SAMPLES for s in rb) + + # No two experiments in one layer may share a qubit. + by_layer = {} + for spec in rb: + by_layer.setdefault(spec.layer, []).append(set(spec.qubits)) + for layer, pairs in by_layer.items(): + seen = set() + for pair in pairs: + assert not (seen & pair), f'layer {layer} reuses a qubit' + seen |= pair + + +def test_level3_covers_the_whole_chip_with_tutorial_parameters(): + plan = bench.build_plan(bench.LEVEL_FULL, bench.Targets([], []), 8, + _line_edges(8)) + kinds = {s.kind for s in plan.specs} + assert kinds == {'t1', 't2hahn', 'readout', 'rb1q', 'rb2q'} + + t1 = next(s for s in plan.specs if s.kind == 't1') + assert t1.params['delays'] == bench.T1T2_DELAYS + assert t1.qubits == tuple(range(8)), 'L3 ignores targets, covers the chip' + + rb1 = next(s for s in plan.specs if s.kind == 'rb1q') + assert rb1.params['lengths'] == bench.RB_1Q_LENGTHS + assert rb1.params['num_samples'] == bench.RB_1Q_SAMPLES + + rb2 = {s.qubits for s in plan.specs if s.kind == 'rb2q'} + assert rb2 == set(_line_edges(8)), 'L3 benchmarks every coupling edge' + assert plan.shots == bench.DEFAULT_SHOTS == 1000 + + +def test_empty_targets_produce_an_empty_plan(): + plan = bench.build_plan(bench.LEVEL_TARGETED, bench.Targets([], []), 8, + _line_edges(8)) + assert plan.specs == [] + + +# ── 3. estimate_cost ──────────────────────────────────────────────── + +def test_cost_is_monotonic_in_level_and_in_target_count(): + targets = bench.Targets([0, 1, 2, 3], [(0, 1), (1, 2), (2, 3)]) + coupling = _line_edges(20) + costs = [bench.estimate_cost( + bench.build_plan(lvl, targets, 20, coupling)).qpu_seconds + for lvl in (1, 2, 3)] + assert costs[0] < costs[1] < costs[2], costs + + small = bench.Targets([0, 1], [(0, 1)]) + big = bench.Targets(list(range(10)), _line_edges(10)) + c_small = bench.estimate_cost(bench.build_plan(2, small, 20, coupling)) + c_big = bench.estimate_cost(bench.build_plan(2, big, 20, coupling)) + assert c_big.qpu_seconds > c_small.qpu_seconds + assert c_big.circuits > c_small.circuits + + +def test_full_chip_127q_matches_the_tutorial_figure(): + """The cost constants are calibrated against the tutorial's ~240 s.""" + coupling = _line_edges(127) + plan = bench.build_plan(bench.LEVEL_FULL, bench.Targets([], []), 127, + coupling) + seconds = bench.estimate_cost(plan).qpu_seconds + assert 240 * 0.7 <= seconds <= 240 * 1.3, ( + f'full-chip estimate {seconds:.0f}s is outside 240s +/-30%') + + +def test_empty_plan_costs_nothing(): + plan = bench.build_plan(1, bench.Targets([], []), 8, _line_edges(8)) + cost = bench.estimate_cost(plan) + assert cost.circuits == 0 and cost.qpu_seconds == 0.0 + + +# ── 4. results_to_epoch ───────────────────────────────────────────── + +def test_measured_values_override_only_measured_elements(): + qp, gp = _reported() + targets = bench.Targets([1, 2], [(1, 2)]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, 8, _line_edges(8)) + + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + raw[idx] = [_Res(qubits=[1], + assignment_matrix=[[0.9, 0.1], [0.2, 0.8]]), + _Res(qubits=[2], + assignment_matrix=[[0.97, 0.03], [0.01, 0.99]])] + elif spec.kind == 'rb2q': + raw[idx] = [_Res(name='EPG', value=0.004)] + + epoch = bench.results_to_epoch(raw, plan, qp, gp, _line_edges(8)) + + # measured + assert epoch.qubit_props['readout_error'][1] == pytest.approx(0.15) + assert epoch.qubit_props['readout_error'][2] == pytest.approx(0.02) + assert epoch.gate_props['cz_error'][bench_edge_index(1, 2)] == \ + pytest.approx(0.004) + # untouched + for q in (0, 3, 4, 5, 6, 7): + assert epoch.qubit_props['readout_error'][q] == pytest.approx(0.05) + assert epoch.gate_props['cz_error'][0] == pytest.approx(0.01) + # masks + assert list(np.where(epoch.measured_qubit_mask)[0]) == [1, 2] + assert list(np.where(epoch.measured_edge_mask)[0]) == [bench_edge_index(1, 2)] + # the reported arrays passed in must not be mutated in place + assert qp['readout_error'][1] == pytest.approx(0.05) + + +def bench_edge_index(a, b): + return _line_edges(8).index((a, b)) + + +def test_fit_failure_keeps_reported_value_and_emits_a_notice(): + qp, gp = _reported() + targets = bench.Targets([1, 2], [(1, 2)]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, 8, _line_edges(8)) + + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + raw[idx] = [_Res(qubits=[1], + assignment_matrix=[[0.9, 0.1], [0.2, 0.8]])] + elif spec.kind == 'rb2q': + raw[idx] = [_Res(name='EPG', value=float('nan'))] # bad fit + + epoch = bench.results_to_epoch(raw, plan, qp, gp, _line_edges(8)) + + assert epoch.gate_props['cz_error'][bench_edge_index(1, 2)] == \ + pytest.approx(0.01), 'a failed fit must keep the reported value' + assert not epoch.measured_edge_mask.any() + assert any('RB fit failed' in n for n in epoch.notices), epoch.notices + + +def test_missing_results_are_a_notice_not_a_crash(): + qp, gp = _reported() + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, + bench.Targets([1], []), 8, _line_edges(8)) + epoch = bench.results_to_epoch({0: None}, plan, qp, gp, _line_edges(8)) + assert not epoch.measured_qubit_mask.any() + assert epoch.notices + + +def test_empty_result_set_is_never_a_silent_no_op(): + """A runner that returns no analysis results must say so. + + The dangerous failure mode is not a crash, it is a benchmark that appears + to succeed, changes nothing, and lets the user believe the numbers are + fresh. Empty results therefore produce a notice and leave the mask clear. + """ + qp, gp = _reported() + targets = bench.Targets([1, 2], [(1, 2)]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, 8, _line_edges(8)) + + epoch = bench.results_to_epoch({i: [] for i in range(len(plan.specs))}, + plan, qp, gp, _line_edges(8)) + + assert not epoch.measured_qubit_mask.any() + assert not epoch.measured_edge_mask.any() + assert len(epoch.notices) == len(plan.specs), epoch.notices + assert all('no results' in n for n in epoch.notices), epoch.notices + + +def test_t1_t2_are_converted_from_seconds_to_microseconds(): + qp, gp = _reported() + plan = bench.build_plan(bench.LEVEL_FULL, bench.Targets([], []), 8, + _line_edges(8)) + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 't1': + raw[idx] = [_Res(qubits=[0], value=150e-6)] # 150 us in seconds + elif spec.kind == 't2hahn': + raw[idx] = [_Res(qubits=[0], value=90e-6)] + + epoch = bench.results_to_epoch(raw, plan, qp, gp, _line_edges(8)) + assert epoch.qubit_props['t1'][0] == pytest.approx(150.0) + assert epoch.qubit_props['t2'][0] == pytest.approx(90.0) + assert epoch.qubit_props['t1'][1] == pytest.approx(100.0) # untouched + + +def test_readout_error_is_the_symmetrised_assignment_error(): + assert bench._readout_error_from_matrix([[0.9, 0.1], [0.2, 0.8]]) == \ + pytest.approx(0.15) + + +# ── 5. persistence + TTL ──────────────────────────────────────────── + +def _epoch(when, level=2): + qp, gp = _reported() + mask_q = np.zeros(8, dtype=bool); mask_q[1] = True + mask_e = np.zeros(7, dtype=bool); mask_e[1] = True + return bench.MeasuredEpoch(qp, gp, mask_q, mask_e, level, when, + ['q1: example notice']) + + +def test_save_list_load_roundtrip(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + import time as _time + when = _time.time() + epoch = _epoch(when) + + assert bench.save_measured_epoch('ibm_test', epoch) is not None + assert bench.list_measured_epochs('ibm_test') + + back = bench.load_measured_epoch('ibm_test', when) + assert back is not None + assert back.level == epoch.level + assert back.notices == epoch.notices + np.testing.assert_allclose(back.qubit_props['readout_error'], + epoch.qubit_props['readout_error']) + np.testing.assert_array_equal(back.measured_qubit_mask, + epoch.measured_qubit_mask) + + +def test_load_missing_epoch_returns_none(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + assert bench.load_measured_epoch('ibm_test', 1.0) is None + + +def test_ttl_reuse_window(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + import time as _time + now = _time.time() + + fresh = _epoch(now - 10 * 60) # 10 minutes old + assert fresh.younger_than(60, now) is True + assert fresh.age_minutes(now) == pytest.approx(10, abs=0.1) + + stale = _epoch(now - 120 * 60) # 2 hours old + assert stale.younger_than(60, now) is False + + bench.save_measured_epoch('ibm_test', stale) + assert bench.latest_reusable_epoch('ibm_test', 60, now) is None + bench.save_measured_epoch('ibm_test', fresh) + got = bench.latest_reusable_epoch('ibm_test', 60, now) + assert got is not None and got.level == fresh.level + + +# ── 6. apply_measured_epoch ───────────────────────────────────────── + +def test_apply_sets_arrays_label_and_resets_delta(): + state = _state(8) + epoch = _epoch(1_700_000_000.0, level=2) + assert bench.apply_measured_epoch(state, epoch) is True + + assert state.qubit_props_data is epoch.qubit_props + assert state.gate_props_data is epoch.gate_props + assert state.delta_mode is False + assert 'measured' in state.calibration_data_label + assert 'L2' in state.calibration_data_label + assert getattr(state, '_measured_epoch') is epoch + + +def test_apply_rejects_a_shape_mismatch(): + state = _state(4) # 4 qubits, epoch has 8 + assert bench.apply_measured_epoch(state, _epoch(1.0)) is False + assert state.delta_mode is True, 'a rejected epoch must change nothing' + + +def test_measured_badge_only_marks_measured_elements(): + state = _state(8) + assert bench.measured_badge(state, qubit=1) == '' # nothing applied yet + bench.apply_measured_epoch(state, _epoch(1.0)) + assert bench.measured_badge(state, qubit=1) == ' (measured)' + assert bench.measured_badge(state, qubit=0) == '' + assert bench.measured_badge(state, edge=1) == ' (measured)' + assert bench.measured_badge(state, edge=0) == '' + + +# ── 7. plan gating ────────────────────────────────────────────────── + +@pytest.mark.parametrize('plan_name,level,allowed,warns', [ + ('premium', 1, True, False), + ('premium', 2, True, False), + ('premium', 3, True, False), + ('dedicated', 3, True, False), + ('open', 1, True, False), + ('open', 2, True, True), + ('open', 3, False, True), + (None, 1, True, False), + (None, 2, True, True), + (None, 3, False, True), + ('', 3, False, True), +]) +def test_plan_gate_matrix(plan_name, level, allowed, warns): + gate = bench.plan_gate(plan_name, level) + assert gate.allowed is allowed + assert (gate.warning is not None) is warns + + +def test_level3_always_needs_acknowledgement_even_on_premium(): + assert bench.requires_acknowledgement('premium', 3) is True + assert bench.requires_acknowledgement('premium', 2) is False + assert bench.requires_acknowledgement('open', 2) is True + assert bench.requires_acknowledgement(None, 1) is False + + +# ── run_plan / install hint ───────────────────────────────────────── + +def test_run_plan_delegates_to_the_injected_runner(): + plan = bench.build_plan(1, bench.Targets([0], []), 8, _line_edges(8)) + seen = {} + bench.run_plan(plan, lambda p: seen.setdefault('plan', p) or {'ok': 1}) + assert seen['plan'] is plan + + +def test_run_plan_skips_the_runner_for_an_empty_plan(): + plan = bench.build_plan(1, bench.Targets([], []), 8, _line_edges(8)) + + def _boom(_p): # pragma: no cover + raise AssertionError('runner must not be called for an empty plan') + + assert bench.run_plan(plan, _boom) == {} + + +def test_make_runtime_runner_raises_the_documented_install_hint(): + """With no qiskit-experiments installed the hint names the extra. + + Call-shape contracts live in tests/test_benchmark_runtime_contract.py. + """ + with pytest.raises(ImportError, match=r'i-qmapper\[benchmark\]'): + bench.make_runtime_runner(object()) + + +# ── v2: target-selection modes ────────────────────────────────────── + +def test_current_layouts_mode_unions_every_circuit_slot(): + """Hand-placed or auto-placed, C1..Cn all count — and no duplicate edges.""" + state = _state(8, layouts={ + 0: {'alpha': ['0', '1'], 'beta': ['2'], 'ancilla': [], 'other': []}, + 1: {'alpha': ['4', '5'], 'beta': ['6'], 'ancilla': ['3'], 'other': []}, + }) + targets = bench.select_targets(state, None, mode=bench.TARGET_CURRENT) + + assert targets.qubits == [0, 1, 2, 3, 4, 5, 6] + assert len(targets.edges) == len(set(targets.edges)), 'duplicate edges' + assert targets.edges == [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] + assert all(7 not in e for e in targets.edges) + + +def test_whole_qpu_mode_takes_every_qubit_and_edge(): + state = _state(8) + targets = bench.select_targets(state, None, mode=bench.TARGET_WHOLE) + assert targets.qubits == list(range(8)) + assert targets.edges == _line_edges(8) + + +def test_custom_mode_filters_edges_to_both_endpoints_in_the_set(): + state = _state(8) + targets = bench.select_targets(state, None, mode=bench.TARGET_CUSTOM, + custom='0, 1, 2, 5') + assert targets.qubits == [0, 1, 2, 5] + # (2,3) and (4,5) each have one endpoint outside the set. + assert targets.edges == [(0, 1), (1, 2)] + + +def test_custom_mode_ignores_junk_and_out_of_range_qubits(): + state = _state(8) + targets = bench.select_targets(state, None, mode=bench.TARGET_CUSTOM, + custom='[0, 1] q3, 99, -4, , 2') + assert targets.qubits == [0, 1, 2], 'junk and out-of-range must drop' + + +def test_sweep_mode_is_unchanged(): + state = _state(8) + entries = [_entry([0, 1], [2], [3]), _entry([4, 5], [6], [])] + by_mode = bench.select_targets(state, entries, top_k=2, + mode=bench.TARGET_SWEEP) + legacy = bench.select_targets(state, entries, top_k=2) + assert by_mode == legacy + + +def test_sweep_mode_is_offered_only_once_a_sweep_has_run(): + state = _state(8, layouts={0: {'alpha': ['1'], 'beta': [], 'ancilla': [], + 'other': []}}) + assert bench.TARGET_SWEEP not in bench.available_target_modes(state, []) + assert bench.TARGET_SWEEP in bench.available_target_modes( + state, [_entry([0, 1], [2], [3])]) + # Order is the one the spec lists. + assert bench.available_target_modes(state, [_entry([0], [1], [])]) == [ + bench.TARGET_CURRENT, bench.TARGET_SWEEP, bench.TARGET_WHOLE, + bench.TARGET_CUSTOM] + + +def test_default_mode_prefers_a_placed_layout(): + placed = _state(8, layouts={0: {'alpha': ['1'], 'beta': [], 'ancilla': [], + 'other': []}}) + assert bench.default_target_mode(placed, None) == bench.TARGET_CURRENT + empty = _state(8) + assert bench.default_target_mode(empty, [_entry([0], [1], [])]) == \ + bench.TARGET_SWEEP + + +# ── v2: Level 1 does not scale with qubit count ───────────────────── + +def test_level1_cost_is_flat_in_qubit_count(): + """LocalReadoutError is two circuits whatever the width. + + This is what makes `Whole QPU x L1` the cheap "refresh the readout + heatmap" action rather than a full-chip expense. + """ + coupling = _line_edges(127) + ten = bench.estimate_cost(bench.build_plan( + 1, bench.Targets(list(range(10)), []), 127, coupling)) + whole = bench.estimate_cost(bench.build_plan( + 1, bench.Targets(list(range(127)), []), 127, coupling)) + + assert whole.qpu_seconds == pytest.approx(ten.qpu_seconds) + assert whole.circuits == ten.circuits == 2 + + +def test_level2_cost_scales_with_edge_count(): + coupling = _line_edges(127) + few = bench.estimate_cost(bench.build_plan( + 2, bench.Targets(list(range(5)), coupling[:4]), 127, coupling)) + many = bench.estimate_cost(bench.build_plan( + 2, bench.Targets(list(range(40)), coupling[:39]), 127, coupling)) + assert many.qpu_seconds > few.qpu_seconds + assert many.circuits > few.circuits diff --git a/tests/test_benchmark_runtime_contract.py b/tests/test_benchmark_runtime_contract.py new file mode 100644 index 0000000..ed92575 --- /dev/null +++ b/tests/test_benchmark_runtime_contract.py @@ -0,0 +1,291 @@ +"""Contract tests for the production benchmark runner. + +These exist because of a specific failure. The first live benchmark run died +on `Session.__init__() got an unexpected keyword argument 'service'`: +qiskit-ibm-runtime 0.48 dropped the `service=` kwarg, and nothing offline +exercised the production runner, so the drift reached a real device before it +reached a test. + +Everything here monkeypatches `benchmark._runtime_api` with fakes that record +how they were constructed and called. No quantum stack is imported, no network +is touched — but the exact call shapes the runner depends on are pinned, so +the next signature change fails here instead of on a QPU. +""" +from types import SimpleNamespace + +import pytest + +from iqmapper import benchmark as bench + + +# ── fakes ─────────────────────────────────────────────────────────── + +class _FakeSession: + """Records its constructor kwargs and its context-manager lifecycle.""" + + instances = [] + + def __init__(self, **kwargs): + self.kwargs = dict(kwargs) + self.entered = False + self.exited = False + self.exit_exc = None + _FakeSession.instances.append(self) + + def __enter__(self): + self.entered = True + return self + + def __exit__(self, exc_type, exc, tb): + self.exited = True + self.exit_exc = exc_type + return False # never swallow + + +class _FakeSampler: + instances = [] + + def __init__(self, **kwargs): + self.kwargs = dict(kwargs) + _FakeSampler.instances.append(self) + + +class _FakeData: + def __init__(self, n_children, results=None): + self._n = n_children + self._results = results + self.blocked = False + + def block_for_results(self): + self.blocked = True + + def child_data(self, idx): + if idx >= self._n: + raise IndexError(idx) + return SimpleNamespace( + analysis_results=lambda: (self._results or [f'result-{idx}'])) + + +class _FakeBatch: + instances = [] + + def __init__(self, experiments, **kwargs): + self.experiments = list(experiments) + self.kwargs = dict(kwargs) + self.run_calls = [] + self.raise_on_run = None + _FakeBatch.instances.append(self) + + def run(self, **kwargs): + self.run_calls.append(dict(kwargs)) + if self.raise_on_run is not None: + raise self.raise_on_run + return _FakeData(len(self.experiments)) + + +class _FakeExperiment: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + +def _fake_api(): + return SimpleNamespace( + Session=_FakeSession, SamplerV2=_FakeSampler, + BatchExperiment=_FakeBatch, ParallelExperiment=_FakeExperiment, + LocalReadoutError=_FakeExperiment, StandardRB=_FakeExperiment, + T1=_FakeExperiment, T2Hahn=_FakeExperiment) + + +@pytest.fixture(autouse=True) +def _clean_runtime_cache(): + """`preload_runtime` caches the resolved stack process-wide, so a fake + left behind by one test would be handed to the next. Clear it either + side.""" + bench._reset_runtime_cache() + yield + bench._reset_runtime_cache() + + +@pytest.fixture +def api(monkeypatch): + for cls in (_FakeSession, _FakeSampler, _FakeBatch): + cls.instances = [] + monkeypatch.setattr(bench, '_runtime_api', _fake_api) + return _fake_api() + + +def _plan(level=bench.LEVEL_TARGETED): + targets = bench.Targets([0, 1, 2], [(0, 1), (1, 2)]) + return bench.build_plan(level, targets, 8, [(i, i + 1) for i in range(7)]) + + +# ── the call shapes ───────────────────────────────────────────────── + +def test_session_is_constructed_with_backend_only(api): + """`Session(backend=...)` and nothing else. + + qiskit-ibm-runtime 0.48 removed `service=`; the backend carries its own + service. Any extra kwarg here is the bug that broke the first live run. + """ + backend = object() + runner = bench.make_runtime_runner(backend) + runner(_plan()) + + assert len(_FakeSession.instances) == 1 + session = _FakeSession.instances[0] + assert session.kwargs == {'backend': backend}, ( + f'Session must take backend= only, got {session.kwargs}') + assert 'service' not in session.kwargs + + +def test_sampler_is_constructed_with_mode_session(api): + runner = bench.make_runtime_runner(object()) + runner(_plan()) + + assert len(_FakeSampler.instances) == 1 + sampler = _FakeSampler.instances[0] + assert set(sampler.kwargs) == {'mode'}, sampler.kwargs + assert sampler.kwargs['mode'] is _FakeSession.instances[0] + + +def test_batch_is_run_with_sampler_and_shots(api): + plan = _plan() + runner = bench.make_runtime_runner(object()) + runner(plan) + + batch = _FakeBatch.instances[0] + assert len(batch.run_calls) == 1 + call = batch.run_calls[0] + assert call['sampler'] is _FakeSampler.instances[0] + assert call['shots'] == 1000 == plan.shots + assert 'backend' not in call, ( + 'the sampler carries the backend now; passing it again is the old API') + + +def test_results_are_collected_per_experiment(api): + plan = _plan() + runner = bench.make_runtime_runner(object()) + out = runner(plan) + + assert set(out) == set(range(len(plan.specs))) + assert out[0] == ['result-0'] + + +def test_session_closes_even_when_the_run_raises(api): + """A leaked session keeps holding a reservation — `with` must cover it.""" + runner = bench.make_runtime_runner(object()) + + original_init = _FakeBatch.__init__ + + def _exploding_init(self, experiments, **kwargs): + original_init(self, experiments, **kwargs) + self.raise_on_run = RuntimeError('device went away') + + _FakeBatch.__init__ = _exploding_init + try: + with pytest.raises(RuntimeError, match='device went away'): + runner(_plan()) + finally: + _FakeBatch.__init__ = original_init + + assert len(_FakeSession.instances) == 1 + session = _FakeSession.instances[0] + assert session.entered is True + assert session.exited is True, 'the session leaked on the failure path' + assert session.exit_exc is RuntimeError + + +def test_experiments_are_built_for_every_spec(api): + plan = _plan(bench.LEVEL_FULL) + runner = bench.make_runtime_runner(object()) + runner(plan) + + batch = _FakeBatch.instances[0] + assert len(batch.experiments) == len(plan.specs) + assert batch.kwargs == {'flatten_results': False} + + +def test_runner_is_not_built_when_the_extra_is_missing(monkeypatch): + def _no_stack(): + raise ImportError(bench._INSTALL_HINT) + + monkeypatch.setattr(bench, '_runtime_api', _no_stack) + with pytest.raises(ImportError, match=r'i-qmapper\[benchmark\]'): + bench.make_runtime_runner(object()) + + +# ── plan gating, including the live-observed 'on-prem' ────────────── + +@pytest.mark.parametrize('plan_name', [ + 'on-prem', 'On-Prem', 'ON-PREM', 'onprem', 'premium', 'Premium', + 'IBM Dedicated', 'internal', +]) +def test_unmetered_plans_are_unrestricted(plan_name): + """A live run reported `plan: on-prem` and was gated as if it were Open.""" + for level in (1, 2, 3): + gate = bench.plan_gate(plan_name, level) + assert gate.allowed is True, (plan_name, level) + assert gate.warning is None, (plan_name, level) + + +@pytest.mark.parametrize('plan_name', ['open', 'Open Plan', '', None, 'pay-go']) +def test_everything_else_keeps_the_conservative_open_rules(plan_name): + assert bench.plan_gate(plan_name, 1).allowed is True + assert bench.plan_gate(plan_name, 1).warning is None + assert bench.plan_gate(plan_name, 2).warning is not None + assert bench.plan_gate(plan_name, 3).allowed is False + + +def test_level3_still_needs_acknowledgement_on_an_unmetered_plan(): + """Unmetered is not unlimited: ~4 minutes of QPU is worth a confirmation.""" + assert bench.requires_acknowledgement('on-prem', 3) is True + assert bench.requires_acknowledgement('on-prem', 2) is False + + +# ── preload: the import must happen on the MAIN thread ────────────── + +def test_preload_is_idempotent_and_caches(monkeypatch): + """Only the first call resolves; the rest are cache reads.""" + calls = [] + + def _recording_api(): + calls.append(1) + return _fake_api() + + monkeypatch.setattr(bench, '_runtime_api', _recording_api) + + assert bench.runtime_ready() is False + first = bench.preload_runtime() + assert bench.runtime_ready() is True + second = bench.preload_runtime() + assert first is second + assert len(calls) == 1, 'preload_runtime must resolve exactly once' + + +def test_make_runtime_runner_reads_the_cache_not_the_importer(monkeypatch): + """Once preloaded, building a runner must not re-import anything.""" + calls = [] + + def _recording_api(): + calls.append(1) + return _fake_api() + + monkeypatch.setattr(bench, '_runtime_api', _recording_api) + bench.preload_runtime() + assert len(calls) == 1 + + bench.make_runtime_runner(object()) + assert len(calls) == 1, 'the runner re-resolved an already-loaded stack' + + +def test_a_failed_preload_is_not_cached(monkeypatch): + """A missing extra must stay reportable, not poison the cache.""" + def _boom(): + raise ImportError(bench._INSTALL_HINT) + + monkeypatch.setattr(bench, '_runtime_api', _boom) + for _ in range(2): + with pytest.raises(ImportError, match=r'i-qmapper\[benchmark\]'): + bench.preload_runtime() + assert bench.runtime_ready() is False diff --git a/tests/test_benchmark_ui.py b/tests/test_benchmark_ui.py new file mode 100644 index 0000000..3fd97c6 --- /dev/null +++ b/tests/test_benchmark_ui.py @@ -0,0 +1,694 @@ +"""UI tests for the 📡 Benchmark section. + +Everything runs against a FAKE runner injected through the panel ctx, so no +test ever imports qiskit_experiments or reaches a network. The last test is +the important one: it pins the rule that the multi-QPU scan never benchmarks. +""" +from types import SimpleNamespace + +import numpy as np + +from iqmapper import benchmark as bench + + +# ── harness ───────────────────────────────────────────────────────── + +class _RecLabel: + def __init__(self): + self.history = [] + + @property + def value(self): + return self.history[-1] if self.history else '' + + @value.setter + def value(self, v): + self.history.append(v) + + +class _Stub: + def __init__(self, **attrs): + self.__dict__.update(attrs) + self._observers = [] + self.layout = SimpleNamespace(display='') + + def observe(self, fn, names=None): + self._observers.append(fn) + + def on_click(self, fn): + self._click = fn + + def click(self): + self._click(self) + + +class _Dropdown(_Stub): + """A stub whose .value assignment fires observers, as ipywidgets does.""" + + def __init__(self, value=None, **attrs): + super().__init__(**attrs) + self.__dict__['value'] = value + + def __setattr__(self, name, val): + fire = (name == 'value' and self.__dict__.get('value') != val + and self.__dict__.get('_observers') is not None) + object.__setattr__(self, name, val) + if fire: + for fn in list(self._observers): + fn({'new': val}) + + +def _line_edges(n): + return [(i, i + 1) for i in range(n - 1)] + + +def _state(n_q=8): + return SimpleNamespace( + qubit_ids=[str(i) for i in range(n_q)], + edges_list=_line_edges(n_q), + layouts_data={}, + active_backend='backend-obj', active_backend_name='ibm_test', + active_service=None, + qubit_props_data={'readout_error': np.full(n_q, 0.05)}, + gate_props_data={'cz_error': np.full(n_q - 1, 0.01)}, + calibration_data_label='ibm_test — reported', delta_mode=False) + + +def _entry(alpha, beta, ancillas, lqs=0.5): + return {'alpha': list(alpha), 'beta': list(beta), + 'ancillas': list(ancillas), 'lqs_circuit': lqs, + 'rank_in_stratum': 1} + + +def _ctx(*, state=None, candidates=None, runner=None, spawn=None, + rescore=None, qpu2=None, inter_on=False, target=None): + state = state or _state() + return SimpleNamespace( + state=state, + dd_bench_target=_Dropdown( + value=target or bench.TARGET_CURRENT, + options=[(bench.TARGET_LABELS[m], m) + for m in (bench.TARGET_CURRENT, bench.TARGET_WHOLE, + bench.TARGET_CUSTOM)]), + txt_bench_custom=_Dropdown(value=''), + tb_bench_qpu=_Dropdown(value=1), + dd_bench_level=_Dropdown(value=bench.LEVEL_QUICK_READOUT), + lbl_bench_summary=_RecLabel(), + chk_bench_ack=_Dropdown(value=False), + btn_bench_run=_Stub(disabled=True), + lbl_bench_status=_RecLabel(), + lbl_bench_reuse=_RecLabel(), + btn_bench_reuse=_Stub(disabled=True), + lbl_lucj_notices=_RecLabel(), + lucj_all_layouts=list(candidates or []), + rescore_cell=[rescore], + refresh=lambda: None, + chk_inter_qpu=_Dropdown(value=inter_on), + qpu2_handles_cell=[(lambda: qpu2)] if qpu2 is not None else [None], + bench_spawn_bg=spawn, + bench_runner_factory=(lambda _s: runner) if runner else None, + ) + + +def _fake_runner(plan): + """Plausible results for whatever the plan asked for.""" + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + out[idx] = [SimpleNamespace( + qubits=[q], value=SimpleNamespace( + assignment_matrix=np.array([[0.99, 0.01], [0.01, 0.99]]))) + for q in spec.qubits] + elif spec.kind == 'rb2q': + out[idx] = [SimpleNamespace(name='EPG', value=0.002)] + else: + out[idx] = [] + return out + + +def _have_qe(monkeypatch, present=True): + """The panel disables itself without the extra; pretend it is installed.""" + monkeypatch.setattr(bench, 'have_qiskit_experiments', lambda: present) + + +def _setup(ctx): + from iqmapper.ui.benchmark_panel import setup_benchmark_panel + return setup_benchmark_panel(ctx) + + +# ── 8a. gating on targets and acknowledgement ─────────────────────── + +def test_button_disabled_without_targets(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(candidates=[]) + _setup(ctx) + assert ctx.btn_bench_run.disabled is True + assert 'Targets: 0 qubits' in ctx.lbl_bench_summary.value + + +def test_summary_shows_cost_before_the_click(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], target=bench.TARGET_SWEEP) + _setup(ctx) + summary = ctx.lbl_bench_summary.value + assert 'Targets: 4 qubits' in summary and '3 edges' in summary + assert 'QPU (estimate)' in summary + assert ctx.btn_bench_run.disabled is False, 'L1 on Open needs no ack' + + +def test_open_plan_requires_acknowledgement_for_l2_and_l3(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], target=bench.TARGET_SWEEP) + _setup(ctx) # plan detection -> None = Open + + ctx.dd_bench_level.value = bench.LEVEL_TARGETED + assert ctx.btn_bench_run.disabled is True, 'L2 under Open needs the ack' + assert ctx.chk_bench_ack.layout.display == '' + ctx.chk_bench_ack.value = True + assert ctx.btn_bench_run.disabled is False + + ctx.chk_bench_ack.value = False + ctx.dd_bench_level.value = bench.LEVEL_FULL + assert ctx.btn_bench_run.disabled is True + ctx.chk_bench_ack.value = True + assert ctx.btn_bench_run.disabled is False + + +def test_run_refuses_when_acknowledgement_is_missing(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + called = [] + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=lambda p: called.append(p) or _fake_runner(p)) + api = _setup(ctx) + ctx.dd_bench_level.__dict__['value'] = bench.LEVEL_FULL # no ack ticked + + api['run']() + assert not called, 'the runner must not be reached without the ack' + assert 'understand this uses QPU time' in ctx.lbl_bench_status.value + + +# ── 8b. a successful run ──────────────────────────────────────────── + +def test_successful_run_applies_measured_epoch_and_reranks(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + reranked = [] + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_fake_runner, + rescore=lambda: reranked.append(1) or 4) + api = _setup(ctx) + + api['run']() + + assert 'measured' in state.calibration_data_label + assert 'L1' in state.calibration_data_label + assert getattr(state, '_measured_epoch', None) is not None + # readout was re-measured on the candidate qubits only + epoch = state._measured_epoch + assert list(np.where(epoch.measured_qubit_mask)[0]) == [0, 1, 2, 3] + assert state.qubit_props_data['readout_error'][0] < 0.05 + assert state.qubit_props_data['readout_error'][7] == 0.05 + assert reranked, 'candidates must be re-ranked under the measured epoch' + assert '✅' in ctx.lbl_bench_status.value + assert '4 candidate(s) re-ranked' in ctx.lbl_bench_status.value + # and it was persisted + assert bench.list_measured_epochs('ibm_test') + + +def test_fit_failures_surface_in_the_notices_bar(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + def _bad_runner(plan): + return {i: [] for i, _s in enumerate(plan.specs)} # nothing usable + + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_bad_runner) + api = _setup(ctx) + api['run']() + + assert ctx.lbl_lucj_notices.value, 'fit failures must be visible' + assert '⚠' in ctx.lbl_lucj_notices.value + + +def test_runner_failure_leaves_the_reported_epoch_untouched(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + before_label = state.calibration_data_label + before_readout = state.qubit_props_data['readout_error'].copy() + + def _boom(_plan): + raise RuntimeError('device unavailable') + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_boom) + api = _setup(ctx) + api['run']() + + assert '❌' in ctx.lbl_bench_status.value + assert 'device unavailable' in ctx.lbl_bench_status.value + assert state.calibration_data_label == before_label + np.testing.assert_array_equal(state.qubit_props_data['readout_error'], + before_readout) + assert getattr(state, '_measured_epoch', None) is None + assert ctx.btn_bench_run.disabled is False, 'button must be re-enabled' + + +def test_missing_extra_disables_the_button_with_an_install_hint(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch, present=False) + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], target=bench.TARGET_SWEEP) + _setup(ctx) + assert ctx.btn_bench_run.disabled is True + assert 'i-qmapper[benchmark]' in ctx.lbl_bench_summary.value + + +# ── 8c. reuse ─────────────────────────────────────────────────────── + +def test_reuse_applies_a_saved_epoch_without_running(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + ran = [] + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=lambda p: ran.append(p) or _fake_runner(p)) + api = _setup(ctx) + + api['run']() # produce a saved epoch + assert len(ran) == 1 + state.calibration_data_label = 'ibm_test — reported' # pretend a reset + api['refresh_summary']() + assert 'Reuse (measured' in ctx.lbl_bench_reuse.value + assert ctx.btn_bench_reuse.disabled is False + + api['reuse']() + assert len(ran) == 1, 'reuse must not spend QPU time' + assert 'measured' in state.calibration_data_label + + +# ── 9. the hard rule: scanning never benchmarks ───────────────────── + +def test_scan_never_invokes_the_benchmark_engine(monkeypatch): + """A scan sweeps dozens of backends; an implicit benchmark per backend + would be catastrophic. Nothing on the scan path may touch `benchmark`.""" + import iqmapper.benchmark as bench_mod + + spied = [] + for name in ('run_plan', 'make_runtime_runner', 'apply_measured_epoch', + 'build_plan', 'select_targets'): + original = getattr(bench_mod, name) + + def _spy(*a, _n=name, _o=original, **k): + spied.append(_n) + return _o(*a, **k) + + monkeypatch.setattr(bench_mod, name, _spy) + + # Drive the real scan with its network layer faked out, exactly as + # tests/test_scan_ui.py does. + import numpy as _np + monkeypatch.setattr( + "iqmapper.data.generate_device_data", + lambda s, v, c, d, prefetched_props=None: ( + list(range(8)), [0.0] * 8, _line_edges(8), + [str(i) for i in range(8)], + _np.array([0.01 * (i + 1) for i in range(8)]), + _np.array([0.001 * (i + 1) for i in range(7)]))) + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", + lambda *a, **k: []) + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: None)) + + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + st = SessionState() + for key, val in dict( + active_backend=object(), active_backend_name='ibm_here', + active_chip='c', active_service=None, available_backends=[], + props_warning=None, initial_props=object(), active_ansatz='lucj', + active_vendor='IBM', active_coords=[], custom_colors=[], + cal_history_dates=['_seed_']).items(): + setattr(st, key, val) + builder = MapperUIBuilder(st) + builder.build() + spied.clear() # the panel plans once at build, legitimately + + builder.btn_scan_qpus.click() + + assert spied == [], f'the scan path reached benchmark: {spied}' + + +def test_qpu2_connect_never_invokes_the_benchmark_engine(monkeypatch): + """Connecting a second QPU must not benchmark it either. + + The inter-QPU handoff is one click that builds a whole secondary UI; if + benchmarking rode along with it, every scan pick would silently spend QPU + time on a device the user only wanted to look at. + """ + import iqmapper.benchmark as bench_mod + + spied = [] + for name in ('run_plan', 'make_runtime_runner', 'apply_measured_epoch', + 'results_to_epoch', 'save_measured_epoch'): + original = getattr(bench_mod, name) + + def _spy(*a, _n=name, _o=original, **k): + spied.append(_n) + return _o(*a, **k) + + monkeypatch.setattr(bench_mod, name, _spy) + + def _fake_build(s2, is_secondary=False, return_widgets=False): + s2.qubit_ids = ['0', '1', '2'] + s2.edges_list = [(0, 1), (1, 2)] + fig = SimpleNamespace() + fig_box2 = SimpleNamespace(children=[SimpleNamespace(), + SimpleNamespace(), fig]) + full_ui = SimpleNamespace(children=[SimpleNamespace(), fig_box2]) + w2 = SimpleNamespace(plot_w_slider=SimpleNamespace(value=0), + plot_h_slider=SimpleNamespace(value=0)) + return (full_ui, fig, w2) if return_widgets else (full_ui, fig) + + monkeypatch.setattr("iqmapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("iqmapper.constants.resolve_coords", + lambda b: ([], 'chip_label')) + monkeypatch.setattr("iqmapper.ui.build_mapper_ui", _fake_build) + monkeypatch.setattr("iqmapper.plot.refresh_plot", lambda f, s, w: None) + + from iqmapper.ui.inter_qpu import setup_inter_qpu + state = SimpleNamespace( + available_backends=['ibm_k'], active_backend_name='ibm_here', + active_service=SimpleNamespace( + backend=lambda n: SimpleNamespace(name=n)), + active_ansatz='lucj', current_colorscale='Viridis') + handles_cell = [None] + ctx = SimpleNamespace( + state=state, + chk_inter_qpu=_Stub(value=False), + dd_backend_qpu2=_Stub(disabled=True, options=[], value=None), + btn_connect_qpu2=_Stub(disabled=True), + lbl_qpu2_status=_RecLabel(), + plot_w_slider=_Stub(value=1700), plot_h_slider=_Stub(value=1650), + lbl_fig1=_Stub(layout=SimpleNamespace(display='none')), + ui_sidebar=_Stub(children=[]), ui_sidebar_content=_Stub(children=[]), + sidebar_body=_Stub(children=[]), fig_box=_Stub(children=[]), + qpu2_sidebar_box=_Stub(children=[]), qpu2_fig_box=_Stub(children=[]), + full_ui=_Stub(children=[]), handoff_cell=[None], + qpu2_handles_cell=handles_cell, + spawn_bg=lambda fn, on_done=None, on_error=None: on_done(fn())) + setup_inter_qpu(ctx) + spied.clear() + + ctx.handoff_cell[0]('ibm_k', {'alpha': [0], 'beta': [1], 'ancillas': [2]}) + + assert 'Connected' in ctx.lbl_qpu2_status.value, 'the connect must work' + assert spied == [], f'the QPU-2 connect path reached benchmark: {spied}' + # ...and the accessor is published for the panel to use LATER, on demand. + assert handles_cell[0] is not None + assert handles_cell[0]().backend_name == 'ibm_k' + + +# ── v2: the QPU selector ──────────────────────────────────────────── + +def _qpu2_handles(n_q=6): + """A stand-in for ui.inter_qpu's read-only QPU-2 accessor.""" + state = _state(n_q) + state.active_backend_name = 'ibm_second' + state.calibration_data_label = 'ibm_second — reported' + state.layouts_data = {0: {'alpha': ['0', '1'], 'beta': ['2'], + 'ancilla': [], 'other': []}} + return SimpleNamespace(state=state, fig=None, widgets=None, + backend_name='ibm_second', connected=True) + + +def test_qpu_toggle_hidden_until_inter_qpu_is_on_and_qpu2_connected( + monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + # inter-QPU off, no QPU 2 + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])]) + api = _setup(ctx) + assert ctx.tb_bench_qpu.layout.display == 'none' + assert api['qpu2_available'] is not None and not api['qpu2_available']() + + # inter-QPU on but QPU 2 not connected + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], inter_on=True) + _setup(ctx) + assert ctx.tb_bench_qpu.layout.display == 'none' + + # both + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], inter_on=True, + qpu2=_qpu2_handles()) + _setup(ctx) + assert ctx.tb_bench_qpu.layout.display == '' + + +def test_qpu2_selection_applies_the_epoch_to_the_secondary_state_only( + monkeypatch, tmp_path): + """The whole point of the selector: nothing may leak into QPU 1.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + primary = _state() + primary_label = primary.calibration_data_label + primary_readout = primary.qubit_props_data['readout_error'].copy() + handles = _qpu2_handles() + + reranked = [] + ctx = _ctx(state=primary, candidates=[_entry([0, 1], [2], [3])], + inter_on=True, qpu2=handles, runner=_fake_runner, + rescore=lambda: reranked.append(1) or 4) + api = _setup(ctx) + + ctx.tb_bench_qpu.value = 2 # act on QPU 2 + assert api['active_target']()[0] is handles.state + api['run']() + + # QPU 2 got the epoch... + assert 'measured' in handles.state.calibration_data_label + assert getattr(handles.state, '_measured_epoch', None) is not None + # ...and QPU 1 is untouched, label and arrays both. + assert primary.calibration_data_label == primary_label + assert getattr(primary, '_measured_epoch', None) is None + np.testing.assert_array_equal( + primary.qubit_props_data['readout_error'], primary_readout) + # The Auto candidate list belongs to QPU 1 — not re-ranked on a QPU-2 run. + assert not reranked, 'QPU-2 epoch must not re-rank QPU-1 candidates' + # Saved under QPU 2's own backend name. + assert bench.list_measured_epochs('ibm_second') + assert not bench.list_measured_epochs('ibm_test') + + +def test_qpu2_targets_come_from_the_secondary_layout(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + handles = _qpu2_handles() + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], inter_on=True, + qpu2=handles) + api = _setup(ctx) + + ctx.tb_bench_qpu.value = 2 + ctx.dd_bench_target.value = bench.TARGET_CURRENT + targets, _plan = api['current_plan']() + assert targets.qubits == [0, 1, 2], 'must read QPU 2 layouts_data' + + +# ── v2: whole-QPU messaging ───────────────────────────────────────── + +def test_whole_qpu_level1_is_advertised_as_the_cheap_refresh(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(target=bench.TARGET_WHOLE) + _setup(ctx) + assert 'cheap heatmap refresh' in ctx.lbl_bench_summary.value + assert ctx.btn_bench_run.disabled is False + + +def test_whole_qpu_level3_always_demands_the_acknowledgement(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(target=bench.TARGET_WHOLE) + _setup(ctx) + ctx.dd_bench_level.value = bench.LEVEL_FULL + assert '4 min of QPU' in ctx.lbl_bench_summary.value + assert ctx.btn_bench_run.disabled is True + ctx.chk_bench_ack.value = True + assert ctx.btn_bench_run.disabled is False + + +# ── v2.1: the quantum stack is imported on the MAIN thread ────────── + +def test_runtime_is_preloaded_on_the_main_thread_before_the_worker( + monkeypatch, tmp_path): + """The import must not happen on the worker. + + Live regression: `make_runtime_runner` resolved qiskit_experiments — and + transitively pandas — inside the background worker. Python publishes a + module into sys.modules before executing it, so plotly's click handler, + which probes sys.modules['pandas'] on the main thread, found a half-built + module and raised "partially initialized module 'pandas'". Clicking the + map during a benchmark was enough. + """ + import threading + + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + bench._reset_runtime_cache() + + main_thread = threading.current_thread() + resolved_on = [] + order = [] + + def _recording_api(): + resolved_on.append(threading.current_thread()) + order.append('import') + return _runtime_fakes() + + monkeypatch.setattr(bench, '_runtime_api', _recording_api) + + worker_thread = [] + + def _threaded_spawn(fn, on_done=None, on_error=None): + """A REAL background thread, as default_spawn_bg uses.""" + result = {} + + def _work(): + worker_thread.append(threading.current_thread()) + order.append('worker') + try: + result['value'] = fn() + except Exception as exc: # pragma: no cover + result['error'] = exc + + t = threading.Thread(target=_work) + t.start() + t.join() + if 'error' in result: + if on_error: + on_error(result['error']) + elif on_done: + on_done(result['value']) + + # runner_factory=None -> the PRODUCTION path, which is the one that broke. + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, spawn=_threaded_spawn) + api = _setup(ctx) + try: + api['run']() + + assert resolved_on, 'the runtime was never resolved' + assert len(resolved_on) == 1, 'resolved more than once' + assert resolved_on[0] is main_thread, ( + f'the quantum stack was imported on {resolved_on[0].name}, not ' + f'the main thread — this is the pandas race') + assert worker_thread and worker_thread[0] is not main_thread, ( + 'the test did not actually use a background thread') + assert order == ['import', 'worker'], ( + f'the import must complete before the worker starts, got {order}') + assert bench.runtime_ready() is True + finally: + bench._reset_runtime_cache() + + +def test_second_run_skips_the_loading_message(monkeypatch, tmp_path): + """Preload is idempotent, so only the first run shows the banner.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + bench._reset_runtime_cache() + monkeypatch.setattr(bench, '_runtime_api', _runtime_fakes) + + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP) + api = _setup(ctx) + try: + api['run']() + first = ' '.join(ctx.lbl_bench_status.history) + assert 'Loading benchmark libraries' in first + + mark = len(ctx.lbl_bench_status.history) + api['run']() + second = ' '.join(ctx.lbl_bench_status.history[mark:]) + assert 'Loading benchmark libraries' not in second, ( + 'the loading banner must only appear on the first use') + finally: + bench._reset_runtime_cache() + + +def test_missing_extra_at_run_time_is_reported_not_raised(monkeypatch, + tmp_path): + """A preload failure must surface as a status, and re-enable the button.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + bench._reset_runtime_cache() + + def _boom(): + raise ImportError(bench._INSTALL_HINT) + + monkeypatch.setattr(bench, '_runtime_api', _boom) + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP) + api = _setup(ctx) + try: + api['run']() + assert '❌' in ctx.lbl_bench_status.value + assert 'i-qmapper[benchmark]' in ctx.lbl_bench_status.value + assert ctx.btn_bench_run.disabled is False + finally: + bench._reset_runtime_cache() + + +def _runtime_fakes(): + """Minimal stand-ins for the quantum stack, enough to complete a run.""" + class _Session: + def __init__(self, **kw): + self.kw = kw + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + class _Sampler: + def __init__(self, **kw): + self.kw = kw + + class _Exp: + def __init__(self, *a, **k): + pass + + class _Data: + def __init__(self, n): + self._n = n + + def block_for_results(self): + pass + + def child_data(self, idx): + return SimpleNamespace(analysis_results=lambda: []) + + class _Batch: + def __init__(self, experiments, **kw): + self._n = len(experiments) + + def run(self, **kw): + return _Data(self._n) + + return SimpleNamespace( + Session=_Session, SamplerV2=_Sampler, BatchExperiment=_Batch, + ParallelExperiment=_Exp, LocalReadoutError=_Exp, StandardRB=_Exp, + T1=_Exp, T2Hahn=_Exp) From f286f8a4d697aac0635c9265f5b1387227fce7ab Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Fri, 18 Sep 2026 17:59:23 -0400 Subject: [PATCH 32/66] Guided layout search (phase 1): calibration-guided beam search + 1-opt refinement, engine comparison harness, engine selector (default VF2) --- iqmapper/benchmark.py | 148 +++++- iqmapper/evaluation.py | 445 +++++++++++++++++ iqmapper/guided_search.py | 752 +++++++++++++++++++++++++++++ iqmapper/ui/builder.py | 39 +- iqmapper/ui/lucj_panel.py | 58 ++- tests/conftest.py | 4 + tests/test_auto_panel_ui_polish.py | 121 +++++ tests/test_evaluation.py | 197 ++++++++ tests/test_guided_search.py | 448 +++++++++++++++++ 9 files changed, 2193 insertions(+), 19 deletions(-) create mode 100644 iqmapper/evaluation.py create mode 100644 iqmapper/guided_search.py create mode 100644 tests/test_evaluation.py create mode 100644 tests/test_guided_search.py diff --git a/iqmapper/benchmark.py b/iqmapper/benchmark.py index 8d75b9f..9bbc47c 100644 --- a/iqmapper/benchmark.py +++ b/iqmapper/benchmark.py @@ -448,10 +448,26 @@ def build_plan(level, targets, n_qubits, coupling_edges): qiskit objects are constructed here, which is what lets the whole planning and costing path be tested offline with no quantum stack installed. - Level 1 measures readout on the target qubits. Level 2 adds layered 2Q RB - over the target edges. Level 3 ignores the targets and covers the device: - T1, T2 Hahn, readout, 1Q RB over all qubits, 2Q RB over all coupling - edges — the tutorial suite, at the tutorial's parameters. + THE STRUCTURE IS COMPOSITE, and that is the point. Each spec becomes ONE + `ParallelExperiment` covering many qubits or pairs at once, exactly as the + tutorial does: + + readout -> one LocalReadoutError over every target qubit: 2 circuits + whatever the width. + t1 / t2hahn -> one ParallelExperiment of per-qubit T1/T2Hahn: one circuit + per delay, so 6 each, not 6 x n_qubits. + rb1q -> one ParallelExperiment of per-qubit StandardRB: + len(lengths) x num_samples = 30 circuits. + rb2q_layer -> one ParallelExperiment per edge-colouring LAYER, each + layer a set of vertex-disjoint pairs: 30 circuits per + layer, and heavy-hex needs about three layers. + + A full-chip Level 3 on 156 qubits is therefore 6 + 6 + 2 + 30 + 3x30 = + ~134 circuits. The previous version emitted one spec per qubit and per + EDGE, which on that device meant ~43,400 circuits in a single job and was + rejected outright by IBM (error 1520, shot limit). Keeping the specs + composite is what keeps the run submittable; `plan_circuit_count` is the + check on it. """ level = int(level) coupling = [tuple(e) for e in (coupling_edges or [])] @@ -466,7 +482,7 @@ def build_plan(level, targets, n_qubits, coupling_edges): specs = [] - if level == LEVEL_FULL: + if level == LEVEL_FULL and qubits: specs.append(ExperimentSpec('t1', tuple(qubits), {'delays': list(T1T2_DELAYS)}, 0)) specs.append(ExperimentSpec('t2hahn', tuple(qubits), @@ -481,34 +497,134 @@ def build_plan(level, targets, n_qubits, coupling_edges): {'lengths': list(RB_1Q_LENGTHS), 'num_samples': RB_1Q_SAMPLES}, 0)) if level in (LEVEL_TARGETED, LEVEL_FULL) and edges: + # One ParallelExperiment per colour class. Pairs inside a layer are + # vertex-disjoint, so they genuinely run together. for layer_idx, layer in enumerate(_layer_edges(edges)): - for pair in layer: - specs.append(ExperimentSpec( - 'rb2q', tuple(pair), - {'lengths': list(RB_2Q_LENGTHS), - 'num_samples': RB_2Q_SAMPLES}, layer_idx)) + flat = tuple(q for pair in layer for q in pair) + specs.append(ExperimentSpec( + 'rb2q_layer', flat, + {'pairs': [tuple(p) for p in layer], + 'lengths': list(RB_2Q_LENGTHS), + 'num_samples': RB_2Q_SAMPLES}, layer_idx)) return BenchmarkPlan(level, specs, targets, DEFAULT_SHOTS) -# ── Cost estimation ───────────────────────────────────────────────── +# ── Circuit accounting and the per-job shot budget ────────────────── + +#: IBM rejects a job whose total circuit-shots exceed this (error 1520). +_MAX_CIRCUIT_SHOTS_PER_JOB = 10_000_000 + +#: Submit at 80% of the hard limit; the provider counts a little differently +#: than we do and a rejected job costs a whole round trip. +_BUDGET_MARGIN = 0.8 + +#: Effective per-job ceiling. +_JOB_SHOT_BUDGET = int(_MAX_CIRCUIT_SHOTS_PER_JOB * _BUDGET_MARGIN) + +JobChunk = namedtuple('JobChunk', 'specs circuits shots index') + def _spec_circuits(spec): - """Circuit count for one spec, at the tutorial's parameterisation.""" + """Circuits ONE spec contributes, at the tutorial's parameterisation. + + Every branch is flat in the number of qubits or pairs, because every spec + is a ParallelExperiment: widening a spec adds qubits to each circuit, not + circuits to the job. + """ params = spec.params if spec.kind in ('t1', 't2hahn'): return len(params.get('delays') or []) if spec.kind == 'readout': return 2 # |0...0> and |1...1> preparations - if spec.kind == 'rb1q': - return (len(params.get('lengths') or []) - * int(params.get('num_samples') or 0)) - if spec.kind == 'rb2q': + if spec.kind in ('rb1q', 'rb2q_layer', 'rb2q'): return (len(params.get('lengths') or []) * int(params.get('num_samples') or 0)) return 1 +def plan_circuit_count(plan): + """Exact number of circuits the plan submits.""" + return sum(_spec_circuits(spec) for spec in plan.specs) + + +def plan_shots(plan, shots=DEFAULT_SHOTS): + """Total circuit-shots: the quantity IBM's per-job limit applies to.""" + return plan_circuit_count(plan) * int(shots) + + +def _split_spec(spec, shots): + """Break one over-budget spec into several that each fit. + + Only RB specs can be split, by reducing `num_samples` — the samples are + independent random Clifford sequences, so running them across two jobs is + the same experiment, just submitted twice. T1/T2/readout are already tiny + (2-6 circuits) and cannot exceed a budget measured in millions. + """ + circuits = _spec_circuits(spec) + if circuits * shots <= _JOB_SHOT_BUDGET: + return [spec] + samples = int(spec.params.get('num_samples') or 0) + lengths = len(spec.params.get('lengths') or []) + if samples <= 1 or lengths == 0: + return [spec] # indivisible; caller reports it + per_job = max(1, _JOB_SHOT_BUDGET // (lengths * shots)) + out = [] + remaining = samples + while remaining > 0: + take = min(per_job, remaining) + params = dict(spec.params) + params['num_samples'] = take + out.append(spec._replace(params=params)) + remaining -= take + return out + + +def split_for_submission(plan, shots=DEFAULT_SHOTS): + """Group the plan's experiments into jobs that each fit the shot limit. + + Returns a list of `JobChunk`. Every spec ends up in exactly one chunk — + nothing is dropped, which is the property the tests pin, because silently + discarding an experiment would look like a partial measurement rather than + a bug. + """ + shots = int(shots) + expanded = [] + for spec in plan.specs: + expanded.extend(_split_spec(spec, shots)) + + chunks = [] + current, current_circuits = [], 0 + for spec in expanded: + circuits = _spec_circuits(spec) + if current and (current_circuits + circuits) * shots > _JOB_SHOT_BUDGET: + chunks.append(JobChunk(tuple(current), current_circuits, + current_circuits * shots, len(chunks))) + current, current_circuits = [], 0 + current.append(spec) + current_circuits += circuits + if current: + chunks.append(JobChunk(tuple(current), current_circuits, + current_circuits * shots, len(chunks))) + return chunks + + +def plan_is_submittable(plan, shots=DEFAULT_SHOTS): + """(ok, reason). False when some chunk still exceeds the hard limit. + + A plan that cannot be made to fit must disable Run rather than be sent and + rejected: a rejection costs a round trip and, before this version, ended in + a false success. + """ + for chunk in split_for_submission(plan, shots): + if chunk.shots > _MAX_CIRCUIT_SHOTS_PER_JOB: + return False, ( + f'One experiment needs {chunk.shots:,} circuit-shots, over ' + f"IBM's {_MAX_CIRCUIT_SHOTS_PER_JOB:,} per-job limit, and " + f'cannot be split further. Reduce the target set or the level.') + return True, None + + def estimate_cost(plan, shots=DEFAULT_SHOTS): """Wall-clock QPU seconds a plan is expected to consume. diff --git a/iqmapper/evaluation.py b/iqmapper/evaluation.py new file mode 100644 index 0000000..41516f6 --- /dev/null +++ b/iqmapper/evaluation.py @@ -0,0 +1,445 @@ +""" +evaluation.py — offline comparison of the layout-search engines. + +The guided beam search (`guided_search.guided_sweep`) is a heuristic; the VF2 +sweep (`ancilla_sweep.sweep_ancilla_layouts`) is exhaustive up to a 2000-mapping +cap that it routinely hits on large devices. Which one is actually better is an +empirical question, and this module is how it gets answered before anything is +made the default. + +It replays both engines over the calibration snapshots already sitting in the +local cache — no network, no QPU time, no credentials. For each (date, norb, k) +it records the best circuit-level LQS each engine reached, the wall time, how +many distinct chain scaffolds each produced, and whether VF2 truncated. + +Reading the table +----------------- +`delta_lqs` is `guided - vf2` in LQS points. Positive means guided found a +better layout on that snapshot. `vf2_capped` matters: where VF2 truncated, it +was ranking an arbitrary 2% sample, so a guided win there says the guided +sample is better-chosen, not that beam search beats exhaustive search. Where +VF2 did NOT truncate it enumerated everything, so a guided win is a genuine +win and a guided loss is the heuristic's real cost. + +Both engines get the same graph, the same properties and the same +`circuit_score_fn`, so the comparison is like-for-like. + +Where the topology comes from +----------------------------- +The calibration cache stores ONLY the property arrays: `data._save_calibration` +writes `qubit_props` and `gate_props`, and `_load_calibration` returns exactly +that pair. The coupling map is not cached — the gate arrays are positional +against `state.edges_list`, but that list lives on the session, not in the +cache. `data.py` is a frozen engine, so this module cannot start caching it. + +So the coupling has to come from somewhere else, in this order: + + 1. an explicit `coupling=[(u, v), ...]` argument; + 2. a saved session for that backend under `.iqmapper_sessions/`, which does + persist `edges_list` (see `state.to_dict`); + 3. otherwise the run reports a clear error rather than guessing — an + invented topology would produce numbers that look real and mean nothing. + +Save a session once for the backend you want to evaluate and every cached +calibration for it becomes replayable. + +CLI +--- + python -m iqmapper.evaluation ibm_boston --norb 8 12 16 + +prints the table and writes `.scratch/eval__.md`. +""" +import argparse +import json as _json +import logging +import os +import statistics +import sys +import time +from types import SimpleNamespace + +import numpy as np +import rustworkx + +from . import data as _data +from .ancilla_sweep import sweep_ancilla_layouts +from .guided_search import guided_sweep + +_log = logging.getLogger(__name__) + +DEFAULT_NORBS = (8, 12, 16) + + +# ── replaying a cached calibration as a backend/props pair ────────── + +class _CachedProps: + """BackendProperties stand-in reading a cached calibration snapshot. + + The engines only ever call `readout_error(q)` and `gate_error(name, edge)`, + so that is the whole surface. Missing entries return NaN, which both + engines already map to their uncalibrated penalty. + """ + + def __init__(self, qubit_props, gate_props, edges): + self._readout = np.asarray( + qubit_props.get('readout_error', []), dtype=float) + gate = None + for key in ('cz_error', 'rzz_error'): + if key in gate_props: + gate = np.asarray(gate_props[key], dtype=float) + break + self._gate = gate if gate is not None else np.array([], dtype=float) + self._edge_index = {} + for i, (u, v) in enumerate(edges): + self._edge_index[frozenset((int(u), int(v)))] = i + + def readout_error(self, q): + q = int(q) + if 0 <= q < len(self._readout): + return float(self._readout[q]) + return float('nan') + + def gate_error(self, _name, edge): + u, v = edge + idx = self._edge_index.get(frozenset((int(u), int(v)))) + if idx is None or idx >= len(self._gate): + return float('nan') + return float(self._gate[idx]) + + +def _backend_from_edges(edges, n_qubits, name='cached'): + """A BackendV2-shaped stand-in carrying just the coupling graph.""" + graph = rustworkx.PyDiGraph() + for _ in range(n_qubits): + graph.add_node(None) + for u, v in edges: + graph.add_edge(int(u), int(v), None) + graph.add_edge(int(v), int(u), None) + return SimpleNamespace(name=name, + coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +def _product_scorer(): + """A stand-in `circuit_score_fn` usable without the app's state. + + The real UI scorer is state-bound (`export.scoring.estimate_circuit_fidelity` + needs dict-shaped props on a SessionState). For an engine COMPARISON what + matters is that both engines are ranked by the same monotone function of + layout quality, so the product score serves: it is the same quantity the + UI's LQS is a refinement of, and using it keeps the harness runnable + against a bare cache. Reported as `lqs_proxy` rather than `lqs` for that + reason. + """ + def _score(entry): + return float(entry.get('product_score') or 0.0) + return _score + + +# ── report ────────────────────────────────────────────────────────── + +class Row: + """One (date, norb, k) comparison.""" + + __slots__ = ('date', 'norb', 'k', 'vf2_lqs', 'guided_lqs', 'vf2_time', + 'guided_time', 'vf2_scaffolds', 'guided_scaffolds', + 'vf2_capped', 'refined') + + def __init__(self, date, norb, k, vf2_lqs, guided_lqs, vf2_time, + guided_time, vf2_scaffolds, guided_scaffolds, vf2_capped, + refined): + self.date = date + self.norb = norb + self.k = k + self.vf2_lqs = vf2_lqs + self.guided_lqs = guided_lqs + self.vf2_time = vf2_time + self.guided_time = guided_time + self.vf2_scaffolds = vf2_scaffolds + self.guided_scaffolds = guided_scaffolds + self.vf2_capped = vf2_capped + self.refined = refined + + @property + def delta(self): + if self.vf2_lqs is None or self.guided_lqs is None: + return None + return self.guided_lqs - self.vf2_lqs + + @property + def guided_at_least(self): + d = self.delta + return None if d is None else d >= -1e-12 + + +class Report: + """The rows plus the summary a human actually reads.""" + + def __init__(self, backend_name, rows, errors=None): + self.backend_name = backend_name + self.rows = list(rows) + self.errors = list(errors or []) + + # ── aggregates ────────────────────────────────────────────── + def _comparable(self): + return [r for r in self.rows if r.delta is not None] + + def summary(self): + comp = self._comparable() + if not comp: + return 'No comparable cases.' + wins = sum(1 for r in comp if r.guided_at_least) + deltas = [r.delta * 100.0 for r in comp] # LQS points + vf2_t = sum(r.vf2_time for r in comp) + guided_t = sum(r.guided_time for r in comp) + speed = (vf2_t / guided_t) if guided_t > 0 else float('inf') + faster = (f'{speed:.1f}x faster' if speed >= 1 + else f'{1 / speed:.1f}x slower') + return (f'guided >= VF2 in {wins}/{len(comp)} cases; ' + f'mean dLQS {statistics.mean(deltas):+.1f} pt; ' + f'max {max(deltas):+.1f} pt; min {min(deltas):+.1f} pt; ' + f'{faster}') + + def to_markdown(self): + lines = [f'# Engine comparison - {self.backend_name}', '', + self.summary(), ''] + if self.errors: + lines += ['## Errors', ''] + lines += [f'- {e}' for e in self.errors] + lines += [''] + lines += [ + '| date | norb | k | VF2 | guided | dLQS (pt) | VF2 s | guided s |' + ' VF2 scaffolds | guided scaffolds | VF2 capped | refined |', + '|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|:--:|---:|'] + for r in self.rows: + def _f(value, digits=4): + return '-' if value is None else f'{value:.{digits}f}' + delta = ('-' if r.delta is None else f'{r.delta * 100:+.2f}') + lines.append( + f'| {r.date} | {r.norb} | {r.k} | {_f(r.vf2_lqs)} | ' + f'{_f(r.guided_lqs)} | {delta} | {r.vf2_time:.2f} | ' + f'{r.guided_time:.2f} | {r.vf2_scaffolds} | ' + f'{r.guided_scaffolds} | {"yes" if r.vf2_capped else "no"} | ' + f'{r.refined} |') + return '\n'.join(lines) + '\n' + + def __repr__(self): # pragma: no cover - debug aid + return f'' + + +# ── the comparison ────────────────────────────────────────────────── + +def _scaffolds(result): + """Distinct chain scaffolds across all strata.""" + seen = set() + for entries in (result.get('strata') or {}).values(): + for entry in entries: + seen.add(frozenset(entry['layout'])) + return len(seen) + + +def _best_lqs(result, k): + entries = (result.get('strata') or {}).get(k) or [] + if not entries: + return None + values = [e.get('lqs_circuit') for e in entries + if e.get('lqs_circuit') is not None] + if values: + return max(values) + return max(e['product_score'] for e in entries) + + +def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, + min_bridges=0, cache_dir=None, beam_width=200, + circuit_score_fn=None, limit=None, coupling=None, + session_dir=None): + """Run both engines over the cached calibrations and report. + + Read-only and offline: reads the local calibration cache, never the + network. `min_bridges=0` is clamped to 1, the engines' floor. + + Args: + backend_name: the cached backend to replay. + dates: explicit `last_update` strings, or None for everything cached. + norbs: orbital counts to test. + cache_dir: override `data._CACHE_DIR` for the duration (tests). + limit: cap the number of calibrations replayed. + """ + scorer = circuit_score_fn or _product_scorer() + min_bridges = max(1, int(min_bridges)) + + old_cache = None + if cache_dir is not None: + old_cache = _data._CACHE_DIR + _data._CACHE_DIR = str(cache_dir) + try: + entries = _data.list_known_calibrations(backend_name) + stamps = ([e['last_update'] for e in entries] if dates is None + else list(dates)) + if limit is not None: + stamps = stamps[:int(limit)] + + rows, errors = [], [] + # The cache has no topology; resolve it once for the whole run. + if coupling is None: + coupling = coupling_from_sessions(backend_name, session_dir) + if coupling is None: + errors.append( + f'No coupling map for {backend_name}: the calibration cache ' + f'stores only property arrays. Pass coupling=[(u, v), ...] or ' + f'save a session for this backend so .iqmapper_sessions/ ' + f'carries its edges_list.') + return Report(backend_name, [], errors) + + for stamp in stamps: + snapshot = _data._load_calibration(backend_name, stamp) + if not snapshot: + errors.append(f'{stamp}: no cached calibration') + continue + qubit_props, gate_props, edges = _unpack(snapshot) + if edges is None: + edges = coupling + n_qubits = len(qubit_props.get('readout_error', [])) + if n_qubits == 0: + errors.append(f'{stamp}: no readout_error array; skipped') + continue + backend = _backend_from_edges(edges, n_qubits, backend_name) + props = _CachedProps(qubit_props, gate_props, edges) + + for norb in norbs: + rows.extend(_compare_one(stamp, norb, backend, props, + top_n, min_bridges, beam_width, + scorer, errors)) + return Report(backend_name, rows, errors) + finally: + if old_cache is not None: + _data._CACHE_DIR = old_cache + + +def _unpack(snapshot): + """Cached snapshots have varied in shape; accept what we find. + + `data._load_calibration` returns a 2-tuple `(qubit_props, gate_props)` and + carries no topology, so `edges` is normally None and the caller supplies + the coupling — see the module docstring. + """ + if isinstance(snapshot, tuple): + qubit_props, gate_props = snapshot[0], snapshot[1] + edges = snapshot[2] if len(snapshot) > 2 else None + else: + qubit_props = snapshot.get('qubit_props', {}) + gate_props = snapshot.get('gate_props', {}) + edges = snapshot.get('edges') + if edges is not None: + edges = [tuple(int(x) for x in e) for e in edges] + return dict(qubit_props or {}), dict(gate_props or {}), edges + + +def coupling_from_sessions(backend_name, session_dir=None): + """Recover a coupling map for `backend_name` from a saved session. + + Sessions persist `edges_list` (and `qubit_ids`) via `state.to_dict`, so one + saved session makes every cached calibration for that backend replayable. + Returns a list of (u, v), or None when nothing matches. + """ + directory = session_dir or os.path.join(os.getcwd(), '.iqmapper_sessions') + try: + names = sorted(os.listdir(directory)) + except OSError: + return None + for name in names: + if not name.endswith('.json'): + continue + try: + with open(os.path.join(directory, name), 'r', + encoding='utf-8') as fh: + payload = _json.load(fh) + except Exception: + continue + if str(payload.get('active_backend_name') or '') != str(backend_name): + continue + edges = payload.get('edges_list') or [] + if edges: + return [tuple(int(x) for x in e) for e in edges] + return None + + +def _compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, + scorer, errors): + """One (date, norb): run both engines, emit a row per shared stratum.""" + try: + t0 = time.time() + vf2 = sweep_ancilla_layouts(norb, backend, props, + min_bridges=min_bridges, top_n=top_n, + circuit_score_fn=scorer) + vf2_time = time.time() - t0 + except Exception as exc: # noqa: BLE001 - recorded + errors.append(f'{stamp} norb={norb}: VF2 failed ({exc})') + return [] + try: + t0 = time.time() + guided = guided_sweep(norb, backend, props, min_bridges=min_bridges, + top_n=top_n, circuit_score_fn=scorer, + beam_width=beam_width) + guided_time = time.time() - t0 + except Exception as exc: # noqa: BLE001 - recorded + errors.append(f'{stamp} norb={norb}: guided failed ({exc})') + return [] + + vf2_scaffolds = _scaffolds(vf2) + guided_scaffolds = _scaffolds(guided) + capped = bool(vf2.get('vf2_truncated')) + refined = int(guided.get('refined_count') or 0) + + rows = [] + for k in sorted(set(vf2.get('strata', {})) | set(guided.get('strata', {})), + reverse=True): + rows.append(Row(stamp, norb, k, _best_lqs(vf2, k), + _best_lqs(guided, k), vf2_time, guided_time, + vf2_scaffolds, guided_scaffolds, capped, refined)) + return rows + + +# ── CLI ───────────────────────────────────────────────────────────── + +def main(argv=None): + parser = argparse.ArgumentParser( + prog='python -m iqmapper.evaluation', + description='Compare the VF2 and guided layout-search engines over ' + 'the locally cached calibrations. Offline and read-only.') + parser.add_argument('backend', help='cached backend name, e.g. ibm_boston') + parser.add_argument('--norb', type=int, nargs='+', default=list(DEFAULT_NORBS)) + parser.add_argument('--top-n', type=int, default=3) + parser.add_argument('--min-bridges', type=int, default=1) + parser.add_argument('--beam-width', type=int, default=200) + parser.add_argument('--limit', type=int, default=None, + help='replay at most N cached calibrations') + parser.add_argument('--out-dir', default='.scratch') + parser.add_argument('--session-dir', default=None, + help='where to look for a saved session carrying the ' + 'coupling map (default .iqmapper_sessions)') + args = parser.parse_args(argv) + + logging.basicConfig(level=logging.WARNING) + report = compare_engines(args.backend, norbs=tuple(args.norb), + top_n=args.top_n, min_bridges=args.min_bridges, + beam_width=args.beam_width, limit=args.limit, + session_dir=args.session_dir) + markdown = report.to_markdown() + print(markdown) + + try: + os.makedirs(args.out_dir, exist_ok=True) + stamp = time.strftime('%Y%m%dT%H%M%S') + path = os.path.join(args.out_dir, + f'eval_{args.backend}_{stamp}.md') + with open(path, 'w', encoding='utf-8') as fh: + fh.write(markdown) + print(f'written: {path}') + except Exception as exc: # noqa: BLE001 - informational + print(f'could not write report: {exc}', file=sys.stderr) + return 0 + + +if __name__ == '__main__': # pragma: no cover - CLI + raise SystemExit(main()) diff --git a/iqmapper/guided_search.py b/iqmapper/guided_search.py new file mode 100644 index 0000000..12488bc --- /dev/null +++ b/iqmapper/guided_search.py @@ -0,0 +1,752 @@ +""" +guided_search.py — calibration-guided beam search for LUCJ layouts. + +The existing engine (`ancilla_sweep.sweep_ancilla_layouts`) enumerates zigzag +embeddings with VF2, which is blind to calibration: it finds subgraphs that fit +the template and only then asks how good they are. On a 193-qubit heavy-hex at +low bridge counts that enumeration runs to 37k-100k+ mappings and gets cut off +at the 2000 cap, so the ranking sees an arbitrary 2% sample of the search +space. Quality survives because the downstream cascade, monotonicity anchors +and diversity quota are good — but generation is throwing away information it +already has. + +This module grows layouts WITH the calibration in hand: at every step it +extends the chains onto the best available neighbours and keeps the best +`beam_width` partial states. It then polishes the finalists with a 1-opt local +search against the real objective (circuit-level LQS). + +It is an alternative engine, not a replacement. `ancilla_sweep` stays the +default until `evaluation.compare_engines` says otherwise on real cached +calibration. + + +THE TEMPLATE (derived from auto_lucj.create_lucj_zigzag_layout) +--------------------------------------------------------------- +Everything here must produce a valid embedding of the same graph the frozen +engine searches for, so the rules are restated explicitly: + +* `create_linear_chains(norb)` makes two disjoint paths. Template node `j` is + alpha orbital j (0 <= j < norb); template node `norb + j` is beta orbital j. + Edges: (j, j+1) and (norb+j, norb+j+1) for j in 0..norb-2. +* Bridges sit at orbital slots `n` with `n % 4 == 0`, so slot 0 ALWAYS carries + a bridge and the geometric ceiling is `ceil(norb / 4)`. Bridge i is template + node `2*norb + i` and is adjacent to exactly two nodes: alpha slot `4*i` and + beta slot `4*i`. +* A layout is the list `alpha(norb) + beta(norb) + bridges(k)`, and an + embedding is valid iff it is injective and every template edge maps to a + coupling edge. + +LUCJ PREFIX CONTRACT (from ancilla_sweep, and binding here) + A k'-bridge variant keeps the bridges at the FIRST k' standard slots + `(0, 4, ..., 4*(k'-1))` and drops the tail — one variant per k', never a + scattered subset like {0, 8, 12}. A scattered set is a valid subgraph with + a valid score but a semantically invalid ansatz layout. `bridge_slots` is + therefore always `tuple(range(0, 4*k', 4))`, which is what certifies it. + +CANONICALISATION + `_deduplicate_layouts` treats a layout and its alpha/beta swap as the same + thing; `_embedding_data` normalises by putting the chain with the smaller + first element in alpha. Both are mirrored here (`_normalise_chains`), so + the two engines agree on what counts as a duplicate. + + +SCORING +------- +Two scores, exactly as the frozen engine defines them: + +* `additive_score` — sum of readout errors over used qubits plus 2Q errors + over used edges. Grows with layout size, so it is comparable WITHIN a + stratum only, never across. +* `product_score` — `prod(1 - readout) * prod(1 - gate_err)`. Adding a bridge + multiplies by `(1-r)(1-e1)(1-e2) <= 1`, so it is comparable across strata. + This is the beam's incremental objective, accumulated in log space to keep + long chains numerically honest, and the pre-filter for the final window. + +The FINAL ranking and the refinement objective are the circuit-level LQS +(`circuit_score_fn`), the same scorer the UI banner shows. The product score +is a proxy used to decide what to keep, not what to recommend. + +Uncalibrated or NaN values take `ancilla_sweep._UNCALIBRATED_PENALTY`, via the +frozen module's own `_safe_readout` / `_safe_gate_error` — imported, not +reimplemented, so the two engines cannot drift apart on this. + + +WHAT THIS DOES NOT DO +--------------------- +Beam search is a heuristic. It can miss the global optimum that exhaustive VF2 +would find on a small device, which is precisely why the default stays VF2 and +why `evaluation.compare_engines` exists. On the fixtures in the test suite the +two agree; on a 193-qubit chip VF2 cannot enumerate the space at all, so the +comparison there is between a guided sample and an arbitrary one. +""" +import logging +import math +import time +from collections import namedtuple + +import numpy as np +import rustworkx + +from .ancilla_sweep import (_UNCALIBRATED_PENALTY, _safe_gate_error, + _safe_readout, _select_with_diversity) +from .auto_lucj import (_get_two_q_gate_name, _make_backend_cmap_pygraph, + _remove_nodes_from_graph, create_lucj_zigzag_layout) + +_log = logging.getLogger(__name__) + +#: Beam width default. 200 partial states per growth step is ample on +#: heavy-hex, where a chain qubit has at most 3 candidate continuations. +DEFAULT_BEAM_WIDTH = 200 + +#: How many finalists per stratum get the 1-opt polish. +DEFAULT_REFINE_TOP = 5 + +#: Iteration ceiling for 1-opt, so a pathological calibration cannot spin. +DEFAULT_MAX_ITER = 20 + +#: log(0) guard: a completely dead qubit/edge scores as this, not -inf, so a +#: partial state carrying one can still be compared and discarded on merit. +_LOG_FLOOR = -30.0 + +Move = namedtuple('Move', 'kind index qubit') + + +# ── template helpers ──────────────────────────────────────────────── + +def bridge_slots_for(k): + """The standard slots a k-bridge layout occupies. Prefix contract.""" + return tuple(range(0, 4 * k, 4)) + + +def max_bridges_for(norb): + """Geometric ceiling: one bridge every 4 orbitals, slot 0 included.""" + return (norb + 3) // 4 + + +def template_edges(norb, k): + """Every edge of the LUCJ template, as (template_node, template_node). + + Chain edges first, then the two edges of each bridge. Positions follow the + layout convention: alpha = 0..norb-1, beta = norb..2norb-1, bridge i = + 2*norb + i. + """ + edges = [] + for j in range(norb - 1): + edges.append((j, j + 1)) + edges.append((norb + j, norb + j + 1)) + for i in range(k): + slot = 4 * i + edges.append((slot, 2 * norb + i)) + edges.append((2 * norb + i, norb + slot)) + return edges + + +def validate_layout(layout, norb, k, adjacency): + """True iff `layout` is a valid embedding of the (norb, k) template. + + Checks injectivity and that every template edge lands on a coupling edge. + Used after every refinement move, because a move that produced an invalid + layout would be worse than no refinement at all. + """ + expected = 2 * norb + k + if len(layout) != expected or any(q is None for q in layout): + return False + if len(set(layout)) != expected: + return False + for u, v in template_edges(norb, k): + if layout[v] not in adjacency.get(layout[u], ()): + return False + return True + + +def _normalise_chains(alpha, beta): + """Mirror `_embedding_data`: alpha is the chain with the smaller head.""" + if alpha and beta and alpha[0] > beta[0]: + return list(beta), list(alpha) + return list(alpha), list(beta) + + +# ── search state ──────────────────────────────────────────────────── + +class _Partial: + """A partially grown layout: both chain prefixes plus its bridges. + + `depth` is how many orbital slots are filled (identical on both chains — + they grow in lockstep so a bridge slot can always see both endpoints). + """ + + __slots__ = ('alpha', 'beta', 'bridges', 'used', 'log_score', 'add_score') + + def __init__(self, alpha, beta, bridges, used, log_score, add_score): + self.alpha = alpha + self.beta = beta + self.bridges = bridges + self.used = used + self.log_score = log_score + self.add_score = add_score + + @property + def depth(self): + return len(self.alpha) + + def key(self): + """Canonical identity, collapsing the alpha/beta swap.""" + a, b = _normalise_chains(self.alpha, self.beta) + return (tuple(a), tuple(b), tuple(self.bridges)) + + def extend(self, a, b, bridge, d_log, d_add): + used = self.used | {a, b} + bridges = self.bridges + if bridge is not None: + used = used | {bridge} + bridges = bridges + [bridge] + return _Partial(self.alpha + [a], self.beta + [b], bridges, used, + self.log_score + d_log, self.add_score + d_add) + + +def _safe_log(value): + """log of a fidelity factor, floored so a dead element stays comparable.""" + if value <= 0.0: + return _LOG_FLOOR + return max(_LOG_FLOOR, math.log(value)) + + +# ── the engine ────────────────────────────────────────────────────── + +class _GuidedEngine: + """Holds the graph, the calibration and the growth rules for one run.""" + + def __init__(self, norb, graph, readout, edge_err, qubit_weight=None): + self.norb = norb + self.graph = graph + self.readout = readout + self.edge_err = edge_err + self.qubit_weight = qubit_weight + self.expansions = 0 + self.adjacency = {} + for node in graph.node_indices(): + self.adjacency[node] = frozenset(graph.neighbors(node)) + + # ── per-element factors ───────────────────────────────────── + def r_of(self, q): + try: + return float(self.readout[q]) + except (IndexError, TypeError): + return _UNCALIBRATED_PENALTY + + def e_of(self, a, b): + return self.edge_err.get(frozenset((a, b)), _UNCALIBRATED_PENALTY) + + def q_factor(self, q): + """(1 - readout) for a qubit, times the optional weight hook.""" + factor = max(0.0, 1.0 - self.r_of(q)) + if self.qubit_weight is not None: + try: + weight = float(self.qubit_weight(q)) + except Exception: + weight = 1.0 + factor *= max(0.0, min(1.0, weight)) + return factor + + def e_factor(self, a, b): + return max(0.0, 1.0 - self.e_of(a, b)) + + # ── seeding ───────────────────────────────────────────────── + def seeds(self, k_target): + """Initial states at orbital slot 0. + + Slot 0 always carries a bridge when k >= 1 (n % 4 == 0 includes 0), so + a seed is a (bridge, alpha0, beta0) triple with the bridge adjacent to + both chain heads. With k == 0 there is no bridge and a seed is any + ordered pair of distinct qubits — collapsed by canonicalisation. + """ + out = [] + # Iterate the ADJACENCY, not the graph: excluded qubits (and any + # padding nodes used to keep physical ids as indices) are absent from + # adjacency by construction, and must never seed a layout. + if k_target >= 1: + for r in sorted(self.adjacency): + neighbours = sorted(self.adjacency[r]) + for i, a in enumerate(neighbours): + for b in neighbours[i + 1:]: + d_log = (_safe_log(self.q_factor(a)) + + _safe_log(self.q_factor(b)) + + _safe_log(self.q_factor(r)) + + _safe_log(self.e_factor(a, r)) + + _safe_log(self.e_factor(r, b))) + d_add = (self.r_of(a) + self.r_of(b) + self.r_of(r) + + self.e_of(a, r) + self.e_of(r, b)) + out.append(_Partial([a], [b], [r], {a, b, r}, + d_log, d_add)) + else: + nodes = sorted(self.adjacency) + for i, a in enumerate(nodes): + for b in nodes[i + 1:]: + d_log = (_safe_log(self.q_factor(a)) + + _safe_log(self.q_factor(b))) + d_add = self.r_of(a) + self.r_of(b) + out.append(_Partial([a], [b], [], {a, b}, d_log, d_add)) + return out + + # ── growth ────────────────────────────────────────────────── + def _slot_has_bridge(self, j, k_target): + """Does orbital slot j carry a bridge in a k_target layout?""" + return j % 4 == 0 and (j // 4) < k_target + + def expand(self, state, k_target): + """Every legal one-slot extension of `state`.""" + j = state.depth + a_prev, b_prev = state.alpha[-1], state.beta[-1] + want_bridge = self._slot_has_bridge(j, k_target) + out = [] + for a in sorted(self.adjacency.get(a_prev, frozenset())): + if a in state.used: + continue + for b in sorted(self.adjacency.get(b_prev, frozenset())): + if b in state.used or b == a: + continue + self.expansions += 1 + d_log = (_safe_log(self.q_factor(a)) + + _safe_log(self.q_factor(b)) + + _safe_log(self.e_factor(a_prev, a)) + + _safe_log(self.e_factor(b_prev, b))) + d_add = (self.r_of(a) + self.r_of(b) + + self.e_of(a_prev, a) + self.e_of(b_prev, b)) + if not want_bridge: + out.append(state.extend(a, b, None, d_log, d_add)) + continue + common = (self.adjacency.get(a, frozenset()) + & self.adjacency.get(b, frozenset())) + for r in sorted(common): + if r in state.used or r in (a, b): + continue + b_log = (_safe_log(self.q_factor(r)) + + _safe_log(self.e_factor(a, r)) + + _safe_log(self.e_factor(r, b))) + b_add = self.r_of(r) + self.e_of(a, r) + self.e_of(r, b) + out.append(state.extend(a, b, r, d_log + b_log, + d_add + b_add)) + return out + + def run_beam(self, k_target, beam_width): + """Grow to full length, keeping the best `beam_width` states. + + Pruning only ever compares states of the same depth, so a long + mediocre chain is never ranked against a short excellent one. + """ + beam = self._prune(self.seeds(k_target), beam_width) + for _j in range(1, self.norb): + nxt = [] + for state in beam: + nxt.extend(self.expand(state, k_target)) + if not nxt: + return [] + beam = self._prune(nxt, beam_width) + return beam + + @staticmethod + def _prune(states, beam_width): + """Top-`beam_width` by score, deduplicated, deterministic ties.""" + best = {} + for state in states: + key = state.key() + current = best.get(key) + if current is None or state.log_score > current.log_score: + best[key] = state + ranked = sorted(best.values(), + key=lambda s: (-s.log_score, s.key())) + return ranked[:beam_width] + + +# ── entry construction (mirrors ancilla_sweep._add_variant) ───────── + +def _entry_from_state(engine, alpha, beta, bridges, k): + """Build a sweep-shaped entry for the first `k` bridges of a layout. + + Recomputes both scores from scratch over the kept elements rather than + reusing the beam's incremental total, because a derived k' variant drops + bridges and because the frozen engine's numbers are the reference — see + test_guided_search.py::test_score_parity_with_the_frozen_sweep. + """ + norb = engine.norb + kept = list(bridges[:k]) + norm_alpha, norm_beta = _normalise_chains(alpha, beta) + chain = norm_alpha + norm_beta + + chain_q = np.array(chain, dtype=int) + readout_vals = np.array([engine.r_of(q) for q in chain_q], dtype=float) + chain_edges = ([(norm_alpha[j], norm_alpha[j + 1]) for j in range(norb - 1)] + + [(norm_beta[j], norm_beta[j + 1]) for j in range(norb - 1)]) + gate_vals = np.array([engine.e_of(a, b) for a, b in chain_edges], + dtype=float) + + additive = float(readout_vals.sum() + gate_vals.sum()) + product = float(np.prod(np.clip(1.0 - readout_vals, 0.0, 1.0)) + * np.prod(np.clip(1.0 - gate_vals, 0.0, 1.0))) + + for i, bphys in enumerate(kept): + slot = 4 * i + e1 = engine.e_of(norm_alpha[slot], bphys) + e2 = engine.e_of(bphys, norm_beta[slot]) + r = engine.r_of(bphys) + additive += r + e1 + e2 + product *= (max(0.0, 1.0 - r) * max(0.0, 1.0 - e1) + * max(0.0, 1.0 - e2)) + + return { + 'layout': list(chain), + 'alpha': list(norm_alpha), + 'beta': list(norm_beta), + 'ancillas': kept, + 'bridge_slots': bridge_slots_for(k), + 'product_score': product, + 'additive_score': additive, + 'rank_in_stratum': 0, + 'source': 'guided', + 'chain_fs': frozenset(chain), + } + + +# ── 1-opt local refinement ────────────────────────────────────────── + +def _candidate_moves(engine, entry, k): + """Every 1-opt neighbour of `entry`, as (label, new_layout_parts). + + Three move families, all preserving the template by construction and + re-validated afterwards anyway: + + bridge — swap a bridge for another common unused neighbour of the two + chain qubits it joins; + end — swap a chain END qubit for another unused neighbour of its + predecessor (both ends, both chains); + shift — move a whole chain one step along a parallel path. + """ + norb = engine.norb + alpha, beta = list(entry['alpha']), list(entry['beta']) + bridges = list(entry['ancillas']) + used = set(alpha) | set(beta) | set(bridges) + adj = engine.adjacency + out = [] + + # (i) bridge replacement + for i, bphys in enumerate(bridges): + slot = 4 * i + common = adj.get(alpha[slot], frozenset()) & adj.get(beta[slot], + frozenset()) + for r in sorted(common): + if r in used or r == bphys: + continue + new_bridges = list(bridges) + new_bridges[i] = r + out.append(('bridge', alpha, beta, new_bridges)) + + # (ii) chain-end replacement, both ends of both chains + for chain_name, chain in (('alpha', alpha), ('beta', beta)): + if norb < 2: + break + for end_idx, neighbour_idx in ((norb - 1, norb - 2), (0, 1)): + # A head swap is only free when slot 0 carries no bridge; with a + # bridge there the head is pinned by the bridge's two edges, and + # the bridge move above already covers that region. + if end_idx == 0 and k >= 1: + continue + anchor = chain[neighbour_idx] + for q in sorted(adj.get(anchor, frozenset())): + if q in used or q == chain[end_idx]: + continue + new_chain = list(chain) + new_chain[end_idx] = q + if chain_name == 'alpha': + out.append(('end', new_chain, beta, bridges)) + else: + out.append(('end', alpha, new_chain, bridges)) + + # (iii) whole-chain shift along a parallel path + for chain_name, chain in (('alpha', alpha), ('beta', beta)): + tail = chain[-1] + for q in sorted(adj.get(tail, frozenset())): + if q in used: + continue + shifted = chain[1:] + [q] + if chain_name == 'alpha': + out.append(('shift', shifted, beta, bridges)) + else: + out.append(('shift', alpha, shifted, bridges)) + + return out + + +def refine_entry(engine, entry, k, circuit_score_fn, max_iter=DEFAULT_MAX_ITER): + """Hill-climb `entry` on LQS with 1-opt moves. Returns (entry, changed). + + Accepts a move only when the circuit-level score strictly improves, and + only when the result is still a valid embedding. A scoring failure on a + neighbour is treated as "no improvement" rather than an error, so a flaky + scorer degrades the polish instead of breaking the sweep. + """ + if circuit_score_fn is None: + return entry, False + + current = entry + best_score = current.get('lqs_circuit') + if best_score is None: + try: + best_score = circuit_score_fn(current) + except Exception: + return entry, False + current['lqs_circuit'] = best_score + if best_score is None: + return entry, False + + changed = False + for _iteration in range(max_iter): + improved = False + for _kind, alpha, beta, bridges in _candidate_moves(engine, current, k): + layout = list(alpha) + list(beta) + list(bridges) + if not validate_layout(layout, engine.norb, k, engine.adjacency): + continue + cand = _entry_from_state(engine, alpha, beta, bridges, k) + try: + score = circuit_score_fn(cand) + except Exception: + continue + if score is None or not (score > best_score): + continue + cand['lqs_circuit'] = score + cand['source'] = current.get('source', 'guided') + current, best_score = cand, score + improved = changed = True + break # first-improvement, restart + if not improved: + break + return current, changed + + +# ── public API ────────────────────────────────────────────────────── + +def guided_sweep(norb, backend, props, *, min_bridges=None, top_n=3, + exclude_qubits=None, circuit_score_fn=None, + diversity_threshold=None, beam_width=DEFAULT_BEAM_WIDTH, + refine_top=DEFAULT_REFINE_TOP, qubit_weight=None, + max_iter=DEFAULT_MAX_ITER, seed=0) -> dict: + """Calibration-guided beam search over LUCJ layouts. + + Returns the SAME dict shape as `ancilla_sweep.sweep_ancilla_layouts`, so + every downstream consumer (strata display, best-per-k, diversity badges, + notices, LQS re-scoring, benchmark re-ranking) works unchanged. The extra + keys `engine`, `refined_count`, `beam_width` and `expansions` are additive. + + Args mirror the frozen sweep where they exist, plus: + beam_width: partial states kept per growth step. + refine_top: how many finalists per stratum get the 1-opt polish. + qubit_weight: optional ``callable(q) -> float in (0, 1]`` folded into + each qubit's fidelity factor — the hook for stability/T1/T2 + weighting in a later phase. Default None = no weighting. + max_iter: 1-opt iteration ceiling. + seed: reserved for deterministic tie-breaking; the search itself is + already deterministic (sorted expansion, canonical tie-break). + """ + started = time.time() + + full_graph = _make_backend_cmap_pygraph(backend=backend) + excluded_sorted = sorted(int(q) for q in exclude_qubits) if exclude_qubits \ + else [] + if excluded_sorted: + for i in full_graph.node_indices(): + full_graph[i] = i + search_graph = _remove_nodes_from_graph(full_graph, + set(excluded_sorted)) + phys = {i: search_graph[i] for i in search_graph.node_indices()} + else: + search_graph = full_graph + phys = {i: i for i in search_graph.node_indices()} + + # Work in physical-qubit space throughout: rebuild the pruned graph with + # physical ids as node indices so scores, adjacency and layouts all agree. + work = rustworkx.PyGraph() + id_map = {} + for node in search_graph.node_indices(): + id_map[node] = work.add_node(phys[node]) + for u, v in search_graph.edge_list(): + work.add_edge(id_map[u], id_map[v], None) + index_to_phys = {id_map[n]: phys[n] for n in search_graph.node_indices()} + + # k_max from the same template routine the frozen engine uses, so the two + # agree on the geometric ceiling for this backend. + _template, k_max_effective = create_lucj_zigzag_layout( + num_orbitals=norb, backend_coupling_graph=search_graph, + requested_bridges=-1) + + if min_bridges is None: + min_bridges = min(3, k_max_effective) + if not (1 <= min_bridges <= k_max_effective): + raise ValueError( + f"min_bridges={min_bridges} out of range; must satisfy " + f"1 <= min_bridges <= k_max_effective ({k_max_effective}).") + + gate_name = _get_two_q_gate_name(backend) + if gate_name is None: + raise RuntimeError("Could not determine the backend 2Q gate name.") + + node_indices = list(full_graph.node_indices()) + max_id = max(node_indices) if node_indices else 0 + readout = np.full(max_id + 1, _UNCALIBRATED_PENALTY, dtype=float) + for q in node_indices: + readout[q] = _safe_readout(props, q) + edge_err = {} + for u, v in full_graph.edge_list(): + edge_err[frozenset((u, v))] = _safe_gate_error(props, gate_name, u, v) + + # The engine indexes adjacency by PHYSICAL id. + phys_graph = rustworkx.PyGraph() + seen_nodes = {} + for idx in work.node_indices(): + q = index_to_phys[idx] + seen_nodes[q] = q + for q in sorted(seen_nodes): + while len(phys_graph.node_indices()) <= q: + phys_graph.add_node(None) + phys_graph[q] = q + for u, v in work.edge_list(): + phys_graph.add_edge(index_to_phys[u], index_to_phys[v], None) + live = set(seen_nodes) + + engine = _GuidedEngine(norb, phys_graph, readout, edge_err, qubit_weight) + # Restrict adjacency to live (non-excluded) qubits. + engine.adjacency = {q: frozenset(n for n in phys_graph.neighbors(q) + if n in live) + for q in live} + + strata_pool = {k: {} for k in range(k_max_effective, min_bridges - 1, -1)} + per_stratum = {k: {'n_direct': 0, 'n_derived': 0, 'truncated': False, + 'shuffled': False} + for k in range(k_max_effective, min_bridges - 1, -1)} + n_candidates_scored = 0 + n_raw_embeddings = 0 + + def _add(alpha, beta, bridges, k, source): + entry = _entry_from_state(engine, alpha, beta, bridges, k) + key = (entry['chain_fs'], frozenset(entry['ancillas'])) + if key in strata_pool[k]: + return False + entry['source'] = source + strata_pool[k][key] = entry + return True + + # ── generation: one beam at k_max, cascading down by the prefix + # contract, plus a direct beam per lower k. The guided search does not + # explode at low k the way VF2 enumeration does (the beam is bounded by + # construction), so no cap is needed and every stratum gets a direct pass. + for k_direct in range(k_max_effective, min_bridges - 1, -1): + finals = engine.run_beam(k_direct, beam_width) + n_raw_embeddings += len(finals) + for state in finals: + for k in range(k_direct, min_bridges - 1, -1): + n_candidates_scored += 1 + source = 'guided' if k == k_direct else 'derived' + if _add(state.alpha, state.beta, state.bridges, k, source): + bucket = 'n_direct' if k == k_direct else 'n_derived' + per_stratum[k][bucket] += 1 + + if n_raw_embeddings == 0: + raise RuntimeError( + f"Guided search found no complete zigzag embedding for " + f"norb={norb} on this backend.") + + # ── ranking, refinement, diversity — mirroring the frozen engine + strata = {} + higher_winners = [] + refined_count = 0 + refine_attempted = 0 + + for k in range(k_max_effective, min_bridges - 1, -1): + pool = strata_pool[k] + by_product = sorted(pool.items(), + key=lambda kv: (-kv[1]['product_score'], + tuple(kv[1]['layout']))) + + if circuit_score_fn is None: + if diversity_threshold is None: + entries = [e for _, e in by_product[:top_n]] + else: + entries = _select_with_diversity( + [e for _, e in by_product], top_n, diversity_threshold) + for rank, entry in enumerate(entries, start=1): + entry['rank_in_stratum'] = rank + strata[k] = entries + continue + + W = max(top_n * 5, 25) + window_keys = [key for key, _ in by_product[:W]] + seen = set(window_keys) + for chain_fs, anc_full in higher_winners: + if len(anc_full) < k: + continue + akey = (chain_fs, frozenset(anc_full[:k])) + if akey in pool and akey not in seen: + seen.add(akey) + window_keys.append(akey) + window = [pool[key] for key in window_keys] + + for entry in window: + try: + entry['lqs_circuit'] = circuit_score_fn(entry) + except Exception as exc: + _log.warning("Circuit scoring failed for a guided candidate " + "(k=%d): %s", k, exc) + entry['lqs_circuit'] = None + window.sort( + key=lambda e: (e['lqs_circuit'] is not None, + e['lqs_circuit'] if e['lqs_circuit'] is not None + else 0.0, + e['product_score']), + reverse=True) + + # 1-opt polish on the finalists, before the diversity slice so a + # refined layout competes on its improved score. + for pos in range(min(refine_top, len(window))): + refine_attempted += 1 + refined, changed = refine_entry(engine, window[pos], k, + circuit_score_fn, max_iter) + if changed: + refined['refined'] = True + refined_count += 1 + window[pos] = refined + else: + window[pos].setdefault('refined', False) + window.sort( + key=lambda e: (e['lqs_circuit'] is not None, + e['lqs_circuit'] if e['lqs_circuit'] is not None + else 0.0, + e['product_score']), + reverse=True) + + if diversity_threshold is None: + entries = window[:top_n] + else: + entries = _select_with_diversity(window, top_n, + diversity_threshold) + for rank, entry in enumerate(entries, start=1): + entry['rank_in_stratum'] = rank + entry.setdefault('refined', False) + strata[k] = entries + higher_winners.extend( + (frozenset(e['layout']), tuple(e['ancillas'])) for e in entries) + + return { + 'strata': strata, + 'k_max_effective': k_max_effective, + 'min_bridges': min_bridges, + 'vf2_truncated': False, # the beam is bounded, never truncated + 'n_raw_embeddings': n_raw_embeddings, + 'n_candidates_scored': n_candidates_scored, + 'excluded_qubits': excluded_sorted, + 'per_stratum': per_stratum, + 'mapping_cap': None, # not a VF2 run; no cap applies + 'engine': 'guided', + 'beam_width': beam_width, + 'refined_count': refined_count, + 'refine_attempted': refine_attempted, + 'expansions': engine.expansions, + 'elapsed_s': time.time() - started, + } diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index a18c84d..36ffe22 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -324,6 +324,10 @@ def _run_pipeline(self): lucj_search_cap=self.lucj_search_cap, lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, chk_lucj_diverse=self.chk_lucj_diverse, + dd_search_engine=self.dd_search_engine, + int_beam_width=self.int_beam_width, + int_refine_top=self.int_refine_top, + guided_params_box=self.bench_guided_box, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, lbl_lucj_notices=self.lbl_lucj_notices, @@ -1399,11 +1403,44 @@ def _build_auto_lucj_widgets(self, W): self.lbl_bench_status, ], layout=W) + # ── Search engine (Advanced) ───────────────────────────── + # Default stays Exhaustive (VF2) until iqmapper.evaluation says the + # guided beam wins on real cached calibration — see the harness. + self.dd_search_engine = Dropdown( + options=[('Exhaustive (VF2)', 'vf2'), ('Guided (beam)', 'guided')], + value='vf2', + description='Search engine:', + layout=Layout(width='280px'), + style={'description_width': '110px'}, + tooltip='Exhaustive enumerates zigzag embeddings with VF2 and is ' + 'calibration-blind (capped at the search cap). Guided ' + 'grows chains using the calibration and polishes the ' + 'finalists; it is a heuristic, so it stays opt-in.') + _guided_layout = Layout(width=W.width, margin=W.margin, + min_width=W.min_width) + _guided_layout.display = 'none' # shown only for Guided + self.bench_guided_box = VBox([], layout=_guided_layout) + self.int_beam_width = BoundedIntText( + value=200, min=10, max=5000, step=50, + description='Beam width:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='partial layouts kept at each growth step') + self.int_refine_top = BoundedIntText( + value=5, min=0, max=50, + description='Refine top:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='how many finalists per ancilla count get the 1-opt polish') + self.bench_guided_box.children = [self.int_beam_width, + self.int_refine_top] + # Expert knobs, collapsed out of the primary flow (ancilla dropdown # -> Run). The defaults are right for nearly everyone, and the notices # bar already reports when the cap truncated a search. self.lucj_advanced_acc = Accordion( - children=[VBox([self.lucj_search_cap, self.chk_deep_search])], + children=[VBox([self.lucj_search_cap, self.chk_deep_search, + self.dd_search_engine, self.bench_guided_box])], layout=W) self.lucj_advanced_acc.set_title(0, '⚙️ Advanced') self.lucj_advanced_acc.selected_index = None # collapsed on open diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 90e8e98..a7e5173 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -190,6 +190,10 @@ def setup_lucj_callbacks(ctx): lucj_chk_score = ctx.lucj_chk_score chk_deep_search = ctx.chk_deep_search chk_lucj_diverse = ctx.chk_lucj_diverse + dd_search_engine = getattr(ctx, 'dd_search_engine', None) + int_beam_width = getattr(ctx, 'int_beam_width', None) + int_refine_top = getattr(ctx, 'int_refine_top', None) + guided_params_box = getattr(ctx, 'guided_params_box', None) btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status lbl_lucj_trunc = ctx.lbl_lucj_trunc @@ -471,6 +475,56 @@ def _sweep_kwargs_from_ui(): 'diversity_threshold': 0.8 if chk_lucj_diverse.value else None, } + # ── ONE dispatch point for the search engine ───────────────── + def _selected_engine(): + """'vf2' (default) or 'guided'. Absent widget → the frozen default.""" + return getattr(dd_search_engine, 'value', 'vf2') or 'vf2' + + def _guided_params(): + return { + 'beam_width': int(getattr(int_beam_width, 'value', 200) or 200), + 'refine_top': int(getattr(int_refine_top, 'value', 5) or 5), + } + + def _run_sweep(norb, backend, props, **kwargs): + """Run the selected search engine. + + Both engines return the same dict shape, so every caller below and all + the display code downstream is engine-agnostic. `hybrid` and + `mapping_cap` are VF2-only concepts (the beam is bounded by + construction and never truncates), so they are dropped for guided + rather than passed and ignored. + """ + if _selected_engine() != 'guided': + from ..ancilla_sweep import sweep_ancilla_layouts + return sweep_ancilla_layouts(norb, backend, props, **kwargs) + + from ..guided_search import guided_sweep + guided_kwargs = {k: v for k, v in kwargs.items() + if k not in ('hybrid', 'mapping_cap', 'shuffle_seed')} + guided_kwargs.update(_guided_params()) + return guided_sweep(norb, backend, props, **guided_kwargs) + + def _engine_suffix(res): + """Status-line tail naming the engine, and the refinement tally.""" + if not isinstance(res, dict) or res.get('engine') != 'guided': + return "" + attempted = res.get('refine_attempted') or 0 + refined = res.get('refined_count') or 0 + return (f" · engine: guided · refined {refined}/{attempted}" + if attempted else " · engine: guided") + + def _on_engine_change(_change=None): + """Guided-only params are hidden while Exhaustive is selected.""" + if guided_params_box is None: + return + guided_params_box.layout.display = ( + '' if _selected_engine() == 'guided' else 'none') + + if dd_search_engine is not None: + dd_search_engine.observe(_on_engine_change, names='value') + _on_engine_change() + # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the # active backend's reference in the scan table, so the scan never # re-searches self yet keeps the reference point. @@ -559,7 +613,7 @@ def _generate_sweep(norb): # the same floor through sweep_with_stability's quality_sigma, so # they never both fire on one search — no double-exclusion). floor_excl = _floor_exclusions() - res = sweep_ancilla_layouts( + res = _run_sweep( norb, state.active_backend, scoring_props, circuit_score_fn=_circuit_score, # aligned circuit LQS exclude_qubits=(floor_excl or None), @@ -636,7 +690,7 @@ def _generate_sweep(norb): f"
✅ {_format_sweep_status(res)}{mode_txt}" - f"{cap_txt}{vin_txt}
") + f"{cap_txt}{vin_txt}{_engine_suffix(res)}") else: lbl_lucj_status.value = ( f""), self.tb_bench_qpu, self.dd_bench_target, self.txt_bench_custom, @@ -1470,13 +1458,8 @@ def _build_auto_lucj_widgets(self, W): value=True, description='Diverse enumeration', layout=_diverse_layout, - tooltip='Make the search cap count DISTINCT candidates: during ' - 'enumeration a layout that overlaps a kept one by 80% ' - 'and does not score better is discarded without using a ' - 'slot. Engages only where the cap is actually reached — ' - 'the low-bridge (hybrid) passes; at the maximum bridge ' - 'count the search finds fewer layouts than the cap and ' - 'nothing is filtered. Off = the historical behaviour.') + tooltip='Counts only distinct candidates toward the search ' + 'cap · README: Diverse enumeration') # ── Search engine (Advanced) ───────────────────────────── # Default stays Exhaustive (VF2) until iqmapper.evaluation says the @@ -1487,10 +1470,8 @@ def _build_auto_lucj_widgets(self, W): description='Search engine:', layout=Layout(width='280px'), style={'description_width': '110px'}, - tooltip='Exhaustive enumerates zigzag embeddings with VF2 and is ' - 'calibration-blind (capped at the search cap). Guided ' - 'grows chains using the calibration and polishes the ' - 'finalists; it is a heuristic, so it stays opt-in.') + tooltip='Exhaustive = VF2 (calibration-blind); Guided = ' + 'calibration-led beam search · README: Search engine') _guided_layout = Layout(width=W.width, margin=W.margin, min_width=W.min_width) _guided_layout.display = 'none' # shown only for Guided @@ -1553,9 +1534,8 @@ def _build_auto_lucj_widgets(self, W): value=3.0, min=0.0, max=20.0, step=0.5, description='Quality floor:', layout=Layout(width='230px'), style={'description_width': '110px'}, - tooltip='Always on: exclude qubits whose CURRENT readout error is ' - 'more than this many σ above the device mean (0 = off). ' - 'Applies to single, multi and scan searches.') + tooltip='Excludes qubits whose readout error is more than N ' + 'sigma above the device mean (0 = off)') # Window + threshold row, revealed only when the volatility filter is on. self.stability_ctrl_box = VBox( [self.rb_stability_window_auto, self.ft_stability_threshold]) diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index e03884a..19b55c5 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -375,11 +375,9 @@ def _on_lucj_layout_select(change): # the Estimated Layout-Quality box reports. '(template)' flags the # internal heuristic used only when circuit scoring is unavailable. with contextlib.suppress(Exception): - dd_lucj_layout.tooltip = ('LQS = circuit-level fidelity, the same ' - 'number as the Estimated Layout-Quality ' - 'box. "(template)" = internal heuristic ' - 'fallback when circuit scoring is ' - 'unavailable.') + dd_lucj_layout.tooltip = ( + 'LQS = circuit-level fidelity; "(template)" = fallback ' + 'heuristic \u00b7 README: LQS') dd_lucj_layout.observe(_on_lucj_layout_select, names='value') # ── Dropdown re-seed helper (observer-safe) ────────────────── @@ -1497,9 +1495,10 @@ def _on_lucj_multi(b): return if len(ancilla_list) != len(norb_list): lbl_lucj_multi.value = ( - f"❌ Ancilla list has " - f"{len(ancilla_list)} value(s) but {len(norb_list)} circuit(s). Match them " - f"(norb '8, 8' → ancilla '2, 2'), or leave ancilla blank.") + f"❌ " + f"{len(ancilla_list)} ancilla values but " + f"{len(norb_list)} circuits — match them or leave " + f"ancilla blank.") return btn_lucj_multi.disabled = True @@ -1737,9 +1736,9 @@ def _multi_failed_banner(result): return ( f"
⚠️ circuit {i + 1} does not fit after " - f"C1..C{i} + buffer — reduce norb or ancillas. The circuits that " - f"fit are placed above.
") + f"margin:4px 0;'>⚠️ Circuit doesn't fit after C1..C{i} — " + f"reduce norb or ancillas; the ones that fit are placed" + f"") def _multi_override_disabled(disabled): for dd in _multi_sweep['dropdowns'].values(): diff --git a/iqmapper/ui/session_io.py b/iqmapper/ui/session_io.py index 3cac929..c2464b7 100644 --- a/iqmapper/ui/session_io.py +++ b/iqmapper/ui/session_io.py @@ -249,12 +249,9 @@ def _on_load_session(change): f"
" - f"⚠️ Session loaded in offline mode. " - f"No backend is connected.
" - f"Layout editing and static export work normally.
" - f"These features require a live backend connection: " - f"Delta Mode, Calibration History, Fetch History, " - f"Error Map refresh.
" + f"⚠️ Offline session: no backend connected. " + f"Live data needs a connection " + f"· README: Offline mode
" f"To reconnect: select '{esc(backend_name or 'your backend')}' " f"from the Backend dropdown above.
" ) diff --git a/iqmapper/ui/time_panel.py b/iqmapper/ui/time_panel.py index 7e0a642..7152f32 100644 --- a/iqmapper/ui/time_panel.py +++ b/iqmapper/ui/time_panel.py @@ -1266,13 +1266,11 @@ def build_time_panel( def _auto_ref_hint(state) -> str: mode = state.delta_ref_mode if mode == 'first': - return ("Reference = first calibration of the current sequence. " - "Works when View is Intraday or Multi-day. " - "Use this to see cumulative drift from a starting point.") + return ("Reference = first calibration of the sequence " + "(cumulative drift) \u00b7 README: Delta references") if mode == 'previous': - return ("Reference = previous calibration in the sequence. " - "The delta updates as you move the slider, showing step-by-step " - "change. At the first position there is no delta.") + return ("Reference = previous calibration in the sequence " + "(step-by-step change) \u00b7 README: Delta references") return "" diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 0bbf01a..0000000 --- a/requirements.txt +++ /dev/null @@ -1,27 +0,0 @@ -# I-QMapper — runtime dependencies. -# Mirrors [project.dependencies] in pyproject.toml (the source of truth). -# Install with: pip install -r requirements.txt -# Requires Python >= 3.10. - -# ── Core (required) ───────────────────────────────────────────────────────── -numpy>=1.23 -plotly>=5.13 -ipywidgets>=8.0 -ipython>=8.0 -anywidget>=0.9 -qiskit-ibm-runtime>=0.20 -qiskit>=1.0 -rustworkx>=0.13 -platformdirs>=3.0 - -# ── Optional features (uncomment as needed) ───────────────────────────────── -# PNG export (Export tab → "Export PNG"): the static image renderer. -# kaleido - -# Time-lapse GIF export (Export tab → "Export Time-Lapse"). -# imageio -# imageio-ffmpeg - -# ── Development / tests ───────────────────────────────────────────────────── -# pytest>=7 -# pytest-cov diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 0adda92..0bd2b4c 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -360,7 +360,9 @@ def test_diverse_enumeration_checkbox_defaults_on(monkeypatch): for w in _descendants(b.lucj_advanced_acc)), \ 'the checkbox is not in the Advanced accordion' tip = b.chk_diverse_cap.tooltip - assert 'DISTINCT' in tip and 'hybrid' in tip, tip + assert 'distinct candidates' in tip, tip + assert 'README: Diverse enumeration' in tip, tip + assert len(tip) <= 90, f'tooltip is {len(tip)} chars' def test_diverse_enumeration_reaches_the_sweep(monkeypatch): diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index ae9c33b..3d8bd89 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -1346,8 +1346,10 @@ def _initialize_experiment_data(self): notices = [] bench._initialize_container(_Composite(), 'bk', notices) - assert any('missing composite metadata' in n for n in notices), notices - assert any('component_child_index' in n for n in notices) + # The UI notice is short; the metadata key names go to the log. + assert any('container incomplete' in n for n in notices), notices + assert all(len(n) <= 100 for n in notices), notices + assert not any('component_child_index' in n for n in notices) def test_children_allocated_later_is_not_an_error(): diff --git a/tests/test_benchmark_ui.py b/tests/test_benchmark_ui.py index 798cbc0..735e102 100644 --- a/tests/test_benchmark_ui.py +++ b/tests/test_benchmark_ui.py @@ -1071,7 +1071,8 @@ def test_reanalysis_without_a_plan_in_the_record_refuses_clearly(monkeypatch, assert not called, 'must not reanalyse without the original plan' status = ctx.lbl_bench_status.value assert '❌' in status - assert 'cannot be rebuilt' in status, status + assert 'no experiment list saved' in status, status + assert 'rebuild' in status def test_results_found_but_none_attributed_is_never_silent(monkeypatch, @@ -1091,17 +1092,17 @@ def test_results_found_but_none_attributed_is_never_silent(monkeypatch, epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) assert epoch.measured_count == (0, 0) - invariant = [n for n in epoch.notices if '0 attributed to targets' in n] + invariant = [n for n in epoch.notices if 'none matched the targets' in n] assert invariant, f'the invariant notice is missing: {epoch.notices}' - assert '1 results found' in invariant[0], invariant - assert 'edge orientation' in invariant[0] or 'matched' in invariant[0] + assert 'plan/run mismatch' in invariant[0], invariant + assert len(invariant[0]) <= 100, invariant def test_an_empty_plan_is_refused_by_reanalysis(): empty = bench.build_plan(bench.LEVEL_TARGETED, bench.Targets([], []), 8, _line_edges(8)) assert empty.specs == [] - with pytest.raises(bench.BenchmarkRunError, match='no experiments'): + with pytest.raises(bench.BenchmarkRunError, match='Nothing to reanalyse'): bench.reanalyze_from_jobs(empty, ['j'], object(), None) @@ -1450,7 +1451,7 @@ def test_calibration_check_renders_the_verdict_table(monkeypatch, tmp_path): assert 'Calibration check' in table_html assert 'parallel' in table_html and 'sequential' in table_html # Both arms offset the same way -> estimator, not crosstalk. - assert 'estimator mismatch' in table_html, table_html + assert 'Estimator bias' in table_html, table_html # THE INVARIANT: a calibration check measures the instrument. assert getattr(state, '_measured_epoch', None) is None, \ @@ -1636,11 +1637,11 @@ def test_copy_names_in_band_and_rescaled_properties(): measured_count=(156, 352)) line = api['result_sentence'](epoch, stats, {'t2', 'cz_error'}) - assert 'Readout error and T1 differ from' in line, line - assert 'real drift today' in line + assert 'Readout error and T1 look like real drift today' in line, line assert 'T2 and CZ error differ by a constant factor' in line, line assert '(×0.2, ×2.1)' in line, line - assert "shown on IBM's scale with today's ranking preserved" in line + assert "shown on IBM's scale" in line + assert 'README: Relative mode' in line for jargon in ('estimator mismatch', 'RELATIVE', 'systematic offset', '⚠'): assert jargon not in line, f'{jargon!r} leaked into the sentence' diff --git a/tests/test_copy_lengths.py b/tests/test_copy_lengths.py new file mode 100644 index 0000000..bebc487 --- /dev/null +++ b/tests/test_copy_lengths.py @@ -0,0 +1,206 @@ +"""The message diet, enforced. + +The interface says what happened and what to do, in one short sentence; the +README explains why. Without a guard that erodes: an audit found 31 strings of +110-377 characters, tooltips that were paragraphs and notices quoting +`state.edges_list`. These tests walk the real built UI and the module source, +so the limits hold as the code changes rather than only on the day they were +applied. + +Limits (from the copy rules): + tooltips <= 90 + status lines <= 120 + notices <= 100 + section intros <= 2 short sentences + +Anything longer must either be an IBM error passed through verbatim (we do not +edit the provider's words) or be moved to the log. +""" +import ast +import glob +import re + +import numpy as np +import pytest + +TAG = re.compile(r'<[^>]+>') + +#: Files whose user-facing strings are covered. +SOURCES = sorted(glob.glob('iqmapper/ui/*.py')) + [ + 'iqmapper/benchmark.py', 'iqmapper/reservoir.py'] + +#: Passed through from the provider or a library — not ours to shorten. +PASSTHROUGH = ( + 'Real-time benchmarking needs qiskit-experiments', # install hint +) + +TOOLTIP_MAX = 90 +STATUS_MAX = 120 +NOTICE_MAX = 100 + + +def _strip(text): + return re.sub(r'\s+', ' ', TAG.sub('', text)).strip() + + +def _build_ui(monkeypatch): + monkeypatch.setattr( + 'iqmapper.data.generate_device_data', + lambda s, v, c, d, prefetched_props=None: ( + list(range(8)), [0.0] * 8, [(i, i + 1) for i in range(7)], + [str(i) for i in range(8)], + np.array([0.01 * (i + 1) for i in range(8)]), + np.array([0.001 * (i + 1) for i in range(7)]))) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + state = SessionState() + for key, val in dict( + active_backend=object(), active_backend_name='ibm_here', + active_chip='c', active_service=None, available_backends=[], + props_warning=None, initial_props=object(), active_ansatz='lucj', + active_vendor='IBM', active_coords=[], custom_colors=[], + cal_history_dates=['_seed_']).items(): + setattr(state, key, val) + builder = MapperUIBuilder(state) + full_ui, _fig = builder.build() + return builder, full_ui + + +def _widgets(node, seen=None): + if seen is None: + seen = [] + if any(n is node for n in seen): + return seen + seen.append(node) + for child in getattr(node, 'children', ()) or (): + _widgets(child, seen) + return seen + + +# ── the built UI ──────────────────────────────────────────────────── + +def test_every_tooltip_is_one_short_sentence(monkeypatch): + builder, full_ui = _build_ui(monkeypatch) + offenders = [] + for widget in _widgets(full_ui): + tip = getattr(widget, 'tooltip', None) + if not isinstance(tip, str) or not tip: + continue + text = _strip(tip) + if len(text) > TOOLTIP_MAX: + offenders.append( + f'{type(widget).__name__} ({len(text)} chars): {text[:80]}') + assert not offenders, 'tooltips over %d chars:\n %s' % ( + TOOLTIP_MAX, '\n '.join(offenders)) + + +def test_no_tooltip_mentions_an_internal_name(monkeypatch): + """A user who does not read code should not meet `state.edges_list`.""" + builder, full_ui = _build_ui(monkeypatch) + banned = ('state.', 'qiskit-experiments version', 'composite metadata', + 'job phase', '_error', 'edges_list') + offenders = [] + for widget in _widgets(full_ui): + tip = getattr(widget, 'tooltip', None) + if not isinstance(tip, str): + continue + for token in banned: + if token in tip: + offenders.append(f'{token!r} in {tip[:70]!r}') + assert not offenders, offenders + + +def test_widget_descriptions_stay_short(monkeypatch): + builder, full_ui = _build_ui(monkeypatch) + offenders = [ + f'{_strip(w.description)[:70]} ({len(_strip(w.description))})' + for w in _widgets(full_ui) + if isinstance(getattr(w, 'description', None), str) + and len(_strip(w.description)) > 60] + assert not offenders, offenders + + +# ── the source ────────────────────────────────────────────────────── + +def _string_constants(path): + """Non-docstring, non-log string constants, with their line numbers.""" + with open(path, encoding='utf-8') as fh: + tree = ast.parse(fh.read()) + docstrings = set() + for node in ast.walk(tree): + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, + ast.AsyncFunctionDef)): + doc = ast.get_docstring(node, clean=False) + if doc: + docstrings.add(doc) + logged = set() + for node in ast.walk(tree): + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id in ('_log', 'log', 'logger')): + for sub in ast.walk(node): + if isinstance(sub, ast.Constant) and isinstance(sub.value, str): + logged.add(sub.value) + out = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Constant): + continue + if not isinstance(node.value, str) or node.value in docstrings: + continue + if node.value in logged: + continue + out.append((node.lineno, node.value)) + return out + + +def test_no_user_facing_string_is_a_paragraph(): + """The inventory, re-run. Diagnostics belong in the log, not the UI.""" + offenders = [] + for path in SOURCES: + for lineno, raw in _string_constants(path): + text = _strip(raw) + if len(text) <= STATUS_MAX: + continue + if any(p in text for p in PASSTHROUGH): + continue + offenders.append(f'{path}:{lineno} ({len(text)}): {text[:90]}') + assert not offenders, 'strings over %d chars:\n %s' % ( + STATUS_MAX, '\n '.join(offenders)) + + +# ── README anchors ────────────────────────────────────────────────── + +def _readme_anchors(): + headings = set() + with open('README.md', encoding='utf-8') as fh: + for line in fh: + if line.startswith('#'): + headings.add(line.lstrip('#').strip()) + return headings + + +def test_every_readme_pointer_has_a_matching_heading(): + """A dangling `· README: X` is worse than no pointer at all.""" + anchors = _readme_anchors() + pointer = re.compile(r'README:\s*([^\'"<·]+)') + missing = [] + for path in SOURCES: + for lineno, raw in _string_constants(path): + for match in pointer.finditer(raw): + name = match.group(1).strip().rstrip('.') + if name and name not in anchors: + missing.append(f'{path}:{lineno} -> {name!r}') + assert not missing, ( + 'README pointers with no matching heading:\n ' + + '\n '.join(missing) + + f'\nheadings present: {sorted(anchors)}') + + +def test_the_understanding_section_covers_every_anchor_used(): + anchors = _readme_anchors() + assert 'Understanding the messages' in anchors + for name in ('Search cap', 'Diverse enumeration', 'Search engine', + 'Prefer diverse regions', 'Quality floor', 'Levels', + 'Targets', 'Relative mode', 'Calibration check', + 'Delta references', 'Offline mode', 'LQS'): + assert name in anchors, f'README is missing the {name!r} entry' diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py index 8d4259a..929188c 100644 --- a/tests/test_multi_sweep_ui.py +++ b/tests/test_multi_sweep_ui.py @@ -217,7 +217,7 @@ def test_multi_sweep_failed_at(monkeypatch): b.btn_lucj_multi_sweep.click() v = b.lbl_lucj_multi.value - assert 'circuit 2 does not fit' in v + assert "Circuit doesn't fit after C1..C1" in v assert state.layouts_data[0]['ancilla'] == ['4'] # C1 still applied assert len(_dropdowns(b.lucj_multi_detail_box)) == 1 # only the placed one From 63f47584a1d0e824443701cd6ef666aa88290dd3 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 21:46:46 -0400 Subject: [PATCH 39/66] Hybrid search engine: guided below a k threshold, exhaustive above (engine #18) --- iqmapper/engine_select.py | 156 +++++++++++++++++++++++++++++ iqmapper/ui/builder.py | 21 +++- iqmapper/ui/lucj_panel.py | 58 +++++++---- tests/test_auto_panel_ui_polish.py | 72 ++++++++++++- tests/test_engine_select.py | 139 +++++++++++++++++++++++++ tests/test_floor_batch_ui.py | 72 +++++++++++++ 6 files changed, 494 insertions(+), 24 deletions(-) create mode 100644 iqmapper/engine_select.py create mode 100644 tests/test_engine_select.py diff --git a/iqmapper/engine_select.py b/iqmapper/engine_select.py new file mode 100644 index 0000000..b198aae --- /dev/null +++ b/iqmapper/engine_select.py @@ -0,0 +1,156 @@ +""" +engine_select.py — the hybrid search engine: guided below a bridge-count +threshold, exhaustive VF2 above it. + +The two single-circuit engines fail in opposite places. With few bridges (low +k) the LUCJ template is loose, VF2 finds tens of thousands of embeddings on a +large heavy-hex and ranks only what fits under its mapping cap. With many +bridges (high k) the template is tight, the embeddings are few, and VF2 is +genuinely exhaustive — exactly where a beam search can only tie or lose. So +each stratum is taken from the engine that is reliable there: + + k <= guided_max_k → guided_search.guided_sweep + k > guided_max_k → ancilla_sweep.sweep_ancilla_layouts (floor k+1) + +Both halves are the frozen engines, called unchanged; this module only splits +the k range and merges the two result dicts into the shared sweep shape. +""" +import time + +from .ancilla_sweep import sweep_ancilla_layouts +from .auto_lucj import (_make_backend_cmap_pygraph, _remove_nodes_from_graph, + create_lucj_zigzag_layout) +from .guided_search import guided_sweep + + +def _k_range(norb, backend, exclude_qubits, min_bridges): + """(k_max_effective, floor, excluded_sorted), computed as guided_sweep does. + + Same pruned graph, same `min(3, k_max)` default floor and the same + ValueError text, so a bad floor reads identically whichever engine runs. + """ + full_graph = _make_backend_cmap_pygraph(backend=backend) + excluded_sorted = sorted(int(q) for q in exclude_qubits) if exclude_qubits \ + else [] + if excluded_sorted: + for i in full_graph.node_indices(): + full_graph[i] = i + search_graph = _remove_nodes_from_graph(full_graph, + set(excluded_sorted)) + else: + search_graph = full_graph + _template, k_max_effective = create_lucj_zigzag_layout( + num_orbitals=norb, backend_coupling_graph=search_graph, + requested_bridges=-1) + floor = min(3, k_max_effective) if min_bridges is None else min_bridges + if not (1 <= floor <= k_max_effective): + raise ValueError( + f"min_bridges={floor} out of range; must satisfy " + f"1 <= min_bridges <= k_max_effective ({k_max_effective}).") + return k_max_effective, floor, excluded_sorted + + +def _tagged(per_stratum, ks, engine): + """Copies of `per_stratum[k]` for k in `ks`, each tagged with its engine.""" + out = {} + for k in ks: + meta = dict(per_stratum.get(k, {})) + meta['engine'] = engine + out[k] = meta + return out + + +def hybrid_sweep(norb, backend, props, *, guided_max_k, min_bridges=None, + top_n=3, exclude_qubits=None, circuit_score_fn=None, + diversity_threshold=None, vf2_kwargs=None, + guided_kwargs=None) -> dict: + """Guided search for strata `k <= guided_max_k`, VF2 for the rest. + + Args: + norb, backend, props, min_bridges, top_n, exclude_qubits, + circuit_score_fn, diversity_threshold: as for both engines, and + passed to both. + guided_max_k: highest bridge count taken from the guided engine. + Below the floor → pure VF2; at or above `k_max_effective` → pure + guided. Required: `None` raises ValueError, the caller picks the + threshold (see `evaluation.suggest_guided_max_k`). + vf2_kwargs: extra keyword arguments for VF2 only (`hybrid`, + `mapping_cap`, `shuffle_seed`, `diverse_cap`). + guided_kwargs: extra keyword arguments for guided only (`beam_width`, + `refine_top`, `qubit_weight`, `max_iter`, `seed`). + + `guided_sweep` has no upper-k parameter, so it runs from the floor to + `k_max_effective` and its strata above `guided_max_k` are discarded. That + is wasted work (one beam per discarded stratum), cheap next to the VF2 + half, and the price of leaving the frozen engine untouched. The guided + strata are therefore exactly what `guided_sweep` alone would return, + anchored on its own higher strata rather than on the VF2 winners. + + Returns the shared sweep dict shape (strata k-descending), plus + `engine='hybrid'`, `guided_max_k`, and `per_stratum[k]['engine']` set to + `'guided'` or `'vf2'`. Run-level fields come from the half that owns them: + `vf2_truncated`, `reservoir`, `reservoir_notices` and `mapping_cap` from + VF2; `refined_count`, `refine_attempted`, `beam_width` and `expansions` + from guided; counts and `elapsed_s` are summed. + """ + if guided_max_k is None: + raise ValueError("guided_max_k is required for the hybrid engine.") + started = time.time() + k_max_effective, floor, excluded_sorted = _k_range( + norb, backend, exclude_qubits, min_bridges) + + shared = dict(top_n=top_n, exclude_qubits=exclude_qubits, + circuit_score_fn=circuit_score_fn, + diversity_threshold=diversity_threshold) + vf2_res = guided_res = None + + if guided_max_k < k_max_effective: + vf2_floor = min_bridges if guided_max_k < floor else guided_max_k + 1 + vf2_res = sweep_ancilla_layouts(norb, backend, props, + min_bridges=vf2_floor, + **shared, **(vf2_kwargs or {})) + if guided_max_k >= floor: + guided_res = guided_sweep(norb, backend, props, + min_bridges=min_bridges, + **shared, **(guided_kwargs or {})) + + strata, per_stratum = {}, {} + if vf2_res is not None: + vf2_ks = sorted(vf2_res['strata'], reverse=True) + strata.update((k, vf2_res['strata'][k]) for k in vf2_ks) + per_stratum.update(_tagged(vf2_res['per_stratum'], vf2_ks, 'vf2')) + if guided_res is not None: + guided_ks = sorted((k for k in guided_res['strata'] + if k <= guided_max_k), reverse=True) + strata.update((k, guided_res['strata'][k]) for k in guided_ks) + per_stratum.update(_tagged(guided_res['per_stratum'], guided_ks, + 'guided')) + strata = {k: strata[k] for k in sorted(strata, reverse=True)} + per_stratum = {k: per_stratum[k] for k in sorted(per_stratum, + reverse=True)} + + def _sum(key): + return sum((r or {}).get(key) or 0 for r in (vf2_res, guided_res)) + + vf2 = vf2_res or {} + guided = guided_res or {} + return { + 'strata': strata, + 'reservoir': vf2.get('reservoir', {}), + 'reservoir_notices': list(vf2.get('reservoir_notices', [])), + 'k_max_effective': k_max_effective, + 'min_bridges': floor, + 'vf2_truncated': bool(vf2.get('vf2_truncated', False)), + 'n_raw_embeddings': _sum('n_raw_embeddings'), + 'n_candidates_scored': _sum('n_candidates_scored'), + 'excluded_qubits': excluded_sorted, + 'per_stratum': per_stratum, + 'mapping_cap': vf2.get('mapping_cap'), + 'engine': 'hybrid', + 'guided_max_k': guided_max_k, + 'beam_width': guided.get('beam_width'), + 'refined_count': guided.get('refined_count', 0), + 'refine_attempted': guided.get('refine_attempted', 0), + 'expansions': guided.get('expansions', 0), + 'elapsed_s': time.time() - started, + } diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index d074515..eb416e8 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -328,6 +328,7 @@ def _run_pipeline(self): dd_search_engine=self.dd_search_engine, int_beam_width=self.int_beam_width, int_refine_top=self.int_refine_top, + int_guided_max_k=self.int_guided_max_k, guided_params_box=self.bench_guided_box, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, @@ -1465,16 +1466,25 @@ def _build_auto_lucj_widgets(self, W): # Default stays Exhaustive (VF2) until iqmapper.evaluation says the # guided beam wins on real cached calibration — see the harness. self.dd_search_engine = Dropdown( - options=[('Exhaustive (VF2)', 'vf2'), ('Guided (beam)', 'guided')], + options=[('Exhaustive (VF2)', 'vf2'), ('Guided (beam)', 'guided'), + ('Hybrid', 'hybrid')], value='vf2', description='Search engine:', layout=Layout(width='280px'), style={'description_width': '110px'}, - tooltip='Exhaustive = VF2 (calibration-blind); Guided = ' - 'calibration-led beam search · README: Search engine') + tooltip='Exhaustive = VF2; Guided = calibration-led beam; ' + 'Hybrid = both, split by k · README: Search engine') + # Own Layout: display is toggled at runtime (Hybrid only). + self.int_guided_max_k = BoundedIntText( + value=1, min=0, max=50, + description='Guided up to k:', + layout=Layout(width='220px', display='none'), + style={'description_width': '110px'}, + tooltip='ancilla counts up to this use Guided, above it ' + 'Exhaustive · README: Search engine') _guided_layout = Layout(width=W.width, margin=W.margin, min_width=W.min_width) - _guided_layout.display = 'none' # shown only for Guided + _guided_layout.display = 'none' # shown for Guided and Hybrid self.bench_guided_box = VBox([], layout=_guided_layout) self.int_beam_width = BoundedIntText( value=200, min=10, max=5000, step=50, @@ -1497,7 +1507,8 @@ def _build_auto_lucj_widgets(self, W): self.lucj_advanced_acc = Accordion( children=[VBox([self.lucj_search_cap, self.chk_deep_search, self.chk_diverse_cap, - self.dd_search_engine, self.bench_guided_box])], + self.dd_search_engine, self.int_guided_max_k, + self.bench_guided_box])], layout=W) self.lucj_advanced_acc.set_title(0, '⚙️ Advanced') self.lucj_advanced_acc.selected_index = None # collapsed on open diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 19b55c5..765dec0 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -194,6 +194,7 @@ def setup_lucj_callbacks(ctx): dd_search_engine = getattr(ctx, 'dd_search_engine', None) int_beam_width = getattr(ctx, 'int_beam_width', None) int_refine_top = getattr(ctx, 'int_refine_top', None) + int_guided_max_k = getattr(ctx, 'int_guided_max_k', None) guided_params_box = getattr(ctx, 'guided_params_box', None) btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status @@ -479,7 +480,7 @@ def _sweep_kwargs_from_ui(): # ── ONE dispatch point for the search engine ───────────────── def _selected_engine(): - """'vf2' (default) or 'guided'. Absent widget → the frozen default.""" + """'vf2' (default), 'guided' or 'hybrid'. Absent widget → 'vf2'.""" return getattr(dd_search_engine, 'value', 'vf2') or 'vf2' def _guided_params(): @@ -488,25 +489,36 @@ def _guided_params(): 'refine_top': int(getattr(int_refine_top, 'value', 5) or 5), } + _VF2_ONLY = ('hybrid', 'mapping_cap', 'shuffle_seed', 'diverse_cap') + def _run_sweep(norb, backend, props, **kwargs): """Run the selected search engine. - Both engines return the same dict shape, so every caller below and all + All engines return the same dict shape, so every caller below and all the display code downstream is engine-agnostic. `hybrid` and `mapping_cap` are VF2-only concepts (the beam is bounded by construction and never truncates), so they are dropped for guided - rather than passed and ignored. + rather than passed and ignored; the hybrid engine routes them to its + VF2 half only. """ - if _selected_engine() != 'guided': + engine = _selected_engine() + if engine not in ('guided', 'hybrid'): from ..ancilla_sweep import sweep_ancilla_layouts return sweep_ancilla_layouts(norb, backend, props, **kwargs) + shared = {k: v for k, v in kwargs.items() if k not in _VF2_ONLY} + if engine == 'hybrid': + from ..engine_select import hybrid_sweep + vf2_kwargs = {k: v for k, v in kwargs.items() if k in _VF2_ONLY} + return hybrid_sweep( + norb, backend, props, + guided_max_k=int(getattr(int_guided_max_k, 'value', 1)), + vf2_kwargs=vf2_kwargs, guided_kwargs=_guided_params(), + **shared) + from ..guided_search import guided_sweep - guided_kwargs = {k: v for k, v in kwargs.items() - if k not in ('hybrid', 'mapping_cap', - 'shuffle_seed', 'diverse_cap')} - guided_kwargs.update(_guided_params()) - return guided_sweep(norb, backend, props, **guided_kwargs) + shared.update(_guided_params()) + return guided_sweep(norb, backend, props, **shared) def _reservoir_suffix(res): """The per-stratum cap notice, when a cap was actually reached.""" @@ -517,19 +529,27 @@ def _reservoir_suffix(res): def _engine_suffix(res): """Status-line tail naming the engine, and the refinement tally.""" - if not isinstance(res, dict) or res.get('engine') != 'guided': + engine = res.get('engine') if isinstance(res, dict) else None + if engine == 'guided': + name = "guided" + elif engine == 'hybrid': + name = f"hybrid (guided ≤ k{res.get('guided_max_k')})" + else: return "" attempted = res.get('refine_attempted') or 0 refined = res.get('refined_count') or 0 - return (f" · engine: guided · refined {refined}/{attempted}" - if attempted else " · engine: guided") + return (f" · engine: {name} · refined {refined}/{attempted}" + if attempted else f" · engine: {name}") def _on_engine_change(_change=None): - """Guided-only params are hidden while Exhaustive is selected.""" - if guided_params_box is None: - return - guided_params_box.layout.display = ( - '' if _selected_engine() == 'guided' else 'none') + """Beam params show for Guided and Hybrid; the threshold for Hybrid.""" + engine = _selected_engine() + if guided_params_box is not None: + guided_params_box.layout.display = ( + '' if engine in ('guided', 'hybrid') else 'none') + if int_guided_max_k is not None: + int_guided_max_k.layout.display = ( + '' if engine == 'hybrid' else 'none') if dd_search_engine is not None: dd_search_engine.observe(_on_engine_change, names='value') @@ -2013,7 +2033,9 @@ def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): min_bridges=min_bridges_list, top_n=kwargs['top_n'], mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], diversity_threshold=kwargs['diversity_threshold'], - circuit_score_fn=_circuit_score, exclude_qubits=excl) + # THIS backend's calibration, as in the single-circuit scan. + circuit_score_fn=_scan_circuit_score(props), + exclude_qubits=excl) # Give scan_qpus a rankable 'strata' surface: the batch metric. metric, _ = _batch_metric(res) res['strata'] = {0: [{'product_score': metric}]} diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 0bd2b4c..9007f8a 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -236,7 +236,8 @@ def test_engine_selector_defaults_to_exhaustive(monkeypatch): """Guided stays opt-in until iqmapper.evaluation says otherwise.""" b, _ = _build(monkeypatch) assert b.dd_search_engine.value == 'vf2' - assert [v for _label, v in b.dd_search_engine.options] == ['vf2', 'guided'] + assert [v for _label, v in b.dd_search_engine.options] == [ + 'vf2', 'guided', 'hybrid'] # Guided-only params are hidden while Exhaustive is selected. assert b.bench_guided_box.layout.display == 'none' assert b.int_beam_width.value == 200 @@ -351,6 +352,75 @@ def _spy(norb, backend, props, **kwargs): assert 'refined 2/5' in status, status +def test_hybrid_shows_the_threshold_and_the_beam_params(monkeypatch): + b, _ = _build(monkeypatch) + assert b.int_guided_max_k.value == 1 and b.int_guided_max_k.min == 0 + assert b.int_guided_max_k.layout.display == 'none' + # Toggled at runtime, so it must not share the builder-wide layout. + assert b.int_guided_max_k.layout is not b.txt_auto.layout + assert b.int_guided_max_k.layout is not b.bench_guided_box.layout + assert any(w is b.int_guided_max_k + for w in _descendants(b.lucj_advanced_acc)) + + b.dd_search_engine.value = 'hybrid' + assert b.int_guided_max_k.layout.display == '' + assert b.bench_guided_box.layout.display == '' + b.dd_search_engine.value = 'guided' + assert b.int_guided_max_k.layout.display == 'none' + assert b.bench_guided_box.layout.display == '' + b.dd_search_engine.value = 'vf2' + assert b.int_guided_max_k.layout.display == 'none' + assert b.txt_auto.layout.display != 'none' + + +def test_selecting_hybrid_routes_the_sweep_to_hybrid_sweep(monkeypatch): + b, _ = _build(monkeypatch) + seen = {} + + def _spy(norb, backend, props, **kwargs): + seen['kwargs'] = kwargs + return dict(_empty_sweep(), engine='hybrid', guided_max_k=2, + refined_count=0, refine_attempted=0) + + monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', _spy) + b.dd_search_engine.value = 'hybrid' + b.int_guided_max_k.value = 2 + b.int_beam_width.value = 64 + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + + kw = seen['kwargs'] + assert kw['guided_max_k'] == 2 + assert kw['guided_kwargs']['beam_width'] == 64 + # VF2-only knobs reach the VF2 half only. + assert {'hybrid', 'mapping_cap', 'diverse_cap'} <= set(kw['vf2_kwargs']) + for key in ('hybrid', 'mapping_cap', 'diverse_cap'): + assert key not in kw + assert 'top_n' in kw and 'circuit_score_fn' in kw + + +def test_status_line_names_the_hybrid_threshold(monkeypatch): + b, _ = _build(monkeypatch) + entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4], 'bridge_slots': (0,), + 'product_score': 0.9, 'additive_score': 0.1, + 'lqs_circuit': 0.8, 'rank_in_stratum': 1, 'source': 'guided'} + res = dict(_empty_sweep(), strata={1: [entry]}, + per_stratum={1: {'n_direct': 1, 'n_derived': 0, + 'truncated': False, 'shuffled': False, + 'engine': 'guided'}}, + engine='hybrid', guided_max_k=1, refined_count=1, + refine_attempted=3, reservoir_notices=[]) + monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', + lambda *a, **k: res) + b.dd_search_engine.value = 'hybrid' + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + status = b.lbl_lucj_status.value + assert 'engine: hybrid (guided ≤ k1)' in status, status + assert 'refined 1/3' in status, status + + # ── t8: diverse enumeration ──────────────────────────────────────────────── def test_diverse_enumeration_checkbox_defaults_on(monkeypatch): diff --git a/tests/test_engine_select.py b/tests/test_engine_select.py new file mode 100644 index 0000000..be060e7 --- /dev/null +++ b/tests/test_engine_select.py @@ -0,0 +1,139 @@ +"""Tests for the hybrid engine (guided below a k threshold, VF2 above). + +Offline and deterministic. The edge cases must reduce to the frozen engines +exactly; the split case must be the two engines' own strata, side by side. +""" +import random +from types import SimpleNamespace + +import pytest +import rustworkx + +from iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.engine_select import hybrid_sweep +from iqmapper.guided_search import guided_sweep + +from test_ancilla_sweep import FakeProps, make_backend + + +def heavy_hex_backend(d=5, seed=3): + """heavy_hex_graph(d) as a backend, with seeded random calibrations.""" + graph = rustworkx.generators.heavy_hex_graph(d) + directed = rustworkx.PyDiGraph() + for _ in range(graph.num_nodes()): + directed.add_node(None) + for u, v in graph.edge_list(): + directed.add_edge(u, v, None) + directed.add_edge(v, u, None) + rng = random.Random(seed) + readout = {q: rng.uniform(0.002, 0.04) for q in range(graph.num_nodes())} + gate = {frozenset(e): rng.uniform(0.001, 0.02) for e in graph.edge_list()} + + class _Props: + def readout_error(self, q): + return readout[q] + + def gate_error(self, name, edge): + return gate[frozenset(edge)] + + backend = SimpleNamespace(coupling_map=SimpleNamespace(graph=directed), + operation_names=['cz', 'sx', 'rz', 'x'], + name=f'heavy_hex_{d}') + return backend, _Props() + + +def _score(entry): + return entry['product_score'] + + +def _untagged(per_stratum): + return {k: {f: v for f, v in m.items() if f != 'engine'} + for k, m in per_stratum.items()} + + +@pytest.fixture(scope='module') +def split_case(): + """norb=9 on heavy_hex(5): k_max=3, VF2 capped at k=1.""" + backend, props = heavy_hex_backend() + kw = dict(min_bridges=1, top_n=3, circuit_score_fn=_score) + hyb = hybrid_sweep(9, backend, props, guided_max_k=1, **kw) + guided = guided_sweep(9, backend, props, **kw) + vf2 = sweep_ancilla_layouts(9, backend, props, **dict(kw, min_bridges=2)) + return hyb, guided, vf2 + + +def test_pure_vf2_when_threshold_is_below_the_floor(): + backend, props = make_backend(), FakeProps() + kw = dict(min_bridges=2, top_n=3, circuit_score_fn=_score) + hyb = hybrid_sweep(8, backend, props, guided_max_k=1, **kw) + ref = sweep_ancilla_layouts(8, backend, props, **kw) + assert hyb['strata'] == ref['strata'] + assert _untagged(hyb['per_stratum']) == ref['per_stratum'] + assert {m['engine'] for m in hyb['per_stratum'].values()} == {'vf2'} + assert hyb['refined_count'] == 0 and hyb['refine_attempted'] == 0 + + +def test_pure_guided_when_threshold_reaches_k_max(): + backend, props = make_backend(), FakeProps() + kw = dict(min_bridges=1, top_n=3, circuit_score_fn=_score) + ref = guided_sweep(8, backend, props, **kw) + hyb = hybrid_sweep(8, backend, props, guided_max_k=ref['k_max_effective'], + **kw) + assert hyb['strata'] == ref['strata'] + assert _untagged(hyb['per_stratum']) == ref['per_stratum'] + assert {m['engine'] for m in hyb['per_stratum'].values()} == {'guided'} + assert hyb['vf2_truncated'] is False and hyb['reservoir_notices'] == [] + assert hyb['mapping_cap'] is None + + +def test_split_takes_each_stratum_from_its_engine(split_case): + hyb, guided, vf2 = split_case + assert hyb['k_max_effective'] >= 3 + assert list(hyb['strata']) == sorted(hyb['strata'], reverse=True) + for k, entries in hyb['strata'].items(): + engine = hyb['per_stratum'][k]['engine'] + if k <= 1: + assert engine == 'guided' + assert entries == guided['strata'][k] + else: + assert engine == 'vf2' + assert entries == vf2['strata'][k] + assert set(hyb['strata']) == set(range(hyb['k_max_effective'], 0, -1)) + assert hyb['vf2_truncated'] == vf2['vf2_truncated'] + assert hyb['reservoir_notices'] == vf2['reservoir_notices'] + assert hyb['refined_count'] == guided['refined_count'] + assert hyb['n_raw_embeddings'] == (vf2['n_raw_embeddings'] + + guided['n_raw_embeddings']) + assert hyb['min_bridges'] == 1 and hyb['guided_max_k'] == 1 + assert hyb['engine'] == 'hybrid' + + +def test_result_carries_every_vf2_key(split_case): + hyb, _guided, vf2 = split_case + assert set(vf2) <= set(hyb) + + +def test_exclusions_reach_both_halves(): + backend, props = heavy_hex_backend() + excluded = {0, 1, 2, 3, 20, 21, 40, 41, 60, 61} + res = hybrid_sweep(9, backend, props, guided_max_k=1, min_bridges=1, + exclude_qubits=excluded) + engines = {m['engine'] for m in res['per_stratum'].values()} + assert engines == {'guided', 'vf2'} + assert res['excluded_qubits'] == sorted(excluded) + for entries in res['strata'].values(): + for e in entries: + used = set(e['alpha']) | set(e['beta']) | set(e['ancillas']) + assert used.isdisjoint(excluded) + + +def test_threshold_is_required(): + backend, props = make_backend(), FakeProps() + with pytest.raises(ValueError, match='guided_max_k'): + hybrid_sweep(8, backend, props, guided_max_k=None) + + +def test_out_of_range_floor_raises_the_engine_text(): + backend, props = make_backend(), FakeProps() + with pytest.raises(ValueError, match='min_bridges=9 out of range'): + hybrid_sweep(8, backend, props, guided_max_k=1, min_bridges=9) diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index 99ec8b9..eef1445 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -277,3 +277,75 @@ def test_batch_selector_handoff_payload(monkeypatch): assert name == 'ibm_hi' assert isinstance(payload, list) and len(payload) == 2 # both circuits assert payload[0]['ancillas'] == [4] and payload[1]['ancillas'] == [5] + + +# ── batch scan scores each backend on ITS OWN calibration ─────────────── + +def _ladder_backend(name): + """Two disjoint width-8 ladder blocks (48 qubits), as in test_multi_sweep.""" + import rustworkx + edges = [] + for base in (0, 24): + top = [base + j for j in range(8)] + bot = [base + 8 + j for j in range(8)] + brg = [base + 16 + j for j in range(8)] + for j in range(7): + edges += [(top[j], top[j + 1]), (bot[j], bot[j + 1])] + for j in range(8): + edges += [(top[j], brg[j]), (brg[j], bot[j])] + graph = rustworkx.PyDiGraph() + for i in range(48): + graph.add_node(i) + for u, v in edges: + graph.add_edge(u, v, None) + return SimpleNamespace(name=name, coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +def test_batch_scan_scores_each_backend_with_its_own_props(monkeypatch): + """Same qubit indices, different gate errors: each backend's batch metric + must come from that backend's props, not from the active backend's.""" + from iqmapper import qpu_scan as qs + from iqmapper.props_shim import CachedPropsShim + b, state = _build(monkeypatch) + backends = {n: _ladder_backend(n) for n in ('ibm_a', 'ibm_b')} + gate_err = {'ibm_a': 0.002, 'ibm_b': 0.03} + shims = {} + + def _get_props(backend): + edges = list(backend.coupling_map.graph.edge_list()) + shim = CachedPropsShim( + {'readout_error': np.array([0.01] * 48)}, + {'cz_error': np.array([gate_err[backend.name]] * len(edges))}, + edges, n_qubits=48, vintage='live') + shims[backend.name] = shim + return shim + + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", + lambda state: _get_props) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in backends]) + state.active_service = SimpleNamespace(backend=lambda n: backends[n]) + b.lucj_multi_norbs.value = '4, 4' + captured = {} + real_scan = qs.scan_qpus + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: captured.setdefault( + 'res', real_scan(*a, **k))) + b.btn_scan_batch.click() + + rows = {r['name']: r for r in captured['res']['results']} + metrics = {} + for name, row in rows.items(): + sweep = row['sweep'] + assert sweep['failed_at'] is None and len(sweep['circuits']) == 2 + expect = 1.0 + for c in sweep['circuits']: + ch = c['chosen'] + qubits = list(ch['alpha']) + list(ch['beta']) + list(ch['ancillas']) + own = shims[name].score_layout(qubits)['fidelity'] + assert ch['lqs_circuit'] == own + expect *= own + assert sweep['total_lqs_circuit'] == expect + metrics[name] = sweep['total_lqs_circuit'] + assert metrics['ibm_a'] > metrics['ibm_b'] From 0d3df0a905b97460ff99131571ab3496e761d8f9 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 22:04:16 -0400 Subject: [PATCH 40/66] Joint multi-circuit planner: beam over placement plans, never worse than sequential (engine #19) --- README.md | 5 + iqmapper/joint_plan.py | 345 +++++++++++++++++++++++++++++++++++ iqmapper/ui/builder.py | 42 +++++ iqmapper/ui/lucj_panel.py | 116 +++++++++++- tests/test_joint_plan.py | 347 ++++++++++++++++++++++++++++++++++++ tests/test_joint_plan_ui.py | 273 ++++++++++++++++++++++++++++ 6 files changed, 1119 insertions(+), 9 deletions(-) create mode 100644 iqmapper/joint_plan.py create mode 100644 tests/test_joint_plan.py create mode 100644 tests/test_joint_plan_ui.py diff --git a/README.md b/README.md index d1cc7b5..32a97d9 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,11 @@ grows each layout using the calibration as it goes and polishes the finalists. Guided is a heuristic: it can miss the best layout that exhaustive would find, so it stays opt-in until the comparison harness says otherwise. +### Multi-circuit planner + +**Sequential** places circuits one at a time, each on the best region left. +**Joint** keeps several partial plans and returns the best complete one. + ### Prefer diverse regions The top half of each candidate list is always the best-scoring layouts. The diff --git a/iqmapper/joint_plan.py b/iqmapper/joint_plan.py new file mode 100644 index 0000000..44a60c1 --- /dev/null +++ b/iqmapper/joint_plan.py @@ -0,0 +1,345 @@ +""" +joint_plan.py — joint multi-circuit planner: a beam over placement plans. + +`multi_sweep` places circuits greedily: circuit 0 takes the best region on the +chip, circuit 1 takes the best of what is left, and so on. That is myopic. The +best region for circuit 0 can sit where its footprint plus buffer cuts the chip +into pieces too small for circuit 1, which is then pushed onto a poor region +while two good regions existed side by side. + +This module keeps several partial plans alive instead of one. Circuits are +still placed in the given order. A plan is the entries chosen so far plus the +exclusion set they imply; at each circuit every surviving plan is searched on +the chip minus its own exclusions, extended with its top `branch` candidates, +and the best `beam_width` plans survive. `beam_width = branch = 1` is exactly +the sequential greedy. + +The single-circuit search is injected (`search_fn`), so the planner runs on +whichever engine the caller selected — VF2, guided or hybrid. Exclusion and +buffer semantics are `auto_lucj._exclude_with_buffer`, applied as +`multi_sweep._orchestrate` applies them, and every circuit record is built by +`multi_sweep._circuit_record`, so the result has the `sweep_multi_circuits` +shape and every multi-circuit display path works unchanged. + + +PLAN SCORE +---------- + prod(metric_i) * (1 - boundary_penalty) ** n_boundary + +`metric_i` is the circuit's displayed metric, chosen as `multi_sweep._best_entry` +chooses it: `lqs_circuit` when the circuit's search returned any, otherwise +`product_score`. `n_boundary` counts physical couplers whose two endpoints +belong to two different circuits. With `buffer_qubits >= 1` that count is zero +by construction (every neighbour of a placed qubit is excluded). At buffer 0 a +gate can sit on the boundary between two active circuits — spectator crosstalk +the LQS does not model — and the penalty is the knob that prices it. + + +GUARANTEES +---------- +* Never worse than sequential: the greedy plan is computed through the same + code path and the better of the two is returned (`plan_source` says which). +* Fit failures never raise: a circuit that fits in no surviving plan stops the + run, and the best partial plan is returned with `failed_at` set. +* Deterministic: candidate order follows the search result, pruning ties break + on candidate rank, and final ties on the sorted qubit tuples. +""" +import logging + +from .ancilla_sweep import sweep_ancilla_layouts +from .auto_lucj import _exclude_with_buffer, _make_backend_cmap_pygraph +from .multi_sweep import _circuit_record, _entry_qubits, _per_circuit + +_log = logging.getLogger(__name__) + +DEFAULT_BEAM_WIDTH = 4 +DEFAULT_BRANCH = 3 + + +def worst_case_searches(n_circuits, beam_width): + """Upper bound on single-circuit searches for one joint run. + + The beam searches once per surviving plan per circuit: 1 for circuit 0, + at most `beam_width` for each later one. The greedy comparison plan shares + those searches except when its prefix has dropped out of the beam, which + can cost one extra search for each circuit from index 2 on. + """ + if n_circuits <= 0: + return 0 + return 1 + beam_width * (n_circuits - 1) + max(0, n_circuits - 2) + + +def ranked_candidates(res): + """All entries of a sweep result, best first, by the displayed metric. + + Same rule as `multi_sweep._best_entry(res, True)`: `lqs_circuit` when any + entry carries one (entries without it drop out), else `product_score`. + The sort is stable over strata order, so element 0 is `_best_entry`'s pick + even on ties. Returns `(entries, key)`. + """ + entries = [e for group in res.get('strata', {}).values() for e in group] + scored = [e for e in entries if e.get('lqs_circuit') is not None] + if scored: + return sorted(scored, key=lambda e: -e['lqs_circuit']), 'lqs_circuit' + return sorted(entries, key=lambda e: -e['product_score']), 'product_score' + + +def _metric(entry, key): + value = entry.get(key) + return entry['product_score'] if value is None else value + + +class _Plan: + """A partial placement: one record per placed circuit, plus its footprint.""" + + __slots__ = ('records', 'metrics', 'qsets', 'remaining', 'excluded', + 'placed', 'buffers', 'boundary', 'path') + + def __init__(self, remaining, excluded): + self.records = () + self.metrics = () + self.qsets = () + self.remaining = remaining + self.excluded = frozenset(excluded) + self.placed = () + self.buffers = () + self.boundary = () + self.path = () + + def extend(self, record, metric, buffer_qubits, adjacency, rank): + chosen_full = _entry_qubits(record['chosen']) + qset = frozenset(chosen_full) + new_boundary = [] + for q in sorted(qset): + for other in self.qsets: + for n in adjacency.get(q, ()): + if n in other: + new_boundary.append((min(q, n), max(q, n))) + remaining, new_excl = _exclude_with_buffer( + self.remaining, set(chosen_full), buffer_qubits) + child = _Plan(remaining, self.excluded | new_excl) + child.records = self.records + (record,) + child.metrics = self.metrics + (metric,) + child.qsets = self.qsets + (qset,) + child.placed = self.placed + tuple(chosen_full) + child.buffers = self.buffers + tuple(sorted(new_excl - qset)) + child.boundary = tuple(sorted(set(self.boundary) | set(new_boundary))) + child.path = self.path + (rank,) + return child + + def score(self, penalty): + if not self.records: + return None + total = 1.0 + for m in self.metrics: + total *= m + return total * (1.0 - penalty) ** len(self.boundary) + + def qkey(self): + return tuple(tuple(sorted(s)) for s in self.qsets) + + +def _final_key(plan, penalty): + """Sort key, best first: more circuits, higher score, then qubit tuples.""" + score = plan.score(penalty) + return (-len(plan.records), -(score if score is not None else 0.0), + plan.qkey()) + + +def _beam(ctx, prefix, beam_width, branch): + """Run the beam from a fixed prefix. Returns (best_plan, failed_at).""" + norbs = ctx['norbs'] + penalty = ctx['boundary_penalty'] + buffer_qubits = ctx['buffer_qubits'] + adjacency = ctx['_adjacency'] + + root = _Plan(ctx['_root_remaining'], ctx['_stability']) + for i, (rec, chosen) in enumerate(prefix): + rec = dict(rec) + rec['chosen'] = chosen + _entries, key = ranked_candidates(rec) + root = root.extend(rec, _metric(chosen, key), buffer_qubits, + adjacency, 0) + + beam = [root] + failed_at = None + for i in range(len(prefix), len(norbs)): + children = {} + for plan in beam: + res = _search(ctx, i, plan.excluded) + if res is None: + continue + entries, key = ranked_candidates(res) + for rank, entry in enumerate(entries[:branch]): + rec = _circuit_record(i, norbs[i], res, entry) + child = plan.extend(rec, _metric(entry, key), buffer_qubits, + adjacency, rank) + dedupe = child.qsets + held = children.get(dedupe) + if held is None or (-child.score(penalty), child.path) < ( + -held.score(penalty), held.path): + children[dedupe] = child + if not children: + failed_at = i + break + beam = sorted(children.values(), + key=lambda p: (-p.score(penalty), p.path))[:beam_width] + best = min(beam, key=lambda p: _final_key(p, penalty)) + return best, failed_at + + +def _search(ctx, i, excluded): + """Memoised single-circuit search. None when the circuit does not fit.""" + norb_i = ctx['norbs'][i] + mb = _per_circuit(ctx['min_bridges'], i) + key = (norb_i, mb, frozenset(excluded)) + cache = ctx['_cache'] + if key in cache: + return cache[key] + ctx['_calls'][0] += 1 + try: + res = ctx['search_fn'](norb_i, exclude_qubits=(set(excluded) or None), + min_bridges=mb) + except Exception as exc: + _log.info("Joint plan: circuit %d (norb=%d) did not fit: %s", + i, norb_i, exc) + res = None + if res is not None and not ranked_candidates(res)[0]: + res = None + cache[key] = res + return res + + +def _result(ctx, plan, failed_at, greedy_plan, plan_source, n_searches): + penalty = ctx['boundary_penalty'] + chosen_list = [r['chosen'] for r in plan.records] + total_product = None + if chosen_list: + total_product = 1.0 + for c in chosen_list: + total_product *= c['product_score'] + total_lqs = None + if chosen_list and all(c.get('lqs_circuit') is not None + for c in chosen_list): + total_lqs = 1.0 + for c in chosen_list: + total_lqs *= c['lqs_circuit'] + return { + 'circuits': list(plan.records), + 'total_product': total_product, + 'total_lqs_circuit': total_lqs, + 'placed_qubits': list(plan.placed), + 'buffer_qubits_used': list(plan.buffers), + 'failed_at': failed_at, + 'planner': 'joint', + 'beam_width': ctx['beam_width'], + 'branch': ctx['branch'], + 'boundary_penalty': penalty, + 'boundary_couplers': [tuple(e) for e in plan.boundary], + 'greedy_total': greedy_plan.score(penalty), + 'greedy_placed': len(greedy_plan.records), + 'joint_total': plan.score(penalty), + 'plan_source': plan_source, + 'n_searches': n_searches, + '_context': ctx, + } + + +def _run(ctx, prefix): + calls_before = ctx['_calls'][0] + greedy, greedy_failed = _beam(ctx, prefix, 1, 1) + joint, joint_failed = _beam(ctx, prefix, ctx['beam_width'], ctx['branch']) + penalty = ctx['boundary_penalty'] + if _final_key(greedy, penalty) < _final_key(joint, penalty): + plan, failed_at, source = greedy, greedy_failed, 'greedy' + else: + plan, failed_at, source = joint, joint_failed, 'beam' + return _result(ctx, plan, failed_at, greedy, source, + ctx['_calls'][0] - calls_before) + + +def plan_multi_circuits(norbs, backend, props, *, search_fn=None, + beam_width=DEFAULT_BEAM_WIDTH, branch=DEFAULT_BRANCH, + buffer_qubits=1, exclude_qubits=None, + min_bridges=None, top_n=3, circuit_score_fn=None, + boundary_penalty=0.0) -> dict: + """Place `len(norbs)` LUCJ circuits on one backend, planning jointly. + + Args: + norbs: spatial-orbital counts, one per circuit, in placement order. + backend, props: as for `ancilla_sweep.sweep_ancilla_layouts`. + search_fn: ``callable(norb, *, exclude_qubits, min_bridges) -> sweep + result dict``. Default: VF2 (`sweep_ancilla_layouts`) with + `top_n` and `circuit_score_fn`, the same call `multi_sweep` + makes. Pass a closure to plan on another engine. + beam_width: plans kept after each circuit (B). + branch: candidates per circuit each plan is extended with (M). + buffer_qubits: idle coupling-graph hops kept clear between circuits. + exclude_qubits: physical ids barred from every circuit. + min_bridges: global floor or a per-circuit list. + top_n, circuit_score_fn: used only by the default `search_fn`. + boundary_penalty: in [0, 1); each coupler shared by two circuits + multiplies the plan score by `1 - boundary_penalty`. 0 = off. + + Returns the `multi_sweep.sweep_multi_circuits` keys, plus `planner`, + `beam_width`, `branch`, `boundary_penalty`, `boundary_couplers`, + `greedy_total` and `joint_total` (plan scores, penalty included; + `joint_total` is the returned plan's), `greedy_placed` (circuits the + greedy plan placed — when the joint plan places more, its score is a + product of more factors and the two totals are not comparable), + `plan_source` ('beam' | 'greedy'), and `n_searches` (actual `search_fn` + calls after memoisation). + """ + if not (0.0 <= boundary_penalty < 1.0): + raise ValueError(f"boundary_penalty={boundary_penalty} must be in " + f"[0, 1).") + if beam_width < 1 or branch < 1: + raise ValueError("beam_width and branch must both be >= 1.") + if search_fn is None: + def search_fn(norb, *, exclude_qubits, min_bridges): + return sweep_ancilla_layouts( + norb, backend, props, exclude_qubits=exclude_qubits, + min_bridges=min_bridges, top_n=top_n, + circuit_score_fn=circuit_score_fn) + + # Physical-id-tagged coupling graph for buffer expansion, pruned of the + # stability exclusions first (buffer 0), exactly as _orchestrate does. + remaining = _make_backend_cmap_pygraph(backend=backend) + for idx in remaining.node_indices(): + remaining[idx] = idx + adjacency = {} + for u, v in remaining.edge_list(): + adjacency.setdefault(u, set()).add(v) + adjacency.setdefault(v, set()).add(u) + stability = set(int(q) for q in (exclude_qubits or [])) + if stability: + remaining, _ = _exclude_with_buffer(remaining, stability, 0) + + ctx = { + 'norbs': list(norbs), 'backend': backend, 'props': props, + 'search_fn': search_fn, 'beam_width': beam_width, 'branch': branch, + 'buffer_qubits': buffer_qubits, 'exclude_qubits': exclude_qubits, + 'min_bridges': min_bridges, 'top_n': top_n, + 'circuit_score_fn': circuit_score_fn, + 'boundary_penalty': boundary_penalty, + '_root_remaining': remaining, '_stability': frozenset(stability), + '_adjacency': adjacency, '_cache': {}, '_calls': [0], + } + return _run(ctx, []) + + +def replan_from(result, index, new_choice): + """Fix circuits `< index` and `new_choice` at `index`; plan the rest. + + Same contract as `multi_sweep.replan_from`: pure, reads the `_context` the + result carries (searches already made are reused from its memo), returns a + fresh result of the same shape. + """ + ctx = result['_context'] + circuits = result['circuits'] + if not (0 <= index < len(circuits)): + raise IndexError(f"replan index {index} out of range " + f"(have {len(circuits)} placed circuits)") + prefix = [(circuits[i], circuits[i]['chosen']) for i in range(index)] + prefix.append((circuits[index], new_choice)) + return _run(ctx, prefix) diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index eb416e8..23878f9 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -336,6 +336,10 @@ def _run_pipeline(self): dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, + dd_planner=self.dd_planner, int_plans_kept=self.int_plans_kept, + int_cands_per_circuit=self.int_cands_per_circuit, + ft_boundary_penalty=self.ft_boundary_penalty, + joint_params_box=self.joint_params_box, lucj_multi_ancillas=self.lucj_multi_ancillas, btn_lucj_multi=self.btn_lucj_multi, btn_lucj_multi_sweep=self.btn_lucj_multi_sweep, @@ -1607,6 +1611,42 @@ def _build_auto_lucj_widgets(self, W): description='Buffer qubits:', layout=Layout(width='220px'), style={'description_width': '110px'}) + # ── Multi-circuit planner ───────────────────────────────── + # Default Sequential = the greedy multi_sweep, unchanged. Each widget + # owns its Layout: the Joint-only box is toggled at runtime. + self.dd_planner = Dropdown( + options=[('Sequential', 'sequential'), ('Joint', 'joint')], + value='sequential', + description='Planner:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='Sequential = best region per circuit in turn; Joint = ' + 'plan all together · README: Multi-circuit planner') + self.int_plans_kept = BoundedIntText( + value=4, min=1, max=50, + description='Plans kept:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='partial plans kept after each circuit ' + '· README: Multi-circuit planner') + self.int_cands_per_circuit = BoundedIntText( + value=3, min=1, max=50, + description='Candidates per circuit:', + layout=Layout(width='220px'), + style={'description_width': '150px'}, + tooltip='layouts each plan tries for the next circuit ' + '· README: Multi-circuit planner') + self.ft_boundary_penalty = BoundedFloatText( + value=0.0, min=0.0, max=0.95, step=0.05, + description='Boundary penalty:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='cost per coupler shared by two circuits; matters only ' + 'at buffer 0 · README: Multi-circuit planner') + self.joint_params_box = VBox( + [self.int_plans_kept, self.int_cands_per_circuit, + self.ft_boundary_penalty], + layout=Layout(display='none')) # Legacy multi-circuit button — no longer shown in the Multi subpanel # (the sweep is the single generate action). The widget + its handler # (_on_lucj_multi) and engine (get_multi_circuit_layouts) stay wired and @@ -2065,6 +2105,8 @@ def _build_auto_lucj_view(self): self.lucj_multi_norbs, self.lucj_multi_ancillas, self.lucj_buffer_slider, + self.dd_planner, + self.joint_params_box, # Legacy btn_lucj_multi intentionally omitted — the sweep button is # the single generate action. Handler/engine remain wired + pinned. self.btn_lucj_multi_sweep, diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 765dec0..250947d 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -206,6 +206,11 @@ def setup_lucj_callbacks(ctx): lucj_multi_norbs = ctx.lucj_multi_norbs lucj_multi_ancillas = ctx.lucj_multi_ancillas lucj_buffer_slider = ctx.lucj_buffer_slider + dd_planner = getattr(ctx, 'dd_planner', None) + int_plans_kept = getattr(ctx, 'int_plans_kept', None) + int_cands_per_circuit = getattr(ctx, 'int_cands_per_circuit', None) + ft_boundary_penalty = getattr(ctx, 'ft_boundary_penalty', None) + joint_params_box = getattr(ctx, 'joint_params_box', None) btn_lucj_multi = ctx.btn_lucj_multi btn_lucj_multi_sweep = ctx.btn_lucj_multi_sweep btn_scan_batch = ctx.btn_scan_batch @@ -555,6 +560,94 @@ def _on_engine_change(_change=None): dd_search_engine.observe(_on_engine_change, names='value') _on_engine_change() + # ── ONE dispatch point for the multi-circuit planner ───────── + def _selected_planner(): + """'sequential' (default) or 'joint'. Absent widget → 'sequential'.""" + return getattr(dd_planner, 'value', 'sequential') or 'sequential' + + def _joint_params(): + return { + 'beam_width': int(getattr(int_plans_kept, 'value', 4) or 4), + 'branch': int(getattr(int_cands_per_circuit, 'value', 3) or 3), + 'boundary_penalty': float( + getattr(ft_boundary_penalty, 'value', 0.0) or 0.0), + } + + def _run_multi(norbs, backend, props, *, sweep_kwargs, **seq_kwargs): + """Place several circuits with the selected planner. + + Sequential passes `seq_kwargs` to `multi_sweep.sweep_multi_circuits` + untouched, so each call site keeps its exact call. Joint plans with + `joint_plan.plan_multi_circuits`, searching each circuit through + `_run_sweep` with `sweep_kwargs`, so the selected engine is used. + """ + if _selected_planner() != 'joint': + from ..multi_sweep import sweep_multi_circuits + return sweep_multi_circuits(norbs, backend, props, **seq_kwargs) + + from ..joint_plan import plan_multi_circuits + scorer = seq_kwargs.get('circuit_score_fn') + base = {k: v for k, v in sweep_kwargs.items() if k != 'min_bridges'} + + def _search(norb, *, exclude_qubits, min_bridges): + return _run_sweep(norb, backend, props, circuit_score_fn=scorer, + exclude_qubits=exclude_qubits, + min_bridges=min_bridges, **base) + + return plan_multi_circuits( + norbs, backend, props, search_fn=_search, + buffer_qubits=seq_kwargs.get('buffer_qubits', 1), + exclude_qubits=seq_kwargs.get('exclude_qubits'), + min_bridges=seq_kwargs.get('min_bridges'), + top_n=seq_kwargs.get('top_n', 3), circuit_score_fn=scorer, + **_joint_params()) + + def _replan_multi(result, index, new_choice): + """Replan with the planner that produced `result`.""" + if result.get('planner') == 'joint': + from ..joint_plan import replan_from + else: + from ..multi_sweep import replan_from + return replan_from(result, index, new_choice) + + def _joint_pending_html(n_circuits): + """'running…' line for a joint run: the worst-case search count.""" + from ..joint_plan import worst_case_searches + n = worst_case_searches(n_circuits, _joint_params()['beam_width']) + return (f"
" + f"⏳ joint plan · up to {n} searches
") + + def _joint_status_html(result): + """Gain over sequential and search count; shared couplers if any.""" + if result.get('planner') != 'joint': + return "" + greedy, joint = result.get('greedy_total'), result.get('joint_total') + placed = len(result.get('circuits') or []) + greedy_placed = result.get('greedy_placed', placed) + if placed > greedy_placed: + gain = f"places {placed} vs {greedy_placed} sequential" + elif greedy and joint is not None: + gain = f"+{(joint / greedy - 1.0) * 100.0:.1f}% vs sequential" + else: + gain = "no plan" + line = (f"
joint plan · {gain} · " + f"{result.get('n_searches', 0)} searches") + shared = result.get('boundary_couplers') or [] + if shared: + line += ("
shared couplers: " + + ", ".join(f"{u}–{v}" for u, v in shared)) + return line + + def _on_planner_change(_change=None): + """Joint-only params are hidden while Sequential is selected.""" + if joint_params_box is not None: + joint_params_box.layout.display = ( + '' if _selected_planner() == 'joint' else 'none') + + if dd_planner is not None: + dd_planner.observe(_on_planner_change, names='value') + _on_planner_change() + # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the # active backend's reference in the scan table, so the scan never # re-searches self yet keeps the reference point. @@ -1821,7 +1914,8 @@ def _render_multi_sweep_output(result): f"padding:8px 10px;border-radius:5px;border:1px solid #abebc6;" f"margin:4px 0;line-height:1.7;'>🧺 " f"{len(result['circuits'])} circuit(s) placed " - f"(buffer={lucj_buffer_slider.value})
{summary}" + f"(buffer={lucj_buffer_slider.value})
{summary}" + f"{_joint_status_html(result)}" + _multi_failed_banner(result)) _build_multi_override_dropdowns(result) @@ -1835,9 +1929,8 @@ def _on_multi_override(i, choice): _multi_override_disabled(True) def _work(): - from ..multi_sweep import replan_from with _capture_qpu_notices(lambda: f'replan C{i + 1}') as handler: - new_result = replan_from(result, i, choice) + new_result = _replan_multi(result, i, choice) return (new_result, list(handler.records)) def _done(payload): @@ -1879,7 +1972,8 @@ def _on_lucj_multi_sweep(b): btn_lucj_multi_sweep.disabled = True btn_lucj_multi_sweep.description = '⏳ Sweeping...' - lbl_lucj_multi.value = "" + lbl_lucj_multi.value = (_joint_pending_html(len(norbs)) + if _selected_planner() == 'joint' else "") lbl_lucj_multi_notices.value = "" kwargs = _sweep_kwargs_from_ui() excl = _multi_stability_exclusions() @@ -1891,10 +1985,10 @@ def _reset_btn(): btn_lucj_multi_sweep.description = '🧺 Generate Multi-Circuit' def _work(): - from ..multi_sweep import sweep_multi_circuits with _capture_qpu_notices(lambda: 'multi sweep') as handler: - result = sweep_multi_circuits( + result = _run_multi( norbs, state.active_backend, scoring_props, + sweep_kwargs=kwargs, min_bridges=min_bridges_list, top_n=kwargs['top_n'], buffer_qubits=buffer, exclude_qubits=excl, mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], @@ -2022,14 +2116,16 @@ def _on_scan_batch(b): btn_scan_batch.disabled = True btn_scan_batch.description = '⏳ Scanning batch...' scan_batch_box.children = [] + if _selected_planner() == 'joint': + lbl_lucj_multi.value = _joint_pending_html(len(norbs)) kwargs = _sweep_kwargs_from_ui() buffer = lucj_buffer_slider.value def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): - from ..multi_sweep import sweep_multi_circuits excl = _batch_backend_exclusions(props, getattr(backend, 'name', None)) - res = sweep_multi_circuits( - norbs, backend, props, buffer_qubits=buffer, + res = _run_multi( + norbs, backend, props, sweep_kwargs=kwargs, + buffer_qubits=buffer, min_bridges=min_bridges_list, top_n=kwargs['top_n'], mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], diversity_threshold=kwargs['diversity_threshold'], @@ -2044,6 +2140,8 @@ def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): def _reset(): btn_scan_batch.disabled = False btn_scan_batch.description = '🌐 Scan batch on all QPUs' + if _selected_planner() == 'joint': + lbl_lucj_multi.value = "" # drop the pending line def _work(): from .. import qpu_scan diff --git a/tests/test_joint_plan.py b/tests/test_joint_plan.py new file mode 100644 index 0000000..323cc28 --- /dev/null +++ b/tests/test_joint_plan.py @@ -0,0 +1,347 @@ +"""Tests for the joint multi-circuit planner (beam over placement plans). + +Offline, deterministic. Hosts: + * the two-block ladder of test_multi_sweep — the greedy-equivalence check; + * hand-built line graphs, where nine consecutive qubits hold exactly one + norb=4 layout (a3-a2-a1-a0-r-b0-b1-b2-b3), so regions are easy to reason + about; + * heavy_hex_graph(5) with seeded calibrations. +""" +from types import SimpleNamespace + +import pytest +import rustworkx + +from iqmapper import multi_sweep +from iqmapper.engine_select import hybrid_sweep +from iqmapper.joint_plan import (plan_multi_circuits, ranked_candidates, + replan_from, worst_case_searches) +from iqmapper.multi_sweep import _best_entry, sweep_multi_circuits + +from test_engine_select import heavy_hex_backend +from test_multi_sweep import _Props, _make_backend + + +# ── hosts ─────────────────────────────────────────────────────────── + +def _lines(lengths): + """Disjoint line graphs, ids allocated in order. Returns (backend, spans).""" + edges, spans, base = [], [], 0 + for length in lengths: + edges += [(base + i, base + i + 1) for i in range(length - 1)] + spans.append(range(base, base + length)) + base += length + graph = rustworkx.PyDiGraph() + for i in range(base): + graph.add_node(i) + for u, v in edges: + graph.add_edge(u, v, None) + backend = SimpleNamespace(coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x'], + name='lines') + return backend, spans + + +class _ErrProps: + """Per-qubit error; a gate takes the worse of its two qubits.""" + + def __init__(self, err): + self.err = err + + def readout_error(self, q): + return self.err[q] + + def gate_error(self, name, edge): + return max(self.err[edge[0]], self.err[edge[1]]) + + +def _myopia_host(): + """X: 17-qubit line, excellent in its middle 9 — the only place norb=8 + fits well. W: a separate, very good 9-qubit line. Y: a bad 17-qubit line. + + Greedy puts the norb=4 circuit on X's middle (its single best layout), + which leaves norb=8 only Y. The joint plan puts norb=4 on W and norb=8 on X. + """ + backend, (x, w, y) = _lines([17, 9, 17]) + err = {q: (0.001 if 4 <= q - x[0] <= 12 else 0.02) for q in x} + err.update({q: 0.0015 for q in w}) + err.update({q: 0.1 for q in y}) + return backend, _ErrProps(err), (set(x), set(w), set(y)) + + +def _adjacent_host(): + """A: an 18-qubit line that holds two norb=4 circuits only back to back + (sharing coupler 8-9). Z: a separate, slightly worse 9-qubit line.""" + backend, (a, z) = _lines([18, 9]) + err = {q: 0.005 + 0.0001 * q for q in a} + err.update({q: 0.02 for q in z}) + return backend, _ErrProps(err), (set(a), set(z)) + + +def _qubits(entry): + return set(entry['alpha']) | set(entry['beta']) | set(entry['ancillas']) + + +def _adjacency(backend): + adj = {} + for u, v in backend.coupling_map.graph.edge_list(): + adj.setdefault(u, set()).add(v) + adj.setdefault(v, set()).add(u) + return adj + + +def _strip(res): + return {k: v for k, v in res.items() if k != '_context'} + + +# ── 1. greedy equivalence ─────────────────────────────────────────── + +@pytest.mark.parametrize('norbs,kw', [ + ([8, 8], dict(buffer_qubits=1)), + ([8, 8], dict(buffer_qubits=0)), + ([8, 6], dict(buffer_qubits=1, min_bridges=[2, 1])), + ([8, 8], dict(buffer_qubits=1, + circuit_score_fn=lambda e: e['product_score'] ** 2)), + ([8, 8, 8], dict(buffer_qubits=1)), # third does not fit + ([8, 8], dict(buffer_qubits=1, exclude_qubits={0, 30})), +]) +def test_beam_one_branch_one_is_the_sequential_greedy(norbs, kw): + backend, props = _make_backend(), _Props() + seq = sweep_multi_circuits(norbs, backend, props, **kw) + joint = plan_multi_circuits(norbs, backend, props, beam_width=1, + branch=1, **kw) + assert ([c['chosen'] for c in joint['circuits']] + == [c['chosen'] for c in seq['circuits']]) + for key in ('placed_qubits', 'buffer_qubits_used', 'total_product', + 'total_lqs_circuit', 'failed_at'): + assert joint[key] == seq[key], key + assert joint['circuits'] == seq['circuits'] + assert joint['greedy_total'] == joint['joint_total'] + + +def test_candidate_order_matches_best_entry(): + backend, props = _make_backend(), _Props() + from iqmapper.ancilla_sweep import sweep_ancilla_layouts + plain = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=5) + scored = sweep_ancilla_layouts(8, backend, props, min_bridges=1, top_n=5, + circuit_score_fn=lambda e: 0.5) # all tie + for res, has_scorer in ((plain, False), (plain, True), (scored, True)): + ranked, _key = ranked_candidates(res) + assert ranked[0] is _best_entry(res, has_scorer) + + +# ── 2. the myopia case ────────────────────────────────────────────── + +def test_joint_beats_greedy_when_greedy_is_myopic(): + backend, props, (x, w, y) = _myopia_host() + seq = sweep_multi_circuits([4, 8], backend, props) + res = plan_multi_circuits([4, 8], backend, props) + assert _qubits(seq['circuits'][1]['chosen']) <= y # greedy's trap + assert res['greedy_total'] == pytest.approx(seq['total_product']) + assert res['joint_total'] > res['greedy_total'] + assert res['plan_source'] == 'beam' + assert _qubits(res['circuits'][0]['chosen']) <= w + assert _qubits(res['circuits'][1]['chosen']) <= x + assert res['total_product'] == pytest.approx(res['joint_total']) + + +# ── 3. never worse than greedy ────────────────────────────────────── + +@pytest.mark.parametrize('seed', range(10)) +def test_never_worse_than_greedy_on_random_calibrations(seed): + # Three circuits on 57 qubits with floor 1: tight enough that the plans + # differ (on several seeds joint scores higher, on one it fits a circuit + # greedy cannot), so this is not a tie-only check. + backend, props = heavy_hex_backend(5, seed=seed) + norbs = [5, 5, 5] + seq = sweep_multi_circuits(norbs, backend, props, min_bridges=1) + res = plan_multi_circuits(norbs, backend, props, min_bridges=1) + assert res['greedy_total'] == pytest.approx(seq['total_product']) + assert res['greedy_placed'] == len(seq['circuits']) + assert len(res['circuits']) >= res['greedy_placed'] + if len(res['circuits']) == res['greedy_placed']: + assert res['joint_total'] >= res['greedy_total'] + + +def test_joint_can_fit_a_circuit_greedy_cannot(): + backend, props = heavy_hex_backend(5, seed=6) + norbs = [5, 5, 5] + seq = sweep_multi_circuits(norbs, backend, props, min_bridges=1) + res = plan_multi_circuits(norbs, backend, props, min_bridges=1) + assert seq['failed_at'] == 2 and res['greedy_placed'] == 2 + assert res['failed_at'] is None and len(res['circuits']) == 3 + assert res['plan_source'] == 'beam' + + +# ── 4. boundary couplers ──────────────────────────────────────────── + +def test_no_boundary_couplers_with_a_buffer(): + backend, props = heavy_hex_backend(5, seed=1) + res = plan_multi_circuits([5, 5, 5], backend, props, buffer_qubits=1) + assert res['boundary_couplers'] == [] + + +def test_boundary_couplers_reported_and_priced_at_buffer_zero(): + backend, props, (a, z) = _adjacent_host() + off = plan_multi_circuits([4, 4], backend, props, buffer_qubits=0) + assert off['boundary_couplers'] == [(8, 9)] + assert all(_qubits(c['chosen']) <= a for c in off['circuits']) + + on = plan_multi_circuits([4, 4], backend, props, buffer_qubits=0, + boundary_penalty=0.5) + assert on['boundary_couplers'] == [] + used = [_qubits(c['chosen']) for c in on['circuits']] + assert any(u <= z for u in used) and any(u <= a for u in used) + # The greedy pair is the adjacent one, priced by the penalty. + assert on['greedy_total'] == pytest.approx(off['joint_total'] * 0.5) + assert on['joint_total'] > on['greedy_total'] + + +@pytest.mark.parametrize('bad', [-0.1, 1.0]) +def test_penalty_outside_its_range_is_refused(bad): + backend, props = _make_backend(), _Props() + with pytest.raises(ValueError, match='boundary_penalty'): + plan_multi_circuits([8], backend, props, boundary_penalty=bad) + + +# ── 5. no overlap, exclusions respected ───────────────────────────── + +@pytest.mark.parametrize('buffer_qubits', [0, 1, 2]) +def test_no_overlap_and_every_exclusion_holds(buffer_qubits): + backend, props = heavy_hex_backend(5, seed=4) + stability = {7, 8, 9, 30, 31, 50} + res = plan_multi_circuits([5, 5, 5], backend, props, + buffer_qubits=buffer_qubits, + exclude_qubits=stability) + adj = _adjacency(backend) + claimed = set() + for c in res['circuits']: + used = _qubits(c['chosen']) + assert used.isdisjoint(stability) + assert used.isdisjoint(claimed) # no overlap, no buffer reuse + ring = set(used) + for _hop in range(buffer_qubits): + ring |= {n for q in ring for n in adj.get(q, ())} + claimed |= ring + assert set(res['buffer_qubits_used']).isdisjoint(res['placed_qubits']) + + +# ── 6. fit failure ────────────────────────────────────────────────── + +def test_more_circuits_than_the_chip_holds_stops_cleanly(): + backend, props = _make_backend(), _Props() + res = plan_multi_circuits([8, 8, 8, 8], backend, props) + assert res['failed_at'] == 2 + assert len(res['circuits']) == 2 + + +def test_nothing_fits_returns_an_empty_plan(): + backend, props = _lines([5])[0], _ErrProps({q: 0.01 for q in range(5)}) + res = plan_multi_circuits([4], backend, props) + assert res['failed_at'] == 0 and res['circuits'] == [] + assert res['greedy_total'] is None and res['joint_total'] is None + + +# ── 7. memoisation ────────────────────────────────────────────────── + +def test_searches_are_memoised(): + backend, props = heavy_hex_backend(5, seed=2) + calls = [] + + def _counting(norb, *, exclude_qubits, min_bridges): + calls.append((norb, frozenset(exclude_qubits or ()), min_bridges)) + from iqmapper.ancilla_sweep import sweep_ancilla_layouts + return sweep_ancilla_layouts(norb, backend, props, top_n=3, + exclude_qubits=exclude_qubits, + min_bridges=min_bridges) + + norbs, beam, branch = [5, 5, 5], 4, 3 + res = plan_multi_circuits(norbs, backend, props, search_fn=_counting, + beam_width=beam, branch=branch) + assert res['n_searches'] == len(calls) + assert len(set(calls)) == len(calls) # never searched twice + assert res['n_searches'] <= worst_case_searches(len(norbs), beam) + assert res['n_searches'] < beam * branch * len(norbs) + + +def test_worst_case_search_count(): + assert worst_case_searches(0, 4) == 0 + assert worst_case_searches(1, 4) == 1 + assert worst_case_searches(2, 4) == 5 + assert worst_case_searches(3, 4) == 10 + + +# ── 8. replan ─────────────────────────────────────────────────────── + +def test_replan_keeps_the_new_choice_and_replans_the_rest(): + backend, props, (x, w, y) = _myopia_host() + res = plan_multi_circuits([4, 8], backend, props) + ranked, _key = ranked_candidates(res['circuits'][0]) + alt = next(e for e in ranked if e is not res['circuits'][0]['chosen']) + new = replan_from(res, 0, alt) + assert new['circuits'][0]['chosen'] is alt + first = _qubits(alt) + ring = first | {n for q in first for n in _adjacency(backend).get(q, ())} + assert _qubits(new['circuits'][1]['chosen']).isdisjoint(ring) + assert set(new) == set(res) + + +def test_replan_index_out_of_range(): + backend, props = _make_backend(), _Props() + res = plan_multi_circuits([8, 8], backend, props) + with pytest.raises(IndexError, match=r'replan index 5 out of range ' + r'\(have 2 placed circuits\)'): + replan_from(res, 5, res['circuits'][0]['chosen']) + seq = sweep_multi_circuits([8, 8], backend, props) + with pytest.raises(IndexError) as seq_err: + multi_sweep.replan_from(seq, 5, seq['circuits'][0]['chosen']) + with pytest.raises(IndexError) as joint_err: + replan_from(res, 5, res['circuits'][0]['chosen']) + assert str(seq_err.value) == str(joint_err.value) + + +# ── 9. engine pass-through ────────────────────────────────────────── + +def test_a_hybrid_search_fn_runs_end_to_end(): + backend, props = heavy_hex_backend(5, seed=6) + + def _hybrid(norb, *, exclude_qubits, min_bridges): + return hybrid_sweep(norb, backend, props, guided_max_k=1, + min_bridges=min_bridges, + exclude_qubits=exclude_qubits, + circuit_score_fn=lambda e: e['product_score']) + + res = plan_multi_circuits([5, 5], backend, props, search_fn=_hybrid, + min_bridges=1) + assert res['failed_at'] is None and len(res['circuits']) == 2 + engines = {m['engine'] for c in res['circuits'] + for m in c['per_stratum'].values()} + assert engines == {'guided', 'vf2'} + assert res['total_lqs_circuit'] is not None + + +# ── 10. determinism ───────────────────────────────────────────────── + +def test_identical_calls_give_identical_results(): + backend, props = heavy_hex_backend(5, seed=8) + a = plan_multi_circuits([5, 5], backend, props, buffer_qubits=0, + boundary_penalty=0.2) + b = plan_multi_circuits([5, 5], backend, props, buffer_qubits=0, + boundary_penalty=0.2) + assert _strip(a) == _strip(b) + + +# ── result shape ──────────────────────────────────────────────────── + +def test_result_carries_every_sequential_key(): + backend, props = _make_backend(), _Props() + seq = sweep_multi_circuits([8, 8], backend, props) + res = plan_multi_circuits([8, 8], backend, props) + assert set(seq) <= set(res) + assert res['planner'] == 'joint' + for key in ('beam_width', 'branch', 'boundary_penalty', + 'boundary_couplers', 'greedy_total', 'joint_total', + 'plan_source', 'n_searches'): + assert key in res + assert set(res['circuits'][0]) == set(seq['circuits'][0]) + diff --git a/tests/test_joint_plan_ui.py b/tests/test_joint_plan_ui.py new file mode 100644 index 0000000..3d4aa5a --- /dev/null +++ b/tests/test_joint_plan_ui.py @@ -0,0 +1,273 @@ +"""The Planner selector: Sequential (default, unchanged) vs Joint. + +Headless, offline. Planner engines are monkeypatched with canned results +except in the batch-scan test, which runs the real joint planner on two stub +backends to prove the per-backend scorer survives the dispatch. +""" +import numpy as np +import pytest + +from test_multi_sweep_ui import _build, _dropdowns, _patch_engine, _result + +SEQ_MULTI_KWARGS = {'min_bridges', 'top_n', 'buffer_qubits', 'exclude_qubits', + 'mapping_cap', 'hybrid', 'diversity_threshold', + 'circuit_score_fn'} + + +def _joint(result, **extra): + res = dict(result, planner='joint', beam_width=4, branch=3, + boundary_penalty=0.0, boundary_couplers=[], greedy_total=0.30, + joint_total=0.3574, greedy_placed=len(result['circuits']), + plan_source='beam', n_searches=7) + res.update(extra) + return res + + +def _patch_joint(monkeypatch, result): + import iqmapper.joint_plan as jp + seen = {} + + def _spy(norbs, backend, props, **kwargs): + seen.update(norbs=norbs, kwargs=kwargs) + return result + + monkeypatch.setattr(jp, 'plan_multi_circuits', _spy) + return seen + + +# ── widgets ───────────────────────────────────────────────────────── + +def test_planner_defaults_to_sequential_with_joint_params_hidden(monkeypatch): + b, _ = _build(monkeypatch) + assert b.dd_planner.value == 'sequential' + assert [v for _l, v in b.dd_planner.options] == ['sequential', 'joint'] + assert b.int_plans_kept.value == 4 + assert b.int_cands_per_circuit.value == 3 + assert b.ft_boundary_penalty.value == 0.0 + assert b.joint_params_box.layout.display == 'none' + b.intra_qpu_mode.value = True + b._build_auto_lucj_view() + for w in (b.dd_planner, b.joint_params_box): + assert any(c is w for c in b._auto_multi_panel.children) + + +def test_planner_widgets_own_their_layouts(monkeypatch): + b, _ = _build(monkeypatch) + widgets = (b.dd_planner, b.joint_params_box, b.int_plans_kept, + b.int_cands_per_circuit, b.ft_boundary_penalty) + for w in widgets: + assert w.layout is not b.txt_auto.layout + assert w.layout is not b.lucj_buffer_slider.layout + layouts = [w.layout for w in widgets] + assert len({id(lay) for lay in layouts}) == len(layouts) + + +def test_joint_reveals_its_params(monkeypatch): + b, _ = _build(monkeypatch) + b.dd_planner.value = 'joint' + assert b.joint_params_box.layout.display == '' + assert b.txt_auto.layout.display != 'none' + b.dd_planner.value = 'sequential' + assert b.joint_params_box.layout.display == 'none' + + +# ── sequential is the call it always was ──────────────────────────── + +def test_sequential_makes_the_same_call_as_before(monkeypatch): + b, state = _build(monkeypatch) + result, _ = _result() + seen = _patch_engine(monkeypatch, result) + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + assert set(seen['sweep_kwargs']) == SEQ_MULTI_KWARGS + assert seen['sweep_args'][0] == [8, 8] + assert seen['sweep_args'][1] is state.active_backend + assert 'joint plan' not in b.lbl_lucj_multi.value + + +def test_sequential_replan_still_uses_multi_sweep(monkeypatch): + import iqmapper.multi_sweep as ms + b, _ = _build(monkeypatch) + result, alt = _result() + _patch_engine(monkeypatch, result) + called = [] + monkeypatch.setattr(ms, 'replan_from', + lambda r, i, c: called.append((i, c)) or result) + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + _dropdowns(b.lucj_multi_detail_box)[0].value = 1 + assert called and called[0][1] is alt + + +# ── joint ─────────────────────────────────────────────────────────── + +def test_joint_dispatches_with_its_params_and_reports_the_gain(monkeypatch): + b, _ = _build(monkeypatch) + result, _ = _result() + seen = _patch_joint(monkeypatch, _joint(result)) + _patch_engine(monkeypatch, None) # must not be called + b.dd_planner.value = 'joint' + b.int_plans_kept.value = 6 + b.int_cands_per_circuit.value = 2 + b.ft_boundary_penalty.value = 0.25 + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + kw = seen['kwargs'] + assert (kw['beam_width'], kw['branch'], kw['boundary_penalty']) == ( + 6, 2, 0.25) + assert callable(kw['search_fn']) and callable(kw['circuit_score_fn']) + status = b.lbl_lucj_multi.value + assert 'joint plan · +19.1% vs sequential · 7 searches' in status, status + assert 'shared couplers' not in status + assert 'C1: k=1 · 61.2%' in status # the usual summary stays + + +def test_joint_that_places_more_circuits_says_so(monkeypatch): + b, _ = _build(monkeypatch) + result, _ = _result() + _patch_joint(monkeypatch, _joint(result, greedy_placed=1, + greedy_total=0.9)) + b.dd_planner.value = 'joint' + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + status = b.lbl_lucj_multi.value + assert 'joint plan · places 2 vs 1 sequential · 7 searches' in status + assert '%' not in status.split('joint plan')[1] + + +def test_joint_names_shared_couplers(monkeypatch): + b, _ = _build(monkeypatch) + result, _ = _result() + _patch_joint(monkeypatch, _joint(result, boundary_couplers=[(47, 48)])) + b.dd_planner.value = 'joint' + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + assert 'shared couplers: 47–48' in b.lbl_lucj_multi.value + + +def test_joint_search_fn_honours_the_selected_engine(monkeypatch): + b, _ = _build(monkeypatch) + result, _ = _result() + seen = _patch_joint(monkeypatch, _joint(result)) + b.dd_planner.value = 'joint' + b.dd_search_engine.value = 'hybrid' + b.int_guided_max_k.value = 2 + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + hybrid_calls = [] + monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', + lambda norb, backend, props, **k: + hybrid_calls.append((norb, k)) or {'strata': {}}) + seen['kwargs']['search_fn'](8, exclude_qubits={3}, min_bridges=1) + norb, k = hybrid_calls[0] + assert norb == 8 and k['guided_max_k'] == 2 + assert k['exclude_qubits'] == {3} and k['min_bridges'] == 1 + assert 'mapping_cap' in k['vf2_kwargs'] + + +def test_joint_pending_line_shows_the_worst_case_count(monkeypatch): + queued = [] + b, _ = _build(monkeypatch, spawn=lambda fn, on_done=None, on_error=None: + queued.append(fn)) + b.dd_planner.value = 'joint' + b.int_plans_kept.value = 4 + b.lucj_multi_norbs.value = '8, 8, 8' + b.btn_lucj_multi_sweep.click() + assert queued, 'the run was not started' + assert 'joint plan · up to 10 searches' in b.lbl_lucj_multi.value + + +def test_joint_replan_uses_the_joint_planner(monkeypatch): + import iqmapper.joint_plan as jp + import iqmapper.multi_sweep as ms + b, _ = _build(monkeypatch) + result, alt = _result() + joint = _joint(result) + _patch_joint(monkeypatch, joint) + called = [] + monkeypatch.setattr(jp, 'replan_from', + lambda r, i, c: called.append((r, i, c)) or joint) + monkeypatch.setattr(ms, 'replan_from', lambda *a: pytest.fail( + 'sequential replan used for a joint result')) + b.dd_planner.value = 'joint' + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + _dropdowns(b.lucj_multi_detail_box)[0].value = 1 + assert called and called[0][0] is joint and called[0][2] is alt + + +# ── batch scan ────────────────────────────────────────────────────── + +def test_batch_sequential_call_is_unchanged(monkeypatch): + from types import SimpleNamespace + from test_floor_batch_ui import _build as _build_batch + from iqmapper import multi_sweep as ms + from iqmapper import qpu_scan as qs + b, _ = _build_batch(monkeypatch) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: SimpleNamespace( + _readout=np.array([0.01] * 16), n_qubits=16, + vintage='live', + score_layout=lambda q: {'fidelity': 0.5}))) + seen = {} + monkeypatch.setattr(ms, 'sweep_multi_circuits', + lambda *a, **k: seen.update(kwargs=k) or { + 'circuits': [], 'total_product': None, + 'total_lqs_circuit': None, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': 0, + '_context': {}}) + b.lucj_multi_norbs.value = '8, 6' + b.btn_scan_batch.click() + assert set(seen['kwargs']) == SEQ_MULTI_KWARGS + + +def test_batch_joint_scores_each_backend_with_its_own_props(monkeypatch): + """Joint batch: real planner, per-backend scorer, through the helper.""" + from types import SimpleNamespace + from test_floor_batch_ui import _build as _build_batch, _ladder_backend + from iqmapper import qpu_scan as qs + from iqmapper.props_shim import CachedPropsShim + b, state = _build_batch(monkeypatch) + backends = {n: _ladder_backend(n) for n in ('ibm_a', 'ibm_b')} + gate_err = {'ibm_a': 0.002, 'ibm_b': 0.03} + shims = {} + + def _get_props(backend): + edges = list(backend.coupling_map.graph.edge_list()) + shim = CachedPropsShim( + {'readout_error': np.array([0.01] * 48)}, + {'cz_error': np.array([gate_err[backend.name]] * len(edges))}, + edges, n_qubits=48, vintage='live') + shims[backend.name] = shim + return shim + + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", + lambda state: _get_props) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in backends]) + state.active_service = SimpleNamespace(backend=lambda n: backends[n]) + captured = {} + real_scan = qs.scan_qpus + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: captured.setdefault( + 'res', real_scan(*a, **k))) + b.dd_planner.value = 'joint' + b.lucj_multi_norbs.value = '4, 4' + b.btn_scan_batch.click() + + for row in captured['res']['results']: + sweep = row['sweep'] + assert sweep['planner'] == 'joint' and sweep['failed_at'] is None + expect = 1.0 + for c in sweep['circuits']: + ch = c['chosen'] + qubits = list(ch['alpha']) + list(ch['beta']) + list(ch['ancillas']) + own = shims[row['name']].score_layout(qubits)['fidelity'] + assert ch['lqs_circuit'] == own + expect *= own + assert sweep['total_lqs_circuit'] == expect + assert 'joint plan · up to' not in b.lbl_lucj_multi.value From 73456862b063a16608750dafd7fc49d36178d8c1 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 22:37:34 -0400 Subject: [PATCH 41/66] Docs: hybrid engine, joint planner, CODE_OVERVIEW update; docstring cleanup (comments only) --- CHANGELOG.md | 12 +++++++++ CODE_OVERVIEW.md | 50 +++++++++++++++++++++++++++++++------ README.md | 43 ++++++++++++++++++++++++++----- iqmapper/engine_select.py | 4 +-- iqmapper/guided_search.py | 8 +++--- iqmapper/reservoir.py | 20 +++++---------- tests/test_guided_search.py | 4 +-- tests/test_reservoir.py | 8 +++--- 8 files changed, 110 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a54c4c2..4927c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,18 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). handoff that reopens the chosen layout on the second QPU. - Epoch-consistent scoring: fidelity and ranking read a single pinned calibration epoch, so comparisons within a sweep stay commensurable. +- Hybrid search engine: guided search for low ancilla counts, where the + exhaustive search hits its cap and only ranks a sample, and the exhaustive + search above a threshold you set ("Guided up to k"). +- Joint multi-circuit planner: keeps several placement plans at once instead + of placing each circuit greedily, so the first circuit no longer takes a + region the next one needed. Never worse than the sequential planner, uses + the selected search engine, and reports couplers shared by two circuits at + buffer 0 (with an optional penalty to avoid them). + +### Fixed +- Batch scan scored every backend's layouts with the active backend's + calibration; each backend is now scored with its own. ## [0.0.5] — 2026-08 diff --git a/CODE_OVERVIEW.md b/CODE_OVERVIEW.md index 2909b3a..c6c8b7b 100644 --- a/CODE_OVERVIEW.md +++ b/CODE_OVERVIEW.md @@ -13,6 +13,8 @@ state.py ◄────── calibration snapshots (live / intraday / multi- │ ├──► plot.py (device graph, heatmaps, delta rendering) ├──► auto_lucj.py (LUCJ auto-placement + layout error scoring) + ├──► layout search: ancilla_sweep / guided_search / engine_select + │ └─► multi_sweep / joint_plan (several circuits), qpu_scan (several QPUs) ├──► stability.py (multi-day stability analysis) └──► export/ (LQS scoring, layout I/O, codegen, PNG/analysis export) ▲ @@ -41,8 +43,10 @@ Design rules that hold across the codebase: | `connection.py` | Account loading UI, the `_VENDOR_LOADERS` dispatch table (extension point for non-IBM providers), backend listing and selection. Supports multiple named `QiskitRuntimeService` accounts. | | `data.py` | Calibration fetch (live, by timestamp, history ranges) and the per-user on-disk cache (`platformdirs`, atomic writes, per-backend index locking, `IQMAPPER_CACHE_DIR` override). | | `plot.py` | Device-graph construction and all heatmap/delta rendering (Plotly `FigureWidget`), colorbars, and the export legend. | +| `mapper.py` | Thin entry point: receives the connection parameters from `__init__.py`, builds the `SessionState` and launches the UI. | | `auto_lucj.py` | LUCJ zig-zag auto-placement on heavy-hex topologies and `lightweight_layout_error_scoring`. Portions adapted from IBM code now incorporated in [ffsim](https://github.com/qiskit-community/ffsim) — see the file header and [NOTICE](NOTICE). | | `stability.py` | Pure, offline multi-day stability analysis over cached history: which qubits/edges stay good across a 7/14/30-day window. | +| `benchmark.py` | Opt-in real-time benchmarking: re-measures T1/T2, readout, 1Q and 2Q RB on the candidate qubits with `qiskit-experiments` and feeds the result back as a "measured" calibration epoch. Optional `[benchmark]` extra. | | `state.py` | The single `SessionState`: layouts, colors, zoom, time-navigation indices, undo/redo (capped history), and versioned session (de)serialization. | | `paths.py` | Path-traversal-safe file resolution (`commonpath` containment, symlink-aware) for every read/write the user can influence. | | `html_safe.py` | The one `esc()` used by every HTML widget sink. | @@ -50,6 +54,25 @@ Design rules that hold across the codebase: | `_upload.py` | Normalizes ipywidgets `FileUpload` payloads across widget versions into `(bytes, filename)`. | | `constants.py` | Device coordinate tables (Heron 156q, Nighthawk 120q), color mapping factories, palette persistence. | +## Layout search + +All single-circuit engines return the same result dict (strata per ancilla +count, provenance, truncation flags), so the display code never needs to know +which one ran. + +| Module | Role | +|---|---| +| `ancilla_sweep.py` | The exhaustive engine: one VF2 solve at the maximum ancilla count, a bridge-subtraction cascade down to the floor, optional direct VF2 per lower count, diversity selection. Capped at 2000 mappings per stratum. | +| `reservoir.py` | Makes the VF2 cap count *distinct* candidates: near-duplicate layouts are discarded without using a slot, so the capped sample spreads across the chip. | +| `guided_search.py` | The guided engine: calibration-led beam search that grows layouts on the best neighbours, then a 1-opt polish against the circuit-level LQS. | +| `engine_select.py` | The hybrid engine: guided for ancilla counts up to a threshold, exhaustive above it, merged into the shared result shape. | +| `stability_filter.py` | Stability-aware sweep: excludes qubits that are volatile across cached history (and statistical outliers), then runs the exhaustive sweep, relaxing the filter when the circuit would no longer fit. | +| `multi_sweep.py` | Sequential multi-circuit placement: each circuit greedily on the best region left, with a buffer around placed ones; replan from any circuit. | +| `joint_plan.py` | Joint multi-circuit planner: a beam over placement plans with an injected single-circuit search, memoised searches and boundary-coupler accounting. Same result shape as `multi_sweep`, never worse than it. | +| `qpu_scan.py` | Multi-QPU scan: lists compatible backends and runs a sweep on each, isolating per-backend failures. | +| `props_shim.py` | Cache-aware properties adapter for the scan: serves a backend's cached calibration arrays through the `readout_error` / `gate_error` / `score_layout` interface the engines read. | +| `evaluation.py` | Offline engine comparison: replays VF2 and guided over cached calibration snapshots and tabulates per-stratum differences (CLI: `python -m iqmapper.evaluation`). | + ## `export/` — analysis & I/O | Module | Role | @@ -60,6 +83,7 @@ Design rules that hold across the codebase: | `autodetect.py` | Heuristics that classify uploaded files and detect layout shapes. | | `session.py` | Session and style-preset save/load (size-capped, versioned). | | `data.py` | Analysis-export helpers (tabular views of calibration data). | +| `analysis.py` | Per-qubit / per-gate rankings, trends, connectivity and stable-element finders. Pure data + HTML. | ## `ui/` — ipywidgets panels @@ -69,20 +93,32 @@ Design rules that hold across the codebase: | `time_panel.py` | Time navigation: live / point / intraday / multi-day modes, snapshot sliders, delta reference selection. | | `history.py` | Multi-day history fetch and the time-lapse GIF/MP4 export (optional `imageio` / `imageio-ffmpeg`). | | `analysis_panel.py` | LQS display, layout rankings, and the Stability Check section. | -| `lucj_panel.py` | LUCJ-specific controls (auto-placement, ancilla/bridge handling). | +| `lucj_panel.py` | LUCJ controls: the single dispatch points for the search engine (`_run_sweep`) and the multi-circuit planner (`_run_multi` / `_replan_multi`), the sweep and scan displays, and replan. | +| `benchmark_panel.py` | Sidebar section "5. Benchmark": targets, cost estimate, run, and applying the measured epoch. | | `inter_qpu.py` | Multi-backend comparison view. | | `png_export.py` | Publication PNG export (optional `kaleido`). | | `session_io.py` | Session save/load UI. | | `backend_switch.py`, `color_picker.py`, `_sidebar_css.py` | Backend switching, palette editing, styling. | +| `pretty_json.py`, `status.py`, `widgets_ref.py` | JSON preview rendering, the shared inline status banner, typed references to widgets shared between modules. | + +**Shared layout `W`.** `builder.py` creates one `Layout` object, `W`, and +passes it to dozens of widgets. Never change it at runtime (e.g. +`.layout.display = 'none'` to hide something): every widget that shares it +changes too, so hiding one hides about 86. Any widget whose layout is changed +at runtime gets its own `Layout(...)`, and its UI test asserts it is not +`W` (`widget.layout is not builder.txt_auto.layout`). ## Tests -`tests/` — 183 tests, deterministic and fully offline (no QPU, no network, no -qiskit required except one optional QPY round-trip that skips when qiskit is -absent). Coverage concentrates on the pure logic: path safety, state -round-trips and undo/redo, upload normalization, layout import hardening -(including hostile-input regressions), scoring, time-status describers, and -HTML escaping. Run with: +`tests/` — 736 tests in 68 files, deterministic and fully offline (no QPU, no +network, no credentials). A few skip when an optional dependency is missing: +the QPY round-trip without qiskit, and `test_benchmark_integration.py` without +the `[benchmark]` extra. Coverage concentrates on the pure logic: the search +engines and planners (on synthetic lattices from +`rustworkx.generators.heavy_hex_graph` with seeded calibrations), path safety, +state round-trips and undo/redo, layout import hardening (including +hostile-input regressions), scoring, the headless UI, the copy-length guard, +and HTML escaping. Run with: ```bash pip install -e ".[dev]" diff --git a/README.md b/README.md index 32a97d9..6634a17 100644 --- a/README.md +++ b/README.md @@ -288,8 +288,8 @@ Tooltips that end with `· README: ` point at the matching entry below. ### Search cap The exhaustive engine enumerates candidate layouts and stops at this many. On -a large chip there can be tens of thousands, so the cap is normally reached at -low ancilla counts. When it is, the notices bar says so — raise the cap for a +a large chip there can be far more layouts than the cap, so it is normally +reached at low ancilla counts. When it is, the notices bar says so — raise the cap for a more thorough (slower) search, or leave it and rely on diverse enumeration. ### Diverse enumeration @@ -297,9 +297,10 @@ more thorough (slower) search, or leave it and rely on diverse enumeration. With this on, the cap counts *distinct* candidates. During the search a layout that overlaps one already kept by more than 80% of its qubits, and does not score better, is discarded without using a slot; one that scores better takes -its place. Without it the cap fills with near-copies of whatever the search -found first, which on a 193-qubit chip meant never looking at 44% of the -device. It only makes a difference where the cap is actually reached. +its place. Without it the cap fills with near-copies of the first region the +search finds, and much of a large chip is never looked at. With it, similar +layouts don't use up the cap, so the sample spreads across the chip. It only +makes a difference where the cap is actually reached. ### Search engine @@ -309,10 +310,40 @@ grows each layout using the calibration as it goes and polishes the finalists. Guided is a heuristic: it can miss the best layout that exhaustive would find, so it stays opt-in until the comparison harness says otherwise. +**Hybrid** uses guided where exhaustive is capped (few ancillas: so many +layouts fit that exhaustive only ranks a sample) and exhaustive where it is +complete (many ancillas: few layouts fit, and all of them are checked). Set +**Guided up to k** to the highest ancilla count where guided does at least as +well as exhaustive in the engine comparison (`python -m iqmapper.evaluation`). +The status line names the split, e.g. `engine: hybrid (guided ≤ k1)`; the +`refined 2/5` tally counts the guided finalists the polish improved. + ### Multi-circuit planner **Sequential** places circuits one at a time, each on the best region left. -**Joint** keeps several partial plans and returns the best complete one. +It is fast but short-sighted: the first circuit can take a region that leaves +the next one only a poor spot, or none at all. + +**Joint** keeps several partial plans instead of one. After each circuit it +tries **Candidates per circuit** layouts on every plan it holds and keeps the +best **Plans kept** of them. It also builds the sequential plan and returns +whichever is better, so it is never worse — only slower. It searches with the +selected search engine (Sequential always uses exhaustive). While it runs, the +status shows `joint plan · up to N searches`, the worst case. + +When it finishes, `joint plan · +X% vs sequential · N searches` compares the +two plans' totals (the product of each circuit's LQS) and counts the searches +actually run. If the joint plan fits more circuits than sequential could, it +says `places 3 vs 2 sequential` instead, since a total over more circuits is +not comparable. + +**Boundary penalty** matters only at **Buffer qubits: 0**. With a buffer of 1 +or more, two circuits can never touch. At 0 they can sit side by side, and a +coupler between them carries gates of one circuit next to idle qubits of the +other: crosstalk the LQS does not model. `shared couplers: 47–48` lists such +couplers. Each one multiplies the plan's score by `1 − penalty`, so a penalty +of 0.5 makes the planner prefer a plan without them when one exists; 0 only +reports them. ### Prefer diverse regions diff --git a/iqmapper/engine_select.py b/iqmapper/engine_select.py index b198aae..c9576a1 100644 --- a/iqmapper/engine_select.py +++ b/iqmapper/engine_select.py @@ -3,8 +3,8 @@ threshold, exhaustive VF2 above it. The two single-circuit engines fail in opposite places. With few bridges (low -k) the LUCJ template is loose, VF2 finds tens of thousands of embeddings on a -large heavy-hex and ranks only what fits under its mapping cap. With many +k) the LUCJ template is loose, VF2 finds far more embeddings on a large chip +than its mapping cap holds and ranks only the capped sample. With many bridges (high k) the template is tight, the embeddings are few, and VF2 is genuinely exhaustive — exactly where a beam search can only tie or lose. So each stratum is taken from the engine that is reliable there: diff --git a/iqmapper/guided_search.py b/iqmapper/guided_search.py index 12488bc..4405723 100644 --- a/iqmapper/guided_search.py +++ b/iqmapper/guided_search.py @@ -3,9 +3,9 @@ The existing engine (`ancilla_sweep.sweep_ancilla_layouts`) enumerates zigzag embeddings with VF2, which is blind to calibration: it finds subgraphs that fit -the template and only then asks how good they are. On a 193-qubit heavy-hex at -low bridge counts that enumeration runs to 37k-100k+ mappings and gets cut off -at the 2000 cap, so the ranking sees an arbitrary 2% sample of the search +the template and only then asks how good they are. On a large chip at low +bridge counts that enumeration yields far more mappings than the 2000 cap and +gets cut off, so the ranking sees only an arbitrary sample of the search space. Quality survives because the downstream cascade, monotonicity anchors and diversity quota are good — but generation is throwing away information it already has. @@ -76,7 +76,7 @@ Beam search is a heuristic. It can miss the global optimum that exhaustive VF2 would find on a small device, which is precisely why the default stays VF2 and why `evaluation.compare_engines` exists. On the fixtures in the test suite the -two agree; on a 193-qubit chip VF2 cannot enumerate the space at all, so the +two agree; on a large chip VF2 cannot enumerate the space at all, so the comparison there is between a guided sample and an arbitrary one. """ import logging diff --git a/iqmapper/reservoir.py b/iqmapper/reservoir.py index c9047b6..0a24a75 100644 --- a/iqmapper/reservoir.py +++ b/iqmapper/reservoir.py @@ -6,16 +6,9 @@ `auto_lucj._collect_vf2_mappings` takes the first `cap` mappings rustworkx yields and stops. VF2 walks the graph in a deterministic traversal order, so those first mappings are spatially clustered: the same region of the chip with -one qubit shifted, over and over. Measured on a 193-qubit heavy-hex at -norb=8, k=1 (37,044 mappings available, cap 2000 = 5.4 %): - - kept set mean pairwise Jaccard qubits covered - first 2000 (the cap) 0.161 109 / 193 - random 2000 0.068 193 / 193 - all 37,044 0.069 193 / 193 - -The cap's sample is 2.3x more self-similar than a representative one and -never sees 44 % of the chip. The downstream cascade, monotonicity anchors and +one qubit shifted, over and over. Where the cap is reached, the capped sample +is far more self-similar than a representative one, and much of a large chip +is never seen. The downstream cascade, monotonicity anchors and diversity quota are all good, but they can only choose among what enumeration handed them. @@ -78,10 +71,9 @@ DEFAULT_JACCARD = 0.8 #: Mappings considered per kept slot. The cap bounds what is HELD; this -#: bounds what is EXAMINED. Iterating VF2 is cheap (37k mappings in ~0.1 s on -#: a 193-qubit heavy-hex) — it is materialising and scoring them that the cap -#: was protecting against — so a generous factor buys most of the available -#: diversity at negligible cost. +#: bounds what is EXAMINED. Iterating VF2 is cheap — it is materialising and +#: scoring the mappings that the cap was protecting against — so a generous +#: factor buys most of the available diversity at negligible cost. OFFER_BUDGET_FACTOR = 20 diff --git a/tests/test_guided_search.py b/tests/test_guided_search.py index 95e090a..eb51f2d 100644 --- a/tests/test_guided_search.py +++ b/tests/test_guided_search.py @@ -347,8 +347,8 @@ def _boom(_e): def test_low_k_does_not_explode_on_heavy_hex(): """The failure mode this engine exists to fix, asserted structurally. - VF2 enumerates 37k-100k+ mappings for k<=1 on a large heavy-hex and gets - capped. The beam is bounded by construction: expansions can never exceed + At k<=1 on a large lattice VF2 finds far more mappings than its cap and + gets cut off. The beam is bounded by construction: expansions can never exceed beam_width x norb x max_degree^2, so the assertion is on a counter rather than on wall time (which would be flaky on CI). """ diff --git a/tests/test_reservoir.py b/tests/test_reservoir.py index 30d32a6..fb485d8 100644 --- a/tests/test_reservoir.py +++ b/tests/test_reservoir.py @@ -1,10 +1,10 @@ """Tests for the diverse VF2 reservoir (engine #17). The reservoir exists because a blind cap keeps a spatially clustered sample: -on a 193-qubit heavy-hex at k=1 the first 2000 of 37,044 mappings have mean -pairwise Jaccard 0.161 and touch only 109 of 193 qubits, against 0.068 / 193 -for a representative sample. These tests pin the sieve's semantics, its -agreement with the sweep's own score, and that it actually widens the sample. +VF2 yields mappings in traversal order, so the first ones are near-copies of +one region and much of a large lattice is never seen. These tests pin the +sieve's semantics, its agreement with the sweep's own score, and that it +actually widens the sample. """ import random from types import SimpleNamespace From fa630f3074199fbe2b3eff724bd7f2ea3118718d Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 22:54:18 -0400 Subject: [PATCH 42/66] Evaluation harness: real LQS per snapshot, threshold suggestion --- CHANGELOG.md | 6 ++ iqmapper/evaluation.py | 210 ++++++++++++++++++++++++++++++++++----- tests/test_evaluation.py | 200 +++++++++++++++++++++++++++++++++++++ 3 files changed, 391 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4927c89..5ce4e1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,12 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). region the next one needed. Never worse than the sequential planner, uses the selected search engine, and reports couplers shared by two circuits at buffer 0 (with an optional penalty to avoid them). +- Engine comparison harness (`python -m iqmapper.evaluation`) now ranks with + the app's real circuit-level LQS, rebuilt for every cached calibration + (`--scorer lqs`, the new default; `proxy` keeps the product score). It can + add a hybrid-engine column (`--hybrid-k`) and prints the suggested + "Guided up to k" for each orbital count (`--tol` sets how far guided may + trail and still count). ### Fixed - Batch scan scored every backend's layouts with the active backend's diff --git a/iqmapper/evaluation.py b/iqmapper/evaluation.py index 41516f6..05435f1 100644 --- a/iqmapper/evaluation.py +++ b/iqmapper/evaluation.py @@ -11,18 +11,30 @@ local cache — no network, no QPU time, no credentials. For each (date, norb, k) it records the best circuit-level LQS each engine reached, the wall time, how many distinct chain scaffolds each produced, and whether VF2 truncated. +Optionally it also runs the hybrid engine (`engine_select.hybrid_sweep`) at one +or more thresholds, and `suggest_guided_max_k` turns the table into the value +to enter as "Guided up to k". + +The metric +---------- +`scorer='lqs'` ranks with the real circuit-level LQS — the same +`export.scoring.estimate_circuit_fidelity` call the app makes — rebuilt for +every snapshot, because the properties change from date to date. +`scorer='proxy'` ranks with the product score instead (reported as +`lqs_proxy`); it needs nothing but the property arrays. An explicit +`circuit_score_fn` overrides both (reported as `custom`). Reading the table ----------------- `delta_lqs` is `guided - vf2` in LQS points. Positive means guided found a better layout on that snapshot. `vf2_capped` matters: where VF2 truncated, it -was ranking an arbitrary 2% sample, so a guided win there says the guided +was ranking an arbitrary sample, so a guided win there says the guided sample is better-chosen, not that beam search beats exhaustive search. Where VF2 did NOT truncate it enumerated everything, so a guided win is a genuine win and a guided loss is the heuristic's real cost. -Both engines get the same graph, the same properties and the same -`circuit_score_fn`, so the comparison is like-for-like. +Both engines get the same graph, the same properties and the same scorer, +so the comparison is like-for-like. Where the topology comes from ----------------------------- @@ -36,18 +48,25 @@ 1. an explicit `coupling=[(u, v), ...]` argument; 2. a saved session for that backend under `.iqmapper_sessions/`, which does - persist `edges_list` (see `state.to_dict`); + persist `edges_list` and `qubit_ids` (see `state.to_dict`); 3. otherwise the run reports a clear error rather than guessing — an invented topology would produce numbers that look real and mean nothing. Save a session once for the backend you want to evaluate and every cached calibration for it becomes replayable. +The gate arrays are positional, so the edges must be the backend's own edge +list in the app's order (`data._generate_ibm`: `coupling_map.get_edges()`, +both directions). A saved session's `edges_list` is exactly that; an explicit +`coupling=` must be too. Qubit ids are `str(i)` for i in 0..n-1 in the app, +which is also the fallback when no session supplies them. + CLI --- - python -m iqmapper.evaluation ibm_boston --norb 8 12 16 + python -m iqmapper.evaluation ibm_boston --norb 8 12 16 --hybrid-k 1 2 -prints the table and writes `.scratch/eval__.md`. +prints the table and the suggested "Guided up to k" per norb, and writes both +to `.scratch/eval__.md`. `--scorer` defaults to `lqs`. """ import argparse import json as _json @@ -63,12 +82,16 @@ from . import data as _data from .ancilla_sweep import sweep_ancilla_layouts +from .engine_select import hybrid_sweep from .guided_search import guided_sweep _log = logging.getLogger(__name__) DEFAULT_NORBS = (8, 12, 16) +#: Scorer names accepted by `compare_engines`, and the metric each reports. +SCORERS = {'proxy': 'lqs_proxy', 'lqs': 'lqs'} + # ── replaying a cached calibration as a backend/props pair ────────── @@ -136,6 +159,39 @@ def _score(entry): return _score +def _lqs_scorer(qubit_props, gate_props, edges, qubit_ids): + """The app's circuit-level LQS for one calibration snapshot. + + Mirrors `ui.lucj_panel._circuit_score`: a scratch one-layout state with the + candidate's qubits as string ids, scored by + `export.scoring.estimate_circuit_fidelity(fake, 0, 'lucj')`. The arrays + are bound once, so build a new scorer for every snapshot. + """ + from .export.scoring import estimate_circuit_fidelity + qubit_props_data = {k: np.asarray(v) for k, v in qubit_props.items()} + gate_props_data = {k: np.asarray(v) for k, v in gate_props.items()} + edges_list = [tuple(int(x) for x in e) for e in edges] + ids = [str(q) for q in qubit_ids] + + def _score(entry): + layout = { + 'alpha': [str(q) for q in entry['alpha']], + 'beta': [str(q) for q in entry['beta']], + 'other': [], + 'ancilla': [str(q) for q in entry['ancillas']], + } + fake = SimpleNamespace( + layouts_data={0: layout}, + qubit_props_data=qubit_props_data, + gate_props_data=gate_props_data, + qubit_ids=ids, + edges_list=edges_list, + ) + res = estimate_circuit_fidelity(fake, 0, 'lucj') + return res['fidelity'] if res else None + return _score + + # ── report ────────────────────────────────────────────────────────── class Row: @@ -143,11 +199,11 @@ class Row: __slots__ = ('date', 'norb', 'k', 'vf2_lqs', 'guided_lqs', 'vf2_time', 'guided_time', 'vf2_scaffolds', 'guided_scaffolds', - 'vf2_capped', 'refined') + 'vf2_capped', 'refined', 'hybrid_lqs') def __init__(self, date, norb, k, vf2_lqs, guided_lqs, vf2_time, guided_time, vf2_scaffolds, guided_scaffolds, vf2_capped, - refined): + refined, hybrid_lqs=None): self.date = date self.norb = norb self.k = k @@ -159,6 +215,8 @@ def __init__(self, date, norb, k, vf2_lqs, guided_lqs, vf2_time, self.guided_scaffolds = guided_scaffolds self.vf2_capped = vf2_capped self.refined = refined + # {guided_max_k: best LQS at this k}, one entry per hybrid threshold. + self.hybrid_lqs = dict(hybrid_lqs or {}) @property def delta(self): @@ -175,10 +233,13 @@ def guided_at_least(self): class Report: """The rows plus the summary a human actually reads.""" - def __init__(self, backend_name, rows, errors=None): + def __init__(self, backend_name, rows, errors=None, metric='lqs_proxy', + hybrid_ks=()): self.backend_name = backend_name self.rows = list(rows) self.errors = list(errors or []) + self.metric = metric + self.hybrid_ks = tuple(hybrid_ks) # ── aggregates ────────────────────────────────────────────── def _comparable(self): @@ -202,31 +263,74 @@ def summary(self): def to_markdown(self): lines = [f'# Engine comparison - {self.backend_name}', '', - self.summary(), ''] + f'Metric: {self.metric}', '', self.summary(), ''] if self.errors: lines += ['## Errors', ''] lines += [f'- {e}' for e in self.errors] lines += [''] + hybrid_head = ''.join(f' hybrid k<={t} |' for t in self.hybrid_ks) + hybrid_rule = '---:|' * len(self.hybrid_ks) lines += [ '| date | norb | k | VF2 | guided | dLQS (pt) | VF2 s | guided s |' - ' VF2 scaffolds | guided scaffolds | VF2 capped | refined |', - '|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|:--:|---:|'] + ' VF2 scaffolds | guided scaffolds | VF2 capped | refined |' + + hybrid_head, + '|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|:--:|---:|' + + hybrid_rule] for r in self.rows: def _f(value, digits=4): return '-' if value is None else f'{value:.{digits}f}' delta = ('-' if r.delta is None else f'{r.delta * 100:+.2f}') + hybrid_cells = ''.join(f' {_f(r.hybrid_lqs.get(t))} |' + for t in self.hybrid_ks) lines.append( f'| {r.date} | {r.norb} | {r.k} | {_f(r.vf2_lqs)} | ' f'{_f(r.guided_lqs)} | {delta} | {r.vf2_time:.2f} | ' f'{r.guided_time:.2f} | {r.vf2_scaffolds} | ' f'{r.guided_scaffolds} | {"yes" if r.vf2_capped else "no"} | ' - f'{r.refined} |') + f'{r.refined} |' + hybrid_cells) return '\n'.join(lines) + '\n' def __repr__(self): # pragma: no cover - debug aid return f'' +def suggest_guided_max_k(report, tol=0.0): + """The highest k up to which guided holds its own, per norb. + + For each norb: the largest `t` such that, for every k from the floor up + to `t`, the median `delta` (guided - VF2) over the snapshots is + `>= -tol`. `tol` is in LQS points, the unit of the dLQS column. `None` + when guided already loses at the floor (or the floor has no comparable + rows). This is the value for "Guided up to k". + """ + by_norb = {} + for r in report.rows: + if r.delta is not None: + by_norb.setdefault(r.norb, {}).setdefault(r.k, []).append(r.delta) + suggestion = {} + for norb in sorted({r.norb for r in report.rows}): + per_k = by_norb.get(norb, {}) + ks = sorted({r.k for r in report.rows if r.norb == norb}) + best = None + for k in ks: + deltas = per_k.get(k) + if not deltas or statistics.median(deltas) * 100.0 < -tol: + break + best = k + suggestion[norb] = best + return suggestion + + +def format_suggestion(suggestion): + """One line per norb, for the CLI.""" + lines = ['Suggested "Guided up to k":'] + for norb, t in sorted(suggestion.items()): + lines.append(f'- norb {norb}: ' + + ('none (guided loses at the floor)' if t is None + else f'{t}')) + return '\n'.join(lines) + '\n' + + # ── the comparison ────────────────────────────────────────────────── def _scaffolds(result): @@ -252,7 +356,7 @@ def _best_lqs(result, k): def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, min_bridges=0, cache_dir=None, beam_width=200, circuit_score_fn=None, limit=None, coupling=None, - session_dir=None): + session_dir=None, scorer='proxy', hybrid_ks=()): """Run both engines over the cached calibrations and report. Read-only and offline: reads the local calibration cache, never the @@ -264,8 +368,19 @@ def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, norbs: orbital counts to test. cache_dir: override `data._CACHE_DIR` for the duration (tests). limit: cap the number of calibrations replayed. + scorer: 'proxy' (product score, `lqs_proxy`) or 'lqs' (the app's + circuit-level LQS, rebuilt per snapshot). An explicit + `circuit_score_fn` wins over both. + hybrid_ks: thresholds at which to also run the hybrid engine; each + adds a `hybrid k<=t` column. Empty = the two-engine table. """ - scorer = circuit_score_fn or _product_scorer() + if scorer not in SCORERS: + raise ValueError(f"scorer={scorer!r}; expected one of " + f"{sorted(SCORERS)}.") + metric = 'custom' if circuit_score_fn is not None else SCORERS[scorer] + fixed_scorer = circuit_score_fn or ( + _product_scorer() if scorer == 'proxy' else None) + hybrid_ks = tuple(int(t) for t in hybrid_ks) min_bridges = max(1, int(min_bridges)) old_cache = None @@ -281,15 +396,18 @@ def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, rows, errors = [], [] # The cache has no topology; resolve it once for the whole run. + session_ids = None if coupling is None: - coupling = coupling_from_sessions(backend_name, session_dir) + topology = _session_topology(backend_name, session_dir) + if topology is not None: + coupling, session_ids = topology if coupling is None: errors.append( f'No coupling map for {backend_name}: the calibration cache ' f'stores only property arrays. Pass coupling=[(u, v), ...] or ' f'save a session for this backend so .iqmapper_sessions/ ' f'carries its edges_list.') - return Report(backend_name, [], errors) + return Report(backend_name, [], errors, metric, hybrid_ks) for stamp in stamps: snapshot = _data._load_calibration(backend_name, stamp) @@ -305,12 +423,20 @@ def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, continue backend = _backend_from_edges(edges, n_qubits, backend_name) props = _CachedProps(qubit_props, gate_props, edges) + if fixed_scorer is not None: + snapshot_scorer = fixed_scorer + else: + ids = (session_ids if session_ids is not None + and len(session_ids) == n_qubits + else [str(i) for i in range(n_qubits)]) + snapshot_scorer = _lqs_scorer(qubit_props, gate_props, edges, + ids) for norb in norbs: rows.extend(_compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, - scorer, errors)) - return Report(backend_name, rows, errors) + snapshot_scorer, errors, hybrid_ks)) + return Report(backend_name, rows, errors, metric, hybrid_ks) finally: if old_cache is not None: _data._CACHE_DIR = old_cache @@ -342,6 +468,15 @@ def coupling_from_sessions(backend_name, session_dir=None): saved session makes every cached calibration for that backend replayable. Returns a list of (u, v), or None when nothing matches. """ + topology = _session_topology(backend_name, session_dir) + return None if topology is None else topology[0] + + +def _session_topology(backend_name, session_dir=None): + """`(edges, qubit_ids)` from the first matching saved session, or None. + + `qubit_ids` is None when the session does not carry it. + """ directory = session_dir or os.path.join(os.getcwd(), '.iqmapper_sessions') try: names = sorted(os.listdir(directory)) @@ -360,13 +495,15 @@ def coupling_from_sessions(backend_name, session_dir=None): continue edges = payload.get('edges_list') or [] if edges: - return [tuple(int(x) for x in e) for e in edges] + ids = payload.get('qubit_ids') + return ([tuple(int(x) for x in e) for e in edges], + [str(q) for q in ids] if ids else None) return None def _compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, - scorer, errors): - """One (date, norb): run both engines, emit a row per shared stratum.""" + scorer, errors, hybrid_ks=()): + """One (date, norb): run the engines, emit a row per stratum.""" try: t0 = time.time() vf2 = sweep_ancilla_layouts(norb, backend, props, @@ -386,6 +523,17 @@ def _compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, errors.append(f'{stamp} norb={norb}: guided failed ({exc})') return [] + hybrid = {} + for t in hybrid_ks: + try: + hybrid[t] = hybrid_sweep(norb, backend, props, guided_max_k=t, + min_bridges=min_bridges, top_n=top_n, + circuit_score_fn=scorer, + guided_kwargs={'beam_width': beam_width}) + except Exception as exc: # noqa: BLE001 - recorded + errors.append(f'{stamp} norb={norb}: hybrid k<={t} failed ' + f'({exc})') + vf2_scaffolds = _scaffolds(vf2) guided_scaffolds = _scaffolds(guided) capped = bool(vf2.get('vf2_truncated')) @@ -396,7 +544,8 @@ def _compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, reverse=True): rows.append(Row(stamp, norb, k, _best_lqs(vf2, k), _best_lqs(guided, k), vf2_time, guided_time, - vf2_scaffolds, guided_scaffolds, capped, refined)) + vf2_scaffolds, guided_scaffolds, capped, refined, + {t: _best_lqs(res, k) for t, res in hybrid.items()})) return rows @@ -418,14 +567,25 @@ def main(argv=None): parser.add_argument('--session-dir', default=None, help='where to look for a saved session carrying the ' 'coupling map (default .iqmapper_sessions)') + parser.add_argument('--scorer', choices=sorted(SCORERS), default='lqs', + help='lqs = the app\'s circuit-level LQS (default); ' + 'proxy = product score') + parser.add_argument('--hybrid-k', type=int, nargs='+', default=[], + help='also run the hybrid engine at these thresholds') + parser.add_argument('--tol', type=float, default=0.0, + help='LQS points guided may trail VF2 by and still ' + 'count as holding its own (default 0)') args = parser.parse_args(argv) logging.basicConfig(level=logging.WARNING) report = compare_engines(args.backend, norbs=tuple(args.norb), top_n=args.top_n, min_bridges=args.min_bridges, beam_width=args.beam_width, limit=args.limit, - session_dir=args.session_dir) - markdown = report.to_markdown() + session_dir=args.session_dir, + scorer=args.scorer, + hybrid_ks=tuple(args.hybrid_k)) + markdown = (report.to_markdown() + '\n' + + format_suggestion(suggest_guided_max_k(report, args.tol))) print(markdown) try: diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py index 9273451..2fce77a 100644 --- a/tests/test_evaluation.py +++ b/tests/test_evaluation.py @@ -195,3 +195,203 @@ def test_cli_runs_and_writes_a_report(tmp_path, capsys, monkeypatch): written = list(out_dir.glob('eval_ibm_fixture_*.md')) assert written, 'the CLI did not write a report' assert '# Engine comparison' in written[0].read_text(encoding='utf-8') + + +# ── the real-LQS scorer ───────────────────────────────────────────── + +def _entry(alpha, beta, ancillas): + return {'alpha': list(alpha), 'beta': list(beta), + 'ancillas': list(ancillas), 'product_score': 0.5} + + +def _snapshot(n_rungs=8, seed=0, gate_scale=1.0): + edges = _ladder_edges(n_rungs) + n_q = 3 * n_rungs + rng = np.random.default_rng(seed) + qubit_props = {'readout_error': 0.01 + 0.01 * rng.random(n_q)} + gate_props = {'cz_error': gate_scale * (0.005 + 0.01 + * rng.random(len(edges)))} + return qubit_props, gate_props, edges, [str(i) for i in range(n_q)] + + +def test_lqs_scorer_matches_the_app_path(): + """Same value as estimate_circuit_fidelity on a real SessionState, and + on the scratch state the panel's _circuit_score builds.""" + from types import SimpleNamespace + from iqmapper.export.scoring import estimate_circuit_fidelity + from iqmapper.state import SessionState + + qubit_props, gate_props, edges, ids = _snapshot() + entry = _entry([0, 1, 2, 3], [8, 9, 10, 11], [16]) + ours = ev._lqs_scorer(qubit_props, gate_props, edges, ids)(entry) + + layout = {'alpha': ['0', '1', '2', '3'], 'beta': ['8', '9', '10', '11'], + 'other': [], 'ancilla': ['16']} + fake = SimpleNamespace(layouts_data={0: layout}, + qubit_props_data=qubit_props, + gate_props_data=gate_props, qubit_ids=ids, + edges_list=[tuple(e) for e in edges]) + panel = estimate_circuit_fidelity(fake, 0, 'lucj')['fidelity'] + + state = SessionState() + state.qubit_ids = list(ids) + state.edges_list = [tuple(e) for e in edges] + state.qubit_props_data = {k: np.asarray(v) for k, v in qubit_props.items()} + state.gate_props_data = {k: np.asarray(v) for k, v in gate_props.items()} + state.layouts_data = {0: dict(layout)} + real = estimate_circuit_fidelity(state, 0, 'lucj')['fidelity'] + + assert ours == pytest.approx(panel, rel=1e-12) + assert ours == pytest.approx(real, rel=1e-12) + assert 0.0 < ours < entry['product_score'] * 2 + + +def test_lqs_scorer_is_rebuilt_for_every_snapshot(tmp_path, monkeypatch): + backend = 'ibm_fixture' + stamps = ['2026-09-01T00:00:00Z', '2026-09-02T00:00:00Z'] + edges = _write_cache(tmp_path, backend, stamps) + built = [] + real = ev._lqs_scorer + + def _spy(qubit_props, gate_props, edges_, ids): + fn = real(qubit_props, gate_props, edges_, ids) + built.append(fn) + return fn + + monkeypatch.setattr(ev, '_lqs_scorer', _spy) + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, coupling=edges, + beam_width=50, scorer='lqs') + assert not report.errors, report.errors + assert len(built) == len(stamps) + entry = _entry([0, 1, 2, 3], [8, 9, 10, 11], [16]) + assert built[0](entry) != built[1](entry) # different gate errors + assert report.metric == 'lqs' + assert 'Metric: lqs\n' in report.to_markdown() + + +def test_lqs_scorer_takes_qubit_ids_from_the_session(tmp_path, monkeypatch): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + session_dir = tmp_path / 'sessions' + _write_session(str(session_dir), backend, edges, 24) + seen = [] + real = ev._lqs_scorer + monkeypatch.setattr(ev, '_lqs_scorer', lambda q, g, e, ids: ( + seen.append((list(e), list(ids))) or real(q, g, e, ids))) + ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, session_dir=str(session_dir), + beam_width=50, scorer='lqs') + assert seen == [([tuple(e) for e in edges], + [str(i) for i in range(24)])] + + +def _numbers(report): + return [(r.date, r.norb, r.k, r.vf2_lqs, r.guided_lqs, r.vf2_scaffolds, + r.guided_scaffolds, r.vf2_capped, r.refined) + for r in report.rows] + + +def test_proxy_and_an_explicit_scorer_reproduce_the_default(tmp_path): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + kw = dict(norbs=(4,), top_n=2, min_bridges=1, cache_dir=tmp_path, + coupling=edges, beam_width=50) + default = ev.compare_engines(backend, **kw) + proxy = ev.compare_engines(backend, scorer='proxy', **kw) + explicit = ev.compare_engines(backend, scorer='lqs', + circuit_score_fn=ev._product_scorer(), **kw) + assert _numbers(default) == _numbers(proxy) == _numbers(explicit) + assert default.metric == proxy.metric == 'lqs_proxy' + assert explicit.metric == 'custom' + + +def test_an_unknown_scorer_is_refused(tmp_path): + with pytest.raises(ValueError, match='scorer'): + ev.compare_engines('ibm_fixture', scorer='fidelity', + cache_dir=tmp_path, coupling=[(0, 1)]) + + +# ── the threshold suggestion ──────────────────────────────────────── + +def _row(norb, k, vf2, guided, date='d1'): + return ev.Row(date, norb, k, vf2, guided, 0.0, 0.0, 1, 1, False, 0) + + +def test_suggest_guided_max_k(): + rows = [ + # norb 8: guided holds at k=1 and 2, loses at 3 → t = 2 + _row(8, 1, 0.50, 0.52), _row(8, 1, 0.50, 0.49, 'd2'), + _row(8, 1, 0.50, 0.51, 'd3'), + _row(8, 2, 0.40, 0.40), _row(8, 3, 0.30, 0.25), + # norb 12: loses at the floor → None + _row(12, 1, 0.50, 0.45), _row(12, 2, 0.40, 0.45), + # norb 16: 0.4 pt behind at k=1 — a tolerance of 0.5 pt lets it pass + _row(16, 1, 0.500, 0.496), _row(16, 2, 0.4, None), + ] + report = ev.Report('ibm_x', rows) + assert ev.suggest_guided_max_k(report) == {8: 2, 12: None, 16: None} + assert ev.suggest_guided_max_k(report, tol=0.5) == {8: 2, 12: None, + 16: 1} + assert ev.suggest_guided_max_k(report, tol=6.0)[8] == 3 + text = ev.format_suggestion({8: 2, 12: None}) + assert '- norb 8: 2' in text + assert '- norb 12: none (guided loses at the floor)' in text + + +# ── the hybrid column ─────────────────────────────────────────────── + +def test_hybrid_column_is_added_and_matches_its_halves(tmp_path): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + report = ev.compare_engines(backend, norbs=(5,), top_n=2, min_bridges=1, + cache_dir=tmp_path, coupling=edges, + beam_width=50, hybrid_ks=(1,)) + assert not report.errors, report.errors + assert {r.k for r in report.rows} == {1, 2} + for r in report.rows: + expected = r.guided_lqs if r.k <= 1 else r.vf2_lqs + assert r.hybrid_lqs == {1: expected} + text = report.to_markdown() + header = next(line for line in text.splitlines() + if line.startswith('| date')) + assert header.endswith(' refined | hybrid k<=1 |') + + +def test_no_hybrid_leaves_the_table_unchanged(): + rows = [_row(8, 1, 0.5, 0.52)] + report = ev.Report('ibm_x', rows) + assert report.to_markdown() == ev.Report('ibm_x', rows, + hybrid_ks=()).to_markdown() + assert report.to_markdown() == ( + '# Engine comparison - ibm_x\n' + '\n' + 'Metric: lqs_proxy\n' + '\n' + f'{report.summary()}\n' + '\n' + '| date | norb | k | VF2 | guided | dLQS (pt) | VF2 s | guided s |' + ' VF2 scaffolds | guided scaffolds | VF2 capped | refined |\n' + '|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|:--:|---:|\n' + '| d1 | 8 | 1 | 0.5000 | 0.5200 | +2.00 | 0.00 | 0.00 | 1 | 1 |' + ' no | 0 |\n') + + +def test_cli_prints_the_suggestion_and_takes_the_new_flags( + tmp_path, capsys, monkeypatch): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + session_dir = tmp_path / 'sessions' + _write_session(str(session_dir), backend, edges, 24) + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + code = ev.main([backend, '--norb', '5', '--top-n', '2', + '--min-bridges', '1', '--beam-width', '50', + '--session-dir', str(session_dir), + '--out-dir', str(tmp_path / 'out'), + '--hybrid-k', '1', '--tol', '0.5']) + assert code == 0 + printed = capsys.readouterr().out + assert 'Metric: lqs\n' in printed # CLI default + assert 'hybrid k<=1' in printed + assert 'Suggested "Guided up to k":' in printed + assert '- norb 5:' in printed From f9bf4c28c936ab50a1ea42bef0405d68c91fcc43 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 23:16:40 -0400 Subject: [PATCH 43/66] Evaluation harness: find real saved sessions (backend_name key, --session flag) --- iqmapper/evaluation.py | 177 +++++++++++++++++++++++++++++++-------- tests/test_evaluation.py | 134 ++++++++++++++++++++++++++--- 2 files changed, 266 insertions(+), 45 deletions(-) diff --git a/iqmapper/evaluation.py b/iqmapper/evaluation.py index 05435f1..a1dbaec 100644 --- a/iqmapper/evaluation.py +++ b/iqmapper/evaluation.py @@ -47,13 +47,19 @@ So the coupling has to come from somewhere else, in this order: 1. an explicit `coupling=[(u, v), ...]` argument; - 2. a saved session for that backend under `.iqmapper_sessions/`, which does - persist `edges_list` and `qubit_ids` (see `state.to_dict`); - 3. otherwise the run reports a clear error rather than guessing — an + 2. an explicit saved session file (`session_path=`, CLI `--session PATH`), + which must be a session for the requested backend and carry an + `edges_list`, or the run reports why it is not usable; + 3. a saved session for that backend found by scanning + `/.iqmapper_sessions/` (any `.json`) and `/` + (`*.qpusession.json`, where "Export Session" saves by default); + 4. otherwise the run reports a clear error rather than guessing — an invented topology would produce numbers that look real and mean nothing. -Save a session once for the backend you want to evaluate and every cached -calibration for it becomes replayable. +Sessions persist `backend_name`, `edges_list` and `qubit_ids` (see +`state.to_session_dict`). Save a session once for the backend you want to +evaluate and every cached calibration for it becomes replayable; if it was +saved elsewhere, pass it with `--session`. The gate arrays are positional, so the edges must be the backend's own edge list in the app's order (`data._generate_ibm`: `coupling_map.get_edges()`, @@ -66,7 +72,8 @@ python -m iqmapper.evaluation ibm_boston --norb 8 12 16 --hybrid-k 1 2 prints the table and the suggested "Guided up to k" per norb, and writes both -to `.scratch/eval__.md`. `--scorer` defaults to `lqs`. +to `.scratch/eval__.md`. `--scorer` defaults to `lqs`; +`--session PATH` names the saved session to take the coupling map from. """ import argparse import json as _json @@ -92,6 +99,9 @@ #: Scorer names accepted by `compare_engines`, and the metric each reports. SCORERS = {'proxy': 'lqs_proxy', 'lqs': 'lqs'} +#: Extension "Export Session" gives a saved session. +SESSION_SUFFIX = '.qpusession.json' + # ── replaying a cached calibration as a backend/props pair ────────── @@ -356,7 +366,8 @@ def _best_lqs(result, k): def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, min_bridges=0, cache_dir=None, beam_width=200, circuit_score_fn=None, limit=None, coupling=None, - session_dir=None, scorer='proxy', hybrid_ks=()): + session_dir=None, scorer='proxy', hybrid_ks=(), + session_path=None): """Run both engines over the cached calibrations and report. Read-only and offline: reads the local calibration cache, never the @@ -373,6 +384,8 @@ def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, `circuit_score_fn` wins over both. hybrid_ks: thresholds at which to also run the hybrid engine; each adds a `hybrid k<=t` column. Empty = the two-engine table. + session_path: a saved session file to take the coupling map from, + instead of scanning for one. Ignored when `coupling` is given. """ if scorer not in SCORERS: raise ValueError(f"scorer={scorer!r}; expected one of " @@ -397,16 +410,19 @@ def compare_engines(backend_name, dates=None, norbs=DEFAULT_NORBS, top_n=3, rows, errors = [], [] # The cache has no topology; resolve it once for the whole run. session_ids = None + if coupling is None and session_path is not None: + try: + coupling, session_ids = _session_from_path(backend_name, + session_path) + except ValueError as exc: + errors.append(f'No coupling map for {backend_name}: {exc}') + return Report(backend_name, [], errors, metric, hybrid_ks) if coupling is None: topology = _session_topology(backend_name, session_dir) if topology is not None: coupling, session_ids = topology if coupling is None: - errors.append( - f'No coupling map for {backend_name}: the calibration cache ' - f'stores only property arrays. Pass coupling=[(u, v), ...] or ' - f'save a session for this backend so .iqmapper_sessions/ ' - f'carries its edges_list.') + errors.append(_no_session_message(backend_name, session_dir)) return Report(backend_name, [], errors, metric, hybrid_ks) for stamp in stamps: @@ -464,43 +480,130 @@ def _unpack(snapshot): def coupling_from_sessions(backend_name, session_dir=None): """Recover a coupling map for `backend_name` from a saved session. - Sessions persist `edges_list` (and `qubit_ids`) via `state.to_dict`, so one - saved session makes every cached calibration for that backend replayable. - Returns a list of (u, v), or None when nothing matches. + Sessions persist `edges_list` (and `qubit_ids`) via + `state.to_session_dict`, so one saved session makes every cached + calibration for that backend replayable. Returns a list of (u, v), or None + when nothing matches. """ topology = _session_topology(backend_name, session_dir) return None if topology is None else topology[0] -def _session_topology(backend_name, session_dir=None): - """`(edges, qubit_ids)` from the first matching saved session, or None. +def _session_backend(payload): + """The backend a session belongs to. `to_session_dict` writes + `backend_name`; `active_backend_name` is accepted as well.""" + return str(payload.get('backend_name') + or payload.get('active_backend_name') or '') - `qubit_ids` is None when the session does not carry it. - """ - directory = session_dir or os.path.join(os.getcwd(), '.iqmapper_sessions') + +def _read_session(path): + """A saved session as a dict. Raises ValueError saying what is wrong.""" + from .export import MAX_IMPORT_BYTES try: - names = sorted(os.listdir(directory)) - except OSError: + size = os.path.getsize(path) + except OSError as exc: + raise ValueError(f'cannot read session file {path} ({exc}).') from exc + if size > MAX_IMPORT_BYTES: + raise ValueError(f'session file {path} is larger than ' + f'{MAX_IMPORT_BYTES // 1_048_576} MB.') + try: + with open(path, 'r', encoding='utf-8') as fh: + payload = _json.load(fh) + except (OSError, ValueError) as exc: + raise ValueError(f'{path} is not a readable session file ' + f'({exc}).') from exc + if not isinstance(payload, dict): + raise ValueError(f'{path} is not a session file.') + return payload + + +def _topology_of(payload): + """`(edges, qubit_ids)` from a session, or None without an edges_list.""" + edges = payload.get('edges_list') or [] + if not edges: return None - for name in names: - if not name.endswith('.json'): + ids = payload.get('qubit_ids') + return ([tuple(int(x) for x in e) for e in edges], + [str(q) for q in ids] if ids else None) + + +def _session_from_path(backend_name, path): + """`(edges, qubit_ids)` from one named session file. + + Raises ValueError when the file is unreadable, belongs to another backend, + or carries no edges_list. + """ + payload = _read_session(path) + found = _session_backend(payload) + if found != str(backend_name): + raise ValueError(f'{path} is a session for ' + f'{found or "no named backend"}, not {backend_name}.') + topology = _topology_of(payload) + if topology is None: + raise ValueError(f'{path} is a session for {backend_name} but has no ' + f'edges_list; save it again with the backend ' + f'connected.') + return topology + + +def _session_dirs(session_dir=None): + """(managed session directory, working directory) — where to scan.""" + return (session_dir or os.path.join(os.getcwd(), '.iqmapper_sessions'), + os.getcwd()) + + +def _session_files(session_dir=None): + """Candidate session files: any `.json` in the managed directory, then + `*.qpusession.json` in the working directory. Sorted, deduplicated.""" + managed, cwd = _session_dirs(session_dir) + out, seen = [], set() + for directory, any_json in ((managed, True), (cwd, False)): + try: + names = sorted(os.listdir(directory)) + except OSError: continue + for name in names: + if not (name.endswith(SESSION_SUFFIX) + or (any_json and name.endswith('.json'))): + continue + path = os.path.realpath(os.path.join(directory, name)) + if path not in seen and os.path.isfile(path): + seen.add(path) + out.append(path) + return out + + +def _session_topology(backend_name, session_dir=None): + """`(edges, qubit_ids)` from the first matching saved session, or None. + + `qubit_ids` is None when the session does not carry it. Unreadable files, + other backends' sessions and sessions without an edges_list are skipped. + """ + for path in _session_files(session_dir): try: - with open(os.path.join(directory, name), 'r', - encoding='utf-8') as fh: - payload = _json.load(fh) - except Exception: + payload = _read_session(path) + except ValueError: continue - if str(payload.get('active_backend_name') or '') != str(backend_name): + if _session_backend(payload) != str(backend_name): continue - edges = payload.get('edges_list') or [] - if edges: - ids = payload.get('qubit_ids') - return ([tuple(int(x) for x in e) for e in edges], - [str(q) for q in ids] if ids else None) + topology = _topology_of(payload) + if topology is not None: + return topology return None +def _no_session_message(backend_name, session_dir=None): + """The error for a run with no coupling map: where it looked, and how + to point it at a session saved somewhere else.""" + managed, cwd = _session_dirs(session_dir) + return (f'No coupling map for {backend_name}: the calibration cache ' + f'stores only property arrays, and no saved session for this ' + f'backend with an edges_list was found in {managed} or in {cwd} ' + f'(*{SESSION_SUFFIX}). Save a session for {backend_name} in the ' + f'app and pass it with --session PATH (session_path= in ' + f'compare_engines), or pass coupling=[(u, v), ...].') + + def _compare_one(stamp, norb, backend, props, top_n, min_bridges, beam_width, scorer, errors, hybrid_ks=()): """One (date, norb): run the engines, emit a row per stratum.""" @@ -567,6 +670,9 @@ def main(argv=None): parser.add_argument('--session-dir', default=None, help='where to look for a saved session carrying the ' 'coupling map (default .iqmapper_sessions)') + parser.add_argument('--session', default=None, metavar='PATH', + help='saved session file (.qpusession.json) for this ' + 'backend to take the coupling map from') parser.add_argument('--scorer', choices=sorted(SCORERS), default='lqs', help='lqs = the app\'s circuit-level LQS (default); ' 'proxy = product score') @@ -583,7 +689,8 @@ def main(argv=None): beam_width=args.beam_width, limit=args.limit, session_dir=args.session_dir, scorer=args.scorer, - hybrid_ks=tuple(args.hybrid_k)) + hybrid_ks=tuple(args.hybrid_k), + session_path=args.session) markdown = (report.to_markdown() + '\n' + format_suggestion(suggest_guided_max_k(report, args.tol))) print(markdown) diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py index 2fce77a..54c5158 100644 --- a/tests/test_evaluation.py +++ b/tests/test_evaluation.py @@ -12,6 +12,12 @@ from iqmapper import evaluation as ev +@pytest.fixture(autouse=True) +def _isolated_cwd(tmp_path, monkeypatch): + """The session scan reads the working directory; keep it hermetic.""" + monkeypatch.chdir(tmp_path) + + # ── a synthetic cache ─────────────────────────────────────────────── def _ladder_edges(n_rungs): @@ -54,16 +60,19 @@ def _write_cache(tmp_path, backend, stamps, n_rungs=8): _data._CACHE_DIR = old -def _write_session(session_dir, backend, edges, n_qubits): - os.makedirs(session_dir, exist_ok=True) - payload = { - 'active_backend_name': backend, - 'qubit_ids': [str(i) for i in range(n_qubits)], - 'edges_list': [list(e) for e in edges], - } - with open(os.path.join(session_dir, 'sess.json'), 'w', - encoding='utf-8') as fh: - json.dump(payload, fh) +def _write_session(session_dir, backend, edges, n_qubits, + name='sess.qpusession.json'): + """A session saved the way the app saves one: a real SessionState, + serialised by `to_session_dict` through `save_session_to_path`.""" + from iqmapper.export.session import save_session_to_path + from iqmapper.state import SessionState + state = SessionState() + state.active_backend_name = backend + state.qubit_ids = [str(i) for i in range(n_qubits)] + state.edges_list = [tuple(e) for e in edges] + path = os.path.join(str(session_dir), name) + save_session_to_path(state, path) + return path # ── 8. the harness ────────────────────────────────────────────────── @@ -395,3 +404,108 @@ def test_cli_prints_the_suggestion_and_takes_the_new_flags( assert 'hybrid k<=1' in printed assert 'Suggested "Guided up to k":' in printed assert '- norb 5:' in printed + + +# ── finding a real saved session ──────────────────────────────────── + +def test_a_real_session_is_keyed_by_backend_name(tmp_path): + path = _write_session(tmp_path / 'any', 'ibm_fixture', [(0, 1)], 2) + with open(path, encoding='utf-8') as fh: + payload = json.load(fh) + assert payload['backend_name'] == 'ibm_fixture' + assert 'active_backend_name' not in payload + + +def test_session_path_is_used_directly(tmp_path): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + path = _write_session(tmp_path / 'elsewhere' / 'deep', backend, edges, 24, + name='mine.qpusession.json') + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, session_path=path, + beam_width=50) + assert not report.errors, report.errors + assert report.rows + + +def test_a_session_in_the_working_directory_is_found(tmp_path): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + _write_session(tmp_path, backend, edges, 24, + name='my_session.qpusession.json') # app default + assert ev.coupling_from_sessions(backend) == [tuple(e) for e in edges] + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, beam_width=50) + assert not report.errors, report.errors + assert report.rows + + +def test_the_working_directory_scan_reads_only_session_files(tmp_path): + backend = 'ibm_fixture' + path = _write_session(tmp_path, backend, [(0, 1)], 2, + name='my_session.qpusession.json') + os.rename(path, tmp_path / 'notes.json') + assert ev.coupling_from_sessions(backend) is None + + +def test_a_session_for_another_backend_is_refused(tmp_path): + backend = 'ibm_fixture' + _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + path = _write_session(tmp_path / 'x', 'ibm_other', [(0, 1)], 2) + report = ev.compare_engines(backend, norbs=(4,), cache_dir=tmp_path, + session_path=path) + assert report.rows == [] + assert 'is a session for ibm_other, not ibm_fixture' in report.errors[0] + # The scan skips it rather than using another chip's topology. + _write_session(tmp_path, 'ibm_other', [(0, 1)], 2, + name='other.qpusession.json') + assert ev.coupling_from_sessions(backend) is None + + +def test_a_session_without_edges_is_refused(tmp_path): + backend = 'ibm_fixture' + _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + path = _write_session(tmp_path / 'x', backend, [], 0) + report = ev.compare_engines(backend, norbs=(4,), cache_dir=tmp_path, + session_path=path) + assert report.rows == [] + assert 'has no edges_list' in report.errors[0] + + +def test_a_missing_session_file_is_reported(tmp_path): + report = ev.compare_engines('ibm_fixture', norbs=(4,), cache_dir=tmp_path, + session_path=str(tmp_path / 'nope.json')) + assert report.rows == [] + assert 'cannot read session file' in report.errors[0] + + +def test_nothing_found_says_how_to_pass_a_session(tmp_path): + backend = 'ibm_fixture' + _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + report = ev.compare_engines(backend, norbs=(4,), cache_dir=tmp_path) + message = report.errors[0] + assert '--session PATH' in message and 'session_path=' in message + assert '.iqmapper_sessions' in message and str(tmp_path) in message + + +def test_the_legacy_key_is_still_accepted(tmp_path): + directory = tmp_path / '.iqmapper_sessions' + directory.mkdir() + (directory / 'old.json').write_text(json.dumps({ + 'active_backend_name': 'ibm_fixture', 'edges_list': [[0, 1]]}), + encoding='utf-8') + assert ev.coupling_from_sessions('ibm_fixture') == [(0, 1)] + + +def test_cli_takes_a_session_path(tmp_path, capsys, monkeypatch): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + path = _write_session(tmp_path / 'saved', backend, edges, 24) + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + code = ev.main([backend, '--norb', '4', '--top-n', '2', + '--min-bridges', '1', '--beam-width', '50', + '--session', path, '--out-dir', str(tmp_path / 'out')]) + assert code == 0 + printed = capsys.readouterr().out + assert '## Errors' not in printed + assert '| ' + '2026-09-01T00:00:00Z' in printed From 3a8fc2a296f6ec45e5eeb334616df456c477ccc7 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Mon, 5 Oct 2026 23:35:58 -0400 Subject: [PATCH 44/66] Release prep: CI workflow, badge and URLs to MIQuLab, ignore exported sessions, docs check --- .github/workflows/tests.yml | 30 +++++++++++++++++ .gitignore | 3 ++ CHANGELOG.md | 66 +++++++++++++++++++++++-------------- CODE_OVERVIEW.md | 4 +-- README.md | 24 +++++++++----- 5 files changed, 92 insertions(+), 35 deletions(-) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..2de9210 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,30 @@ +name: tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - name: Install + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + - name: Test + run: python -m pytest -q diff --git a/.gitignore b/.gitignore index 6e5589e..4346454 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,10 @@ htmlcov/ # iqmapper runtime data (never commit) .qpu_calibration_cache/ .iqmapper_sessions/ +.iqmapper_styles/ iqmapper/.qpu_calibration_cache/ iqmapper/.iqmapper_sessions/ +*.qpusession.json +*.qpustyle.json .scratch/ .ipynb_checkpoints/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ce4e1f..037f4ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Opt-in real-time benchmarking (`iqmapper.benchmark`, extra - `pip install "i-qmapper[benchmark]"`): three tiers that re-measure the + `pip install "i-qmapper[benchmark]"`): three levels that re-measure the candidate qubits and edges with `qiskit-experiments` and feed the result back as a "measured" calibration epoch, so the heatmap, LQS, re-ranking and export all read fresh numbers. Never automatic, never inside the multi-QPU @@ -16,45 +16,61 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). layouts / sweep candidates / whole QPU / a custom qubit list) and, in inter-QPU mode, a QPU 1 | QPU 2 selector. The experiment plan is composite (one `ParallelExperiment` per kind, edge-coloured layers for two-qubit RB), - so a full-chip Level 3 is ~134 circuits rather than ~43,400, and is split + so a full-chip Level 3 stays small enough for IBM to accept, and is split across jobs when it would exceed IBM's per-job shot limit. A rejected or errored job now reports IBM's own message with the job ids, and a run that measured nothing is reported as a failure instead of being applied and labelled "measured". Measured values are checked against the reported - calibration after every run; a systematic offset (median more than 2x away) + calibration after every run; a systematic offset (median ratio outside + 0.5x–2x) is treated as an estimator mismatch and the epoch is applied in relative mode, preserving per-element ratios so outlying couplers still stand out. Two-qubit RB now subtracts the measured single-qubit error rates, and a calibration-check mode separates estimator bias from crosstalk. -- Stratified ancilla sweep: a single VF2 solve at `k_max` feeding a - bridge-subtraction cascade down to `k_min`, with a hybrid mode, a shuffled - search for hard instances, and region-diversity selection across the chip. -- Stability filter with an always-on quality floor, so layouts that score well - on one calibration epoch but drift across neighbouring ones are rejected. -- Multi-circuit sweep: sequential orchestration over several circuits with - replan-from-step to recover a run without restarting it. +- Stratified ancilla sweep (the default, exhaustive engine): one VF2 solve at + the maximum ancilla count feeding a bridge-subtraction cascade down to the + minimum, plus a direct search per ancilla count ("Deep search per ancilla + count", on by default), a shuffled search order so a capped search samples + the whole chip, and region-diversity selection ("Prefer diverse regions"). +- Diverse enumeration (on by default): layouts that are near-copies of one + already kept no longer use up the search cap, so a capped search spreads + across the chip instead of filling up with variations of the first region + it finds. +- Guided search engine (opt-in via "Search engine"; Exhaustive stays the + default): a calibration-led beam search that grows layouts on the + best-calibrated qubits, then polishes the finalists with small local moves + (swap a bridge or chain-end qubit, shift a chain by one) kept only when they + raise the circuit-level LQS. +- Opt-in stability filter that excludes qubits volatile across the cached + calibration history, and an always-on quality floor (3σ by default, 0 turns + it off) that removes outlier qubits from every search. +- Multi-circuit sweep: places several circuits one after another; picking a + different layout for one circuit re-plans the circuits after it. - Multi-QPU scan across the available backends, with one-click inter-QPU handoff that reopens the chosen layout on the second QPU. - Epoch-consistent scoring: fidelity and ranking read a single pinned calibration epoch, so comparisons within a sweep stay commensurable. -- Hybrid search engine: guided search for low ancilla counts, where the +- Hybrid search engine (opt-in; the default stays exhaustive): guided search + for ancilla counts up to a threshold you set ("Guided up to k"), where the exhaustive search hits its cap and only ranks a sample, and the exhaustive - search above a threshold you set ("Guided up to k"). -- Joint multi-circuit planner: keeps several placement plans at once instead - of placing each circuit greedily, so the first circuit no longer takes a - region the next one needed. Never worse than the sequential planner, uses - the selected search engine, and reports couplers shared by two circuits at - buffer 0 (with an optional penalty to avoid them). -- Engine comparison harness (`python -m iqmapper.evaluation`) now ranks with - the app's real circuit-level LQS, rebuilt for every cached calibration - (`--scorer lqs`, the new default; `proxy` keeps the product score). It can - add a hybrid-engine column (`--hybrid-k`) and prints the suggested + search above it. +- Joint multi-circuit planner (opt-in; Sequential stays the default): keeps + several placement plans at once instead of placing each circuit greedily, + so the first circuit no longer takes a region the next one needed. Never + worse than the sequential planner, uses the selected search engine, and + reports couplers shared by two circuits at buffer 0 (with an optional + penalty to avoid them). +- Engine comparison harness (`python -m iqmapper.evaluation`): replays the + search engines over the cached calibrations, offline, and ranks with the + app's real circuit-level LQS rebuilt for every calibration (`--scorer lqs`, + the default; `proxy` uses the product score). It takes the coupling map + from a saved session (`--session PATH`, or found in the working folder), + can add a hybrid-engine column (`--hybrid-k`), and prints the suggested "Guided up to k" for each orbital count (`--tol` sets how far guided may trail and still count). - -### Fixed -- Batch scan scored every backend's layouts with the active backend's - calibration; each backend is now scored with its own. +- Shorter UI messages: status lines, notices and tooltips say what happened + in one short sentence, and each is explained in the README section + "Understanding the messages". ## [0.0.5] — 2026-08 diff --git a/CODE_OVERVIEW.md b/CODE_OVERVIEW.md index c6c8b7b..d762bfe 100644 --- a/CODE_OVERVIEW.md +++ b/CODE_OVERVIEW.md @@ -110,8 +110,8 @@ at runtime gets its own `Layout(...)`, and its UI test asserts it is not ## Tests -`tests/` — 736 tests in 68 files, deterministic and fully offline (no QPU, no -network, no credentials). A few skip when an optional dependency is missing: +`tests/` — deterministic and fully offline (no QPU, no network, no +credentials). A few skip when an optional dependency is missing: the QPY round-trip without qiskit, and `test_benchmark_integration.py` without the `[benchmark]` extra. Coverage concentrates on the pure logic: the search engines and planners (on synthetic lattices from diff --git a/README.md b/README.md index 6634a17..83166ca 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Interactive, noise-aware qubit layout selection for IBM Quantum hardware — see your device, understand its errors, and place your circuit where it will actually run well.** -[![tests](https://github.com/mbazayeva/i-qmapper/actions/workflows/tests.yml/badge.svg)](https://github.com/mbazayeva/i-qmapper/actions/workflows/tests.yml) +[![tests](https://github.com/MIQuLab/i-qmapper/actions/workflows/tests.yml/badge.svg)](https://github.com/MIQuLab/i-qmapper/actions/workflows/tests.yml) [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-green.svg)](LICENSE) [![arXiv](https://img.shields.io/badge/arXiv-2606.27508-b31b1b.svg)](https://arxiv.org/abs/2606.27508) @@ -77,18 +77,23 @@ Install from [PyPI](https://pypi.org/project/i-qmapper/): ```bash pip install i-qmapper -pip install "i-qmapper[png]" -pip install "i-qmapper[png,timelapse]" -pip install "i-qmapper[benchmark]" +``` + +Optional extras, combinable (e.g. `"i-qmapper[png,timelapse]"`): + +```bash +pip install "i-qmapper[png]" # publication PNG export (kaleido) +pip install "i-qmapper[timelapse]" # time-lapse GIF/MP4 export (imageio, imageio-ffmpeg) +pip install "i-qmapper[benchmark]" # real-time benchmarking (qiskit-experiments) ``` ### From source (development) ```bash -git clone https://github.com/MIQuLab/i-qmapper +git clone https://github.com/MIQuLab/i-qmapper cd i-qmapper -pip install -e ".[dev]" -pytest -q +pip install -e ".[dev]" +pytest -q ``` ## Set up your IBM Quantum account @@ -453,11 +458,14 @@ iqmapper/ ├── data.py # calibration fetch + per-user cache ├── plot.py # device graph & heatmap rendering ├── auto_lucj.py # LUCJ auto-placement + layout error scoring +├── ancilla_sweep.py, guided_search.py, engine_select.py, multi_sweep.py, +│ joint_plan.py, qpu_scan.py … # layout search engines and planners +├── benchmark.py # opt-in real-time benchmarking ├── stability.py # multi-day stability analysis ├── state.py # session state, undo/redo, (de)serialization ├── export/ # scoring (LQS), layout I/O, codegen, PNG/analysis export └── ui/ # ipywidgets panels (builder, time, history, analysis, …) -tests/ # 183 tests, offline, no QPU required +tests/ # offline, no QPU required — run with: python -m pytest -q ``` For a guided tour of the modules and data flow, see From 202df1f575f9a2d36686cd2d07d33fb0c644eef4 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 6 Oct 2026 15:11:18 -0400 Subject: [PATCH 45/66] Batch handoff: draw every circuit on QPU 2, report outcomes next to the open button --- iqmapper/ui/inter_qpu.py | 104 +++++++++++++---- iqmapper/ui/lucj_panel.py | 40 +++++-- tests/test_batch_handoff.py | 210 +++++++++++++++++++++++++++++++++++ tests/test_floor_batch_ui.py | 3 +- tests/test_scan_ui.py | 3 +- tests/test_scan_ui_pass.py | 3 +- 6 files changed, 331 insertions(+), 32 deletions(-) create mode 100644 tests/test_batch_handoff.py diff --git a/iqmapper/ui/inter_qpu.py b/iqmapper/ui/inter_qpu.py index 19a2f1a..56767da 100644 --- a/iqmapper/ui/inter_qpu.py +++ b/iqmapper/ui/inter_qpu.py @@ -136,6 +136,7 @@ def setup_inter_qpu(ctx): _pre_inter_fig_size = [None, None] # (width, height) before toggling on _qpu_toggle = [None] # ToggleButtons for QPU1/QPU2 sidebar swap _pending_handoff = [None] # (backend_name, candidate) staged from a scan pick + _last_paint_err = [None] # candidate-paint failure of the last connect _qpu2_content_box = [None] # Container holding the QPU2 sidebar # ── Toggle handler ────────────────────────────────────────── @@ -309,25 +310,55 @@ def _apply_one_to_slot(d, candidate): d['styles'][q] = {'fill': fills[role], 'line': line, 'width': 2, 'text_color': '#000000'} - def _apply_candidate_to_state(s2, candidate): + def _clear_slot(d): + d['alpha'] = []; d['beta'] = []; d['other'] = [] + d['qubits'] = []; d['ancilla'] = []; d['styles'] = {} + + def _set_circuit_count(w2, n): + """Show exactly `n` circuits on QPU 2: a batch turns multi-circuit + mode on with n circuits, a single candidate turns it off. Without this + QPU 2 draws C1 only and a batch's other circuits stay invisible.""" + intra = getattr(w2, 'intra_qpu_mode', None) + count = getattr(w2, 'num_circuits', None) + if intra is None or count is None: + return + if n > 1: + count.value = min(n, getattr(count, 'max', n)) + intra.value = True + else: + intra.value = False + + def _apply_candidate_to_state(s2, candidate, w2=None): """Pre-load scan-selected candidate(s) onto QPU-2's layout state so the secondary map renders from its first paint. A single candidate lands on C1; a LIST (a multi-circuit batch) lands on C1..Cn, one per slot — the - list form is what the batch-scan handoff sends.""" - cands = candidate if isinstance(candidate, (list, tuple)) else [candidate] - for i, cand in enumerate(cands): - d = s2.layouts_data.get(i) - if d is not None: - _apply_one_to_slot(d, cand) - - def stage_remote_candidate(backend_name, candidate): + list form is what the batch-scan handoff sends. Every other slot is + cleared, so circuits left over from an earlier, larger batch go, and + QPU 2's circuit count follows the payload (`w2`, when given).""" + cands = list(candidate) if isinstance(candidate, (list, tuple)) \ + else [candidate] + for i in sorted(s2.layouts_data): + if i < len(cands): + _apply_one_to_slot(s2.layouts_data[i], cands[i]) + else: + _clear_slot(s2.layouts_data[i]) + if w2 is not None: + _set_circuit_count(w2, len(cands)) + + def stage_remote_candidate(backend_name, candidate, report=None): """Scan-side entry point: reveal the inter-QPU panel, prefill the QPU-2 backend dropdown, and stage the candidate so it renders as soon as the (user-clicked) connect completes.""" if not chk_inter_qpu.value: chk_inter_qpu.value = True # fires _on_toggle_inter_qpu - with contextlib.suppress(Exception): + try: dd_backend_qpu2.value = backend_name + except Exception as exc: # noqa: BLE001 - reported + _log.warning("QPU-2 backend dropdown rejected %s: %s", + backend_name, exc) + if report is not None: + report('warn', f"{backend_name} is not in the QPU 2 list " + f"({exc})") _pending_handoff[0] = (backend_name, candidate) # Prominent one-liner explaining the half-open state until the # user clicks Connect. Replaced by the connect status once connected. @@ -348,7 +379,8 @@ def stage_remote_candidate(backend_name, candidate): # connect), defined after the connect handler below. Bound via a trampoline # so this assignment can precede _auto_connect's definition. if handoff_cell is not None: - handoff_cell[0] = lambda bn, cand: _auto_connect(bn, cand) + handoff_cell[0] = (lambda bn, cand, report=None: + _auto_connect(bn, cand, report)) # ── Connect-QPU2: worker-safe FETCH + main-thread PAINT ────── # Every ipywidgets / plotly FigureWidget mutation (build_mapper_ui, @@ -409,16 +441,18 @@ def _connect_qpu2_paint(backend_name, fetched): # clear_all_layouts()). pend = _pending_handoff[0] paint_err = None + _last_paint_err[0] = None if pend is not None and pend[0] == backend_name: # Narrow try (was a blanket suppress): a candidate-paint failure # must never crash the connect, but it must NOT be hidden either. # Log it and surface it on the QPU-2 status below. try: - _apply_candidate_to_state(s2, pend[1]) + _apply_candidate_to_state(s2, pend[1], w2) from .. import plot as _plot _plot.refresh_plot(f2, s2, w2) except Exception as _pe: # noqa: BLE001 - reported below paint_err = _pe + _last_paint_err[0] = _pe _log.warning("QPU-2 candidate paint failed for %s: %s", backend_name, _pe, exc_info=True) _pending_handoff[0] = None @@ -537,21 +571,31 @@ def _on_connect_qpu2(b): btn_connect_qpu2.on_click(_on_connect_qpu2) # ── one-click auto-connect on a scan-candidate pick ─────── - def _staged_with_error(backend_name, candidate, err): + def _staged_with_error(backend_name, candidate, err, report=None): """Failure → back to today's STAGED state (re-stage so a manual Connect re-applies the candidate) plus an esc()'d one-line error. The user loses nothing; one click recovers.""" - stage_remote_candidate(backend_name, candidate) + stage_remote_candidate(backend_name, candidate, report) lbl_qpu2_status.value = lbl_qpu2_status.value + ( f"
" f"❌ auto-connect failed: {esc(str(err))}
") + if report is not None: + report('error', f"could not open {backend_name} on QPU 2: {err}") + + def _n_circuits(candidate): + return len(candidate) if isinstance(candidate, (list, tuple)) else 1 - def _auto_connect(backend_name, candidate): + def _auto_connect(backend_name, candidate, report=None): """The scan handoff hook (replaces bare staging): stage, then drive the - SAME Connect-QPU2 handler automatically. Idempotent + race-guarded.""" + SAME Connect-QPU2 handler automatically. Idempotent + race-guarded. + + `report(level, text)`, when given, receives every outcome — started, + opened, applied, failed — so the caller can show it next to the button + that was clicked; the QPU-2 status label is updated as before.""" + n = _n_circuits(candidate) # Always stage first (reveal panel, prefill dropdown, preload candidate, # staged banner) — identical to the prior staging behaviour and the fallback. - stage_remote_candidate(backend_name, candidate) + stage_remote_candidate(backend_name, candidate, report) # Same backend already connected as QPU-2 → skip the reconnect, # just apply the candidate and repaint. _state2[0] holds the connected @@ -564,7 +608,7 @@ def _auto_connect(backend_name, candidate): # and surfaced, not hidden — see the first-connect path. paint_err = None try: - _apply_candidate_to_state(s2, candidate) + _apply_candidate_to_state(s2, candidate, _w2[0]) if _fig2[0] is not None and _w2[0] is not None: from .. import plot as _plot _plot.refresh_plot(_fig2[0], s2, _w2[0]) @@ -580,11 +624,21 @@ def _auto_connect(backend_name, candidate): + ("" if paint_err is None else f"
" f"⚠ candidate paint failed: {esc(str(paint_err))}
")) + if report is not None: + if paint_err is None: + report('ok', f"applied to {backend_name} on QPU 2 · " + f"{n} circuit(s)") + else: + report('warn', f"{backend_name} on QPU 2, but painting " + f"failed: {paint_err}") return # A connect already in flight → the staging above is enough; # don't launch a second connect. if _connect_in_flight[0]: + if report is not None: + report('info', f"a QPU 2 connect is running; {backend_name} " + f"is staged") return _connect_in_flight[0] = True @@ -594,6 +648,9 @@ def _auto_connect(backend_name, candidate): f"padding:6px 10px;border-radius:4px;border:1px solid #ffe08a;" f"margin:3px 0;font-weight:bold;'>📡 connecting " f"{esc(str(backend_name))}…") + if report is not None: + report('info', f"opening {backend_name} on QPU 2 · " + f"{n} circuit(s)…") def _finish(): _connect_in_flight[0] = False @@ -607,11 +664,18 @@ def _paint(fetched): # runs on the main loop (marshalled) _finish() err = _connect_qpu2_paint(backend_name, fetched) if err: # paint reported a failure string - _staged_with_error(backend_name, candidate, err) + _staged_with_error(backend_name, candidate, err, report) + elif report is not None: + if _last_paint_err[0] is None: + report('ok', f"{backend_name} open on QPU 2 · " + f"{n} circuit(s)") + else: + report('warn', f"{backend_name} on QPU 2, but painting " + f"failed: {_last_paint_err[0]}") def _error(exc): # the worker fetch itself raised _finish() - _staged_with_error(backend_name, candidate, exc) + _staged_with_error(backend_name, candidate, exc, report) _spawn_bg(lambda: _connect_qpu2_fetch(backend_name), on_done=_paint, on_error=_error) diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 250947d..284ab9f 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -1282,16 +1282,35 @@ def _render_targets(targets): f"
" f"{line}
")] - def _stage_handoff(backend_name, candidate): + _HANDOFF_STYLE = {'ok': ('✅', '#1e8449'), 'info': ('📡', '#555'), + 'warn': ('⚠', '#e67e22'), 'error': ('❌', '#e74c3c')} + + def _handoff_reporter(label): + """`report(level, text)` writing one short line into `label` — the + status next to the button that was clicked.""" + def _report(level, text): + icon, colour = _HANDOFF_STYLE.get(level, _HANDOFF_STYLE['info']) + label.value = (f"" + f"{icon} {esc(str(text))}") + return _report + + def _stage_handoff(backend_name, candidate, report): + """Open a scan pick (one candidate, or a batch list) on QPU 2. + + Every outcome goes to `report`, so it shows next to the button that + was clicked; a failure is logged as well, never swallowed. A handoff + failure must not break the scan UI, so nothing is re-raised.""" hook = inter_qpu_handoff[0] if inter_qpu_handoff else None if hook is None: - lbl_scan_progress.value = ( - "
Inter-QPU panel " - "unavailable — cannot open a remote candidate.
") + report('error', "QPU 2 panel unavailable here — open from " + "QPU 1's scan") return - # A handoff must never break the scan UI. - with contextlib.suppress(Exception): - hook(backend_name, candidate) + try: + hook(backend_name, candidate, report=report) + except Exception as exc: # noqa: BLE001 - reported + _log.warning("Opening %s on QPU 2 failed: %s", backend_name, exc, + exc_info=True) + report('error', f"could not open {backend_name} on QPU 2: {exc}") def _vintage_cell(vintage): """Calibration provenance. Scan scoring is always LIVE now, so @@ -1351,6 +1370,8 @@ def _scan_selector(rows, *, label_fn, detail_fn, open_ok_fn, payload_fn, det = HTML("") btn = Button(description='🔗 open on QPU 2', button_style='', layout=Layout(width='180px')) + status = HTML("") # handoff outcome, next to btn + report = _handoff_reporter(status) def _sync(idx): r = rows[idx] @@ -1370,11 +1391,12 @@ def _open(_b): return payload = payload_fn(r) if payload is not None: - _stage_handoff(r['name'], payload) # single candidate OR list + _stage_handoff(r['name'], payload, report) # one OR a list btn.on_click(_open) _sync(0) - return [dd, det, HBox([btn], layout=Layout(align_items='center'))] + return [dd, det, HBox([btn, status], + layout=Layout(align_items='center'))] def _scan_detail_line2(r): """Second detail line — the per-backend data the removed comparison diff --git a/tests/test_batch_handoff.py b/tests/test_batch_handoff.py new file mode 100644 index 0000000..4b5f88b --- /dev/null +++ b/tests/test_batch_handoff.py @@ -0,0 +1,210 @@ +"""Opening a scan pick on QPU 2: every circuit of a batch is drawn, the circuit +count follows the payload, and every outcome is reported next to the button +that was clicked. + +Headless: a real MapperUIBuilder with the real inter-QPU wiring; network, +device data and coordinates are stubbed, as in test_inter_qpu_handoff. +""" +import logging +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Button, Dropdown, HBox, HTML + +from test_floor_batch_ui import _ladder_backend, _sync_spawn + +N = 48 + + +def _build(monkeypatch): + import iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + edges = list(_ladder_backend('x').coupling_map.graph.edge_list()) + + def _fake_device(state, vendor, chip, date, prefetched_props=None): + return (list(range(N)), [0.0] * N, edges, [str(i) for i in range(N)], + np.full(N, 0.01), np.full(len(edges), 0.002)) + + monkeypatch.setattr('iqmapper.data.generate_device_data', _fake_device) + monkeypatch.setattr('iqmapper.connection._check_properties', + lambda b, n: (object(), None)) + monkeypatch.setattr('iqmapper.constants.resolve_coords', + lambda b: ([(i, 0) for i in range(N)], 'chip')) + + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + backends = {n: _ladder_backend(n) for n in ('ibm_a', 'ibm_b')} + state = SessionState() + for key, val in dict( + active_backend=object(), active_backend_name='ibm_here', + active_chip='chip', + active_service=SimpleNamespace(backend=lambda n: backends[n]), + available_backends=['ibm_a', 'ibm_b'], props_warning=None, + initial_props=object(), active_ansatz='lucj', active_vendor='IBM', + active_coords=[(i, 0) for i in range(N)], custom_colors=[], + cal_history_dates=['_seed_']).items(): + setattr(state, key, val) + b = MapperUIBuilder(state) + b.build() + + import iqmapper.ui as ui_pkg + real_build = ui_pkg.build_mapper_ui + qpu2 = {} + + def _capture(s2, is_secondary=False, return_widgets=False): + res = real_build(s2, is_secondary=is_secondary, + return_widgets=return_widgets) + qpu2.update(state=s2, fig=res[1], widgets=res[2]) + return res + + monkeypatch.setattr(ui_pkg, 'build_mapper_ui', _capture) + return b, backends, qpu2 + + +def _entry(base): + return {'alpha': [base, base + 1], 'beta': [base + 8, base + 9], + 'ancillas': [base + 16]} + + +def _qubits(entry): + return set(entry['alpha']) | set(entry['beta']) | set(entry['ancillas']) + + +def _painted(qpu2): + trace = next(t for t in qpu2['fig'].data + if 'markers' in (getattr(t, 'mode', '') or '') + and t.x is not None and len(t.x) == N) + return {i for i, c in enumerate(trace.marker.color) if c != '#ffffff'} + + +def _drawn(qpu2): + w = qpu2['widgets'] + return w.num_circuits.value if w.intra_qpu_mode.value else 1 + + +def _selector(box): + kids = list(box.children) + row = next(c for c in kids if isinstance(c, HBox)) + button = next(c for c in row.children if isinstance(c, Button)) + status = next(c for c in row.children if isinstance(c, HTML)) + return next(c for c in kids if isinstance(c, Dropdown)), button, status + + +def _batch_scan(monkeypatch, b, backends, norbs='4, 4'): + from iqmapper import qpu_scan as qs + from iqmapper.props_shim import CachedPropsShim + + def _get_props(backend): + edges = list(backend.coupling_map.graph.edge_list()) + return CachedPropsShim({'readout_error': np.full(N, 0.01)}, + {'cz_error': np.full(len(edges), 0.002)}, + edges, n_qubits=N, vintage='live') + + monkeypatch.setattr('iqmapper.props_shim.make_scan_get_props', + lambda state: _get_props) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in backends]) + b.intra_qpu_mode.value = True + b.lucj_multi_norbs.value = norbs + b.btn_scan_batch.click() + + +# ── every circuit of a batch is drawn ─────────────────────────────── + +def test_a_scanned_batch_opens_with_all_its_circuits(monkeypatch): + b, backends, qpu2 = _build(monkeypatch) + _batch_scan(monkeypatch, b, backends) + _dd, button, status = _selector(b.scan_batch_box) + button.click() + + s2 = qpu2['state'] + assert _drawn(qpu2) == 2 + second = {int(q) for role in ('alpha', 'beta', 'ancilla') + for q in s2.layouts_data[1][role]} + assert second and second <= _painted(qpu2), 'C2 is not on the map' + assert 'open on QPU 2 · 2 circuit(s)' in status.value + + +def test_a_batch_on_an_already_connected_backend_draws_all_circuits( + monkeypatch): + b, _backends, qpu2 = _build(monkeypatch) + hook = b._inter_qpu_handoff[0] + hook('ibm_a', _entry(0)) # single open first + before = _painted(qpu2) + seen = [] + hook('ibm_a', [_entry(0), _entry(24)], report=lambda *m: seen.append(m)) + assert _drawn(qpu2) == 2 + assert _qubits(_entry(24)) <= _painted(qpu2) + assert _painted(qpu2) != before + assert seen[-1] == ('ok', 'applied to ibm_a on QPU 2 · 2 circuit(s)') + + +# ── the circuit count follows the payload, both ways ──────────────── + +def test_a_smaller_batch_drops_the_extra_circuits(monkeypatch): + b, _backends, qpu2 = _build(monkeypatch) + hook = b._inter_qpu_handoff[0] + hook('ibm_a', [_entry(0), _entry(3), _entry(24)]) + assert _drawn(qpu2) == 3 + hook('ibm_a', [_entry(0), _entry(24)]) + assert _drawn(qpu2) == 2 + s2 = qpu2['state'] + assert all(not s2.layouts_data[2][role] + for role in ('alpha', 'beta', 'ancilla')) + assert not (_qubits(_entry(3)) - _qubits(_entry(0))) & _painted(qpu2) + + +def test_a_single_pick_after_a_batch_goes_back_to_one_circuit(monkeypatch): + b, _backends, qpu2 = _build(monkeypatch) + hook = b._inter_qpu_handoff[0] + hook('ibm_a', [_entry(0), _entry(24)]) + assert _drawn(qpu2) == 2 + hook('ibm_a', _entry(5)) + assert _drawn(qpu2) == 1 + assert _painted(qpu2) == _qubits(_entry(5)) + assert not qpu2['state'].layouts_data[1]['alpha'] + + +# ── outcomes are reported where the user clicked ─────────────────── + +def test_a_failing_hook_is_reported_next_to_the_button_and_logged( + monkeypatch, caplog): + b, backends, _qpu2 = _build(monkeypatch) + _batch_scan(monkeypatch, b, backends) + + def _boom(name, payload, report=None): + raise RuntimeError('panel gone') + + b._inter_qpu_handoff[0] = _boom + _dd, button, status = _selector(b.scan_batch_box) + with caplog.at_level(logging.WARNING, logger='iqmapper.ui.lucj_panel'): + button.click() + assert 'could not open ibm_a on QPU 2: panel gone' in status.value + assert any('panel gone' in r.getMessage() for r in caplog.records) + + +def test_a_missing_hook_is_reported_next_to_the_button(monkeypatch): + b, backends, _qpu2 = _build(monkeypatch) + _batch_scan(monkeypatch, b, backends) + b._inter_qpu_handoff[0] = None + _dd, button, status = _selector(b.scan_batch_box) + button.click() + assert 'QPU 2 panel unavailable here' in status.value + assert b.lbl_scan_progress.value == '' + + +def test_a_backend_missing_from_the_qpu2_list_is_logged_and_reported( + monkeypatch, caplog): + b, backends, qpu2 = _build(monkeypatch) + backends['ibm_new'] = _ladder_backend('ibm_new') # not in the dropdown + seen = [] + with caplog.at_level(logging.WARNING, logger='iqmapper.ui.inter_qpu'): + b._inter_qpu_handoff[0]('ibm_new', _entry(0), + report=lambda *m: seen.append(m)) + assert any(level == 'warn' and 'not in the QPU 2 list' in text + for level, text in seen) + assert any('ibm_new' in r.getMessage() for r in caplog.records) + assert seen[-1][0] == 'ok' # the connect still went ahead + assert _qubits(_entry(0)) <= _painted(qpu2) diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index eef1445..ce01be2 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -262,7 +262,8 @@ def test_batch_selector_handoff_payload(monkeypatch): _batch_result_row('ibm_hi', 0.61, 2)], 'n_scanned': 1, 'n_failed': 0, 'n_skipped': 0}) staged = [] - b._inter_qpu_handoff[0] = lambda name, payload: staged.append((name, payload)) + b._inter_qpu_handoff[0] = (lambda name, payload, report=None: + staged.append((name, payload))) b.lucj_multi_norbs.value = '8, 8' b.btn_scan_batch.click() diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index afd35b3..21e46fc 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -214,7 +214,8 @@ def test_scan_handoff_on_select(monkeypatch): b = _build(monkeypatch, marshal=lambda cb: cb()) _patch_scan(monkeypatch) staged = [] - b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) + b._inter_qpu_handoff[0] = (lambda name, cand, report=None: + staged.append((name, cand))) b.btn_scan_qpus.click() # Select the top QPU in the selector, then click its "open on QPU 2" button. diff --git a/tests/test_scan_ui_pass.py b/tests/test_scan_ui_pass.py index 593adfc..1cb73b4 100644 --- a/tests/test_scan_ui_pass.py +++ b/tests/test_scan_ui_pass.py @@ -205,7 +205,8 @@ def test_selector_open_drives_handoff_no_table(monkeypatch): b = _build(monkeypatch) _patch_one(monkeypatch, _sweep(0.73, 0.60), _FixedProps(0.653)) staged = [] - b._inter_qpu_handoff[0] = lambda name, cand: staged.append((name, cand)) + b._inter_qpu_handoff[0] = (lambda name, cand, report=None: + staged.append((name, cand))) b.btn_scan_qpus.click() assert not _has_table(b) From 6fd6ec319a6c3ea1aefed33fd4ab4801ff87f2de Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 6 Oct 2026 15:11:23 -0400 Subject: [PATCH 46/66] LQS: count each coupler once (authorized amendments to scoring.py and props_shim.py) --- iqmapper/export/scoring.py | 55 +++++++++++- iqmapper/props_shim.py | 25 +++--- tests/test_coupler_count.py | 172 ++++++++++++++++++++++++++++++++++++ tests/test_props_shim.py | 15 ++-- 4 files changed, 244 insertions(+), 23 deletions(-) create mode 100644 tests/test_coupler_count.py diff --git a/iqmapper/export/scoring.py b/iqmapper/export/scoring.py index 88a996d..012e5ab 100644 --- a/iqmapper/export/scoring.py +++ b/iqmapper/export/scoring.py @@ -2,10 +2,17 @@ export.scoring — Delta computation between calibration snapshots and heuristic circuit-fidelity estimation. Pure numerical; no I/O. """ +import logging + import numpy as np from . import OUTLIER_MIN_SAMPLES, OUTLIER_SIGMA +_log = logging.getLogger(__name__) + +#: Couplers already reported for direction-dependent error values. +_DIRECTION_MISMATCH_LOGGED = set() + # ═══════════════════════════════════════════════════════════════════════ # ERROR DELTA COMPUTATION @@ -42,6 +49,46 @@ def compute_error_delta(qp_a, gp_a, qp_b, gp_b): # ESTIMATED FIDELITY # ═══════════════════════════════════════════════════════════════════════ +def _missing(err): + return err is None or (isinstance(err, float) and np.isnan(err)) or ( + isinstance(err, np.floating) and np.isnan(err)) + + +def unique_couplers(gate_edges): + """One ``(id_u, id_v, error)`` per physical coupler, in first-seen order. + + Backends with a symmetric native 2Q gate (CZ) list every coupler in both + directions in their coupling map, and ``state.edges_list`` and the + positional gate arrays carry both entries. A coupler is one gate, so it is + scored once; counting both directions would square the gate factor on + those backends and make their scores incomparable with one-direction (ECR) + backends. When the two directions carry different finite errors, the + larger one is kept and the mismatch is logged once per coupler. A missing + (None / NaN) value never replaces a present one. + """ + out, index = [], {} + for u_id, v_id, err in gate_edges: + key = frozenset((u_id, v_id)) + i = index.get(key) + if i is None: + index[key] = len(out) + out.append((u_id, v_id, err)) + continue + u0, v0, prev = out[i] + if _missing(prev): + out[i] = (u0, v0, err) + elif _missing(err) or err == prev: + continue + else: + if key not in _DIRECTION_MISMATCH_LOGGED: + _DIRECTION_MISMATCH_LOGGED.add(key) + _log.info("Coupler %s-%s has different errors per direction " + "(%s, %s); scoring the larger.", u0, v0, prev, err) + if err > prev: + out[i] = (u0, v0, err) + return out + + def estimate_fidelity_core(layout_qubit_ids, readout_by_id, gate_edges, all_readout=None): """Pure product-form fidelity — the math of :func:`estimate_circuit_fidelity` @@ -55,6 +102,8 @@ def estimate_fidelity_core(layout_qubit_ids, readout_by_id, gate_edges, ids. NaN allowed (skipped). Missing ids are skipped. gate_edges: iterable of ``(id_u, id_v, cz_error)`` — the device couplings; those with BOTH endpoints in the layout set contribute. + Pass each coupler once (see :func:`unique_couplers`); a coupler + listed in both directions would be counted twice. all_readout: optional full readout array for device-mean outlier detection; ``None`` → no outliers. @@ -136,7 +185,8 @@ def estimate_circuit_fidelity(state, circuit_idx, mode='lucj'): 1. Assumes independent errors. Does not model crosstalk between simultaneous two-qubit gates or correlated readout errors. - 2. Counts each edge once. Overestimates fidelity for deep circuits + 2. Counts each coupler once, whichever directions the backend lists + (see ``unique_couplers``). Overestimates fidelity for deep circuits that fire the same CZ pair multiple times (e.g. LUCJ ansatzen with large bond-dimension parameters). A tighter upper bound would multiply ε_gate by the per-edge CZ count. @@ -204,5 +254,6 @@ def estimate_circuit_fidelity(state, circuit_idx, mode='lucj'): if i < len(cz_arr): gate_edges.append((u_id, v_id, cz_arr[i])) - return estimate_fidelity_core(qubit_ids, readout_by_id, gate_edges, + return estimate_fidelity_core(qubit_ids, readout_by_id, + unique_couplers(gate_edges), all_readout=re_arr) diff --git a/iqmapper/props_shim.py b/iqmapper/props_shim.py index 1c277cd..43bc35b 100644 --- a/iqmapper/props_shim.py +++ b/iqmapper/props_shim.py @@ -99,11 +99,9 @@ def __init__(self, qubit_props, gate_props, edges, self.n_qubits = n_qubits self._readout = qubit_props['readout_error'] gate_arr = gate_props[gate_key] - # Keep the RAW (edges, gate array) so score_layout can reproduce the - # C1 wrapper's EXACT edge surface — every coupling in the backend's - # own map (both directions, as edges_list carries them), paired - # positionally. Deduping here would halve the gate factors and inflate - # the product. + # Keep the RAW (edges, gate array), paired positionally, so + # score_layout reduces them exactly as the C1 wrapper does (one entry + # per coupler via export.scoring.unique_couplers). self._edges = [(int(u), int(v)) for (u, v) in edges] self._gate_arr = gate_arr # Deduped map for the direction-insensitive gate_error() the sweep's @@ -132,11 +130,11 @@ def gate_error(self, gate_name, pair): def score_layout(self, layout_qubit_ids): """Circuit-level fidelity for a layout on THIS backend, via the shared ``export.scoring.estimate_fidelity_core`` — the SAME edge surface as - the C1 wrapper (``estimate_circuit_fidelity``): every coupling among - the layout set, taken from the backend's OWN edge list (both - directions), so a scan candidate lands on exactly the C1 scale. + the C1 wrapper (``estimate_circuit_fidelity``): every coupler among + the layout set, taken from the backend's OWN edge list and counted + once, so a scan candidate lands on exactly the C1 scale. Returns the core dict (``None`` only if the layout is empty).""" - from .export.scoring import estimate_fidelity_core + from .export.scoring import estimate_fidelity_core, unique_couplers ids = list(layout_qubit_ids) if not ids: return None @@ -146,11 +144,10 @@ def score_layout(self, layout_qubit_ids): readout_by_id[q] = self._readout[q] except (IndexError, KeyError, TypeError): pass - # Full directed surface, positionally paired — mirrors the C1 wrapper's - # `for edge in edges_list` loop (which counts both directions). NOT the - # deduped self._gate, which would halve the factors and inflate. - gate_edges = [(u, v, self._gate_arr[i]) - for i, (u, v) in enumerate(self._edges)] + # The backend's own edges, positionally paired, reduced to one entry + # per coupler by the same helper the C1 wrapper uses. + gate_edges = unique_couplers([(u, v, self._gate_arr[i]) + for i, (u, v) in enumerate(self._edges)]) return estimate_fidelity_core(ids, readout_by_id, gate_edges, all_readout=self._readout) diff --git a/tests/test_coupler_count.py b/tests/test_coupler_count.py new file mode 100644 index 0000000..4f20e47 --- /dev/null +++ b/tests/test_coupler_count.py @@ -0,0 +1,172 @@ +"""LQS counts each physical coupler once. + +CZ backends (Heron) list every coupler in both directions in their coupling +map, and `state.edges_list` carries both; ECR backends (Eagle) list one. The +score of a layout must not depend on that. +""" +import logging +from types import SimpleNamespace + +import numpy as np +import pytest +import rustworkx + +from iqmapper import evaluation as ev +from iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.export import scoring +from iqmapper.export.scoring import estimate_circuit_fidelity, unique_couplers +from iqmapper.props_shim import CachedPropsShim + + +def _heavy_hex(d=7, seed=5): + graph = rustworkx.generators.heavy_hex_graph(d) + rng = np.random.default_rng(seed) + n = graph.num_nodes() + undirected = [tuple(e) for e in graph.edge_list()] + readout = 0.005 + 0.02 * rng.random(n) + err = {frozenset(e): 0.002 + 0.01 * rng.random() for e in undirected} + return n, undirected, readout, err + + +def _state(n, edges, readout, err): + """The app's state shape: positional gate array over `edges`.""" + return SimpleNamespace( + qubit_ids=[str(i) for i in range(n)], edges_list=list(edges), + qubit_props_data={'readout_error': np.asarray(readout)}, + gate_props_data={'cz_error': np.array([err[frozenset(e)] + for e in edges])}) + + +def _both(undirected): + return [e for u, v in undirected for e in ((u, v), (v, u))] + + +def _score(state, entry): + layout = {'alpha': [str(q) for q in entry['alpha']], + 'beta': [str(q) for q in entry['beta']], 'other': [], + 'ancilla': [str(q) for q in entry['ancillas']]} + fake = SimpleNamespace(layouts_data={0: layout}, **vars(state)) + return estimate_circuit_fidelity(fake, 0, 'lucj') + + +def _lucj_gates(entry): + a, b, anc = entry['alpha'], entry['beta'], entry['ancillas'] + gates = ([(a[j], a[j + 1]) for j in range(len(a) - 1)] + + [(b[j], b[j + 1]) for j in range(len(b) - 1)]) + for i, r in enumerate(anc): + gates += [(a[4 * i], r), (r, b[4 * i])] + return gates + + +def _backend(n, undirected): + graph = rustworkx.PyDiGraph() + for _ in range(n): + graph.add_node(None) + for u, v in undirected: + graph.add_edge(u, v, None) + graph.add_edge(v, u, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _Props: + def __init__(self, readout, err): + self.readout, self.err = readout, err + + def readout_error(self, q): + return float(self.readout[q]) + + def gate_error(self, name, edge): + return self.err[frozenset(edge)] + + +@pytest.fixture(scope='module') +def layout_case(): + n, undirected, readout, err = _heavy_hex() + res = sweep_ancilla_layouts(8, _backend(n, undirected), + _Props(readout, err), min_bridges=1, top_n=3) + entry = res['strata'][1][0] + return n, undirected, readout, err, entry + + +def test_both_directions_and_one_direction_score_the_same(layout_case): + n, undirected, readout, err, entry = layout_case + heron = _score(_state(n, _both(undirected), readout, err), entry) + eagle = _score(_state(n, undirected, readout, err), entry) + assert heron['n_gates'] == eagle['n_gates'] + assert heron['fidelity'] == pytest.approx(eagle['fidelity'], rel=1e-12) + + +def test_n_gates_is_the_lucj_gate_count(layout_case): + n, undirected, readout, err, entry = layout_case + res = _score(_state(n, _both(undirected), readout, err), entry) + assert len(entry['ancillas']) == 1 + assert res['n_gates'] == len(_lucj_gates(entry)) == 2 * (8 - 1) + 2 + expected = np.prod([1 - readout[q] for q in + entry['alpha'] + entry['beta'] + entry['ancillas']]) + expected *= np.prod([1 - err[frozenset(g)] for g in _lucj_gates(entry)]) + assert res['fidelity'] == pytest.approx(expected, rel=1e-12) + + +def test_ui_scan_and_harness_agree(layout_case): + n, undirected, readout, err, entry = layout_case + edges = _both(undirected) + state = _state(n, edges, readout, err) + ui = _score(state, entry)['fidelity'] + shim = CachedPropsShim( + {'readout_error': state.qubit_props_data['readout_error']}, + {'cz_error': state.gate_props_data['cz_error']}, edges, n_qubits=n) + qubits = entry['alpha'] + entry['beta'] + entry['ancillas'] + scan = shim.score_layout(qubits) + harness = ev._lqs_scorer(state.qubit_props_data, state.gate_props_data, + edges, state.qubit_ids)(entry) + assert scan['n_gates'] == len(_lucj_gates(entry)) + assert scan['fidelity'] == pytest.approx(ui, rel=1e-12) + assert harness == pytest.approx(ui, rel=1e-12) + + +def test_direction_mismatch_keeps_the_larger_error_and_logs_once(caplog): + scoring._DIRECTION_MISMATCH_LOGGED.discard(frozenset(('7', '8'))) + edges = [('7', '8', 0.01), ('8', '7', 0.03), ('7', '8', 0.02)] + with caplog.at_level(logging.INFO, logger='iqmapper.export.scoring'): + out = unique_couplers(edges) + unique_couplers(edges) + assert out == [('7', '8', 0.03)] + assert sum('different errors per direction' in r.message + for r in caplog.records) == 1 + + +def test_a_missing_direction_never_hides_a_present_one(): + nan = float('nan') + assert unique_couplers([('0', '1', nan), ('1', '0', 0.02)]) == [ + ('0', '1', 0.02)] + assert unique_couplers([('0', '1', 0.02), ('1', '0', None)]) == [ + ('0', '1', 0.02)] + assert unique_couplers([('0', '1', 0.02), ('1', '2', 0.03)]) == [ + ('0', '1', 0.02), ('1', '2', 0.03)] + + +def test_a_real_heron_coupling_map_counts_each_coupler_once(tmp_path, + monkeypatch): + """FakeFez through the app's own data path: both directions listed.""" + fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + from iqmapper import data + from iqmapper.state import SessionState + monkeypatch.setattr(data, '_CACHE_DIR', str(tmp_path)) + backend = fake_provider.FakeFez() + state = SessionState() + state.active_backend = backend + state.active_backend_name = backend.name + state.initial_props = backend.properties() + _x, _y, edges, q_ids, _ro, _cz = data._generate_ibm(state, None) + state.edges_list, state.qubit_ids = edges, q_ids + assert len({frozenset(e) for e in edges}) * 2 == len(edges) + + res = sweep_ancilla_layouts(8, backend, backend.properties(), + min_bridges=1, top_n=1) + entry = res['strata'][1][0] + scored = _score(SimpleNamespace( + qubit_ids=state.qubit_ids, edges_list=state.edges_list, + qubit_props_data=state.qubit_props_data, + gate_props_data=state.gate_props_data), entry) + assert scored['n_gates'] == len(_lucj_gates(entry)) == 16 diff --git a/tests/test_props_shim.py b/tests/test_props_shim.py index 37df7f7..9bbd731 100644 --- a/tests/test_props_shim.py +++ b/tests/test_props_shim.py @@ -233,10 +233,10 @@ def test_shim_score_matches_core_handbuilt(): assert shim_score == pytest.approx(0.0) # dead coupler seen, not hidden -# ── SYM-1 t1: score_layout scores the FULL directed surface (== C1 core) ───── +# ── SYM-1 t1: score_layout scores every coupler in the set, once (== C1) ───── -def test_score_layout_full_directed_surface(): - from iqmapper.export.scoring import estimate_fidelity_core +def test_score_layout_counts_each_coupler_once(): + from iqmapper.export.scoring import estimate_fidelity_core, unique_couplers # Bidirectional coupling map + an INCIDENTAL edge (0,2) among the set # (not on the chain path) carrying a large error. edges = [(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)] @@ -250,15 +250,16 @@ def test_score_layout_full_directed_surface(): core = estimate_fidelity_core( cand, {q: qp['readout_error'][q] for q in cand}, - [(u, v, cz[i]) for i, (u, v) in enumerate(edges)], + unique_couplers([(u, v, cz[i]) for i, (u, v) in enumerate(edges)]), all_readout=qp['readout_error']) assert sh['fidelity'] == pytest.approx(core['fidelity']) - assert sh['n_gates'] == 6 # all directed edges counted - # The incidental (0,2) 0.30 factor IS included (both dirs) — not skipped. + assert sh['n_gates'] == 3 # three couplers, once each + assert sh['fidelity'] == pytest.approx(0.99 ** 3 * 0.99 ** 2 * 0.70) + # The incidental (0,2) 0.30 coupler IS included (once) — not skipped. healthy_only = estimate_fidelity_core( cand, {q: 0.01 for q in cand}, - [(0, 1, 0.01), (1, 0, 0.01), (1, 2, 0.01), (2, 1, 0.01)], + [(0, 1, 0.01), (1, 2, 0.01)], all_readout=qp['readout_error']) assert sh['fidelity'] < healthy_only['fidelity'] From 55faeff7eafe55f7e89a3b5476812da22362ed68 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 6 Oct 2026 15:15:04 -0400 Subject: [PATCH 47/66] LQS: guided search returns induced layouts only; ancilla highlight stays inside its circuit; docs --- CHANGELOG.md | 17 +++ README.md | 15 ++- iqmapper/guided_search.py | 57 +++++++-- iqmapper/plot.py | 37 +++--- tests/test_guided_induced.py | 164 ++++++++++++++++++++++++++ tests/test_guided_search.py | 2 +- tests/test_link_gates_same_circuit.py | 50 ++++++++ 7 files changed, 311 insertions(+), 31 deletions(-) create mode 100644 tests/test_guided_induced.py create mode 100644 tests/test_link_gates_same_circuit.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 037f4ac..e5e879e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,23 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). in one short sentence, and each is explained in the README section "Understanding the messages". +### Fixed +- LQS counted every two-qubit gate twice on backends that list each coupler + in both directions (CZ devices such as Heron), so their scores were too low + and could not be compared with ECR devices such as Eagle, which list one + direction. Each coupler now counts once, in the Layout-Quality box, the + sweep ranking and the multi-QPU scan alike. +- The guided search could return layouts in which two qubits were joined by + a coupler the ansatz does not use (for example the two ends of a chain that + wraps round a hexagon). The LQS counted that coupler as a gate, so such a + layout was scored, and could be ranked, on a gate the circuit never runs. + Guided layouts now contain only the ansatz's own couplers, as exhaustive + ones already did. +- With "Auto-Color Gates" on, an ancilla coloured its edges towards qubits of + other circuits too, so a coupler between two circuits looked like a gate + of one of them. An ancilla now colours only edges to qubits of its own + circuit, on the map and in the PNG export. + ## [0.0.5] — 2026-08 First public-ready release. diff --git a/README.md b/README.md index 83166ca..782a0d7 100644 --- a/README.md +++ b/README.md @@ -427,10 +427,17 @@ you connect a backend from the Hardware section. ### LQS Layout Quality Score: an estimate of how well a circuit would run on a given -set of qubits, combining the readout and gate errors of every qubit and -coupling it uses. It is the same number the Estimated Layout-Quality box -shows. A `(template)` suffix means the full calculation was unavailable and a -simpler heuristic was used instead. +set of qubits. It is the product of (1 − readout error) over the qubits the +circuit uses and (1 − two-qubit gate error) over every coupler joining two of +those qubits, each coupler counted once whichever directions the backend +lists. It is the same number the Estimated Layout-Quality box shows; each +circuit's line there, for example `C1: …% (17q × 16g · …)`, gives the qubit +count and that coupler count. Layouts found by the LUCJ search engines never +contain a coupler the ansatz does not use, so for them the coupler count is +the ansatz's two-qubit gate count: 2 × (norb − 1) along the two chains plus +2 per ancilla (16 for norb = 8 with one ancilla). A `(template)` suffix means +the full calculation was unavailable and a simpler heuristic was used +instead. ## Extending to other vendors diff --git a/iqmapper/guided_search.py b/iqmapper/guided_search.py index 4405723..3cb4e31 100644 --- a/iqmapper/guided_search.py +++ b/iqmapper/guided_search.py @@ -33,8 +33,12 @@ node `2*norb + i` and is adjacent to exactly two nodes: alpha slot `4*i` and beta slot `4*i`. * A layout is the list `alpha(norb) + beta(norb) + bridges(k)`, and an - embedding is valid iff it is injective and every template edge maps to a - coupling edge. + embedding is valid iff it is injective, every template edge maps to a + coupling edge, and no other coupling edge joins two of its qubits. That + last rule makes the embedding induced, which is what + `rustworkx.vf2_mapping(subgraph=True)` returns by default, so both engines + search the same space. The LQS counts every coupler between layout qubits, + so a non-template one would be scored as a gate the circuit never runs. LUCJ PREFIX CONTRACT (from ancilla_sweep, and binding here) A k'-bridge variant keeps the bridges at the FIRST k' standard slots @@ -142,9 +146,10 @@ def template_edges(norb, k): def validate_layout(layout, norb, k, adjacency): - """True iff `layout` is a valid embedding of the (norb, k) template. + """True iff `layout` is a valid induced embedding of the (norb, k) template. - Checks injectivity and that every template edge lands on a coupling edge. + Checks injectivity, that every template edge lands on a coupling edge, and + that every coupling edge between two layout qubits is a template edge. Used after every refinement move, because a move that produced an invalid layout would be worse than no refinement at all. """ @@ -153,9 +158,17 @@ def validate_layout(layout, norb, k, adjacency): return False if len(set(layout)) != expected: return False - for u, v in template_edges(norb, k): + edges = template_edges(norb, k) + for u, v in edges: if layout[v] not in adjacency.get(layout[u], ()): return False + allowed = {frozenset(e) for e in edges} + position = {q: i for i, q in enumerate(layout)} + for i, q in enumerate(layout): + for n in adjacency.get(q, ()): + j = position.get(n) + if j is not None and frozenset((i, j)) not in allowed: + return False return True @@ -251,6 +264,15 @@ def q_factor(self, q): def e_factor(self, a, b): return max(0.0, 1.0 - self.e_of(a, b)) + def couples_only_to(self, q, placed, allowed): + """Is every coupler from `q` into `placed` one of the `allowed` ends? + + Growth calls this for each qubit it adds, against everything already + placed, so every pair of layout qubits is checked once and the + finished layout is an induced embedding. + """ + return self.adjacency.get(q, frozenset()) & placed <= allowed + # ── seeding ───────────────────────────────────────────────── def seeds(self, k_target): """Initial states at orbital slot 0. @@ -258,7 +280,8 @@ def seeds(self, k_target): Slot 0 always carries a bridge when k >= 1 (n % 4 == 0 includes 0), so a seed is a (bridge, alpha0, beta0) triple with the bridge adjacent to both chain heads. With k == 0 there is no bridge and a seed is any - ordered pair of distinct qubits — collapsed by canonicalisation. + ordered pair of distinct qubits — collapsed by canonicalisation. The + two chain heads are never coupled to each other. """ out = [] # Iterate the ADJACENCY, not the graph: excluded qubits (and any @@ -269,6 +292,8 @@ def seeds(self, k_target): neighbours = sorted(self.adjacency[r]) for i, a in enumerate(neighbours): for b in neighbours[i + 1:]: + if b in self.adjacency.get(a, frozenset()): + continue d_log = (_safe_log(self.q_factor(a)) + _safe_log(self.q_factor(b)) + _safe_log(self.q_factor(r)) @@ -282,6 +307,8 @@ def seeds(self, k_target): nodes = sorted(self.adjacency) for i, a in enumerate(nodes): for b in nodes[i + 1:]: + if b in self.adjacency.get(a, frozenset()): + continue d_log = (_safe_log(self.q_factor(a)) + _safe_log(self.q_factor(b))) d_add = self.r_of(a) + self.r_of(b) @@ -294,7 +321,12 @@ def _slot_has_bridge(self, j, k_target): return j % 4 == 0 and (j // 4) < k_target def expand(self, state, k_target): - """Every legal one-slot extension of `state`.""" + """Every legal one-slot extension of `state`. + + A new qubit may couple only to its template neighbours among the + qubits already placed: a chain qubit to its predecessor, a bridge to + the two chain qubits it joins. + """ j = state.depth a_prev, b_prev = state.alpha[-1], state.beta[-1] want_bridge = self._slot_has_bridge(j, k_target) @@ -302,9 +334,13 @@ def expand(self, state, k_target): for a in sorted(self.adjacency.get(a_prev, frozenset())): if a in state.used: continue + if not self.couples_only_to(a, state.used, {a_prev}): + continue for b in sorted(self.adjacency.get(b_prev, frozenset())): if b in state.used or b == a: continue + if not self.couples_only_to(b, state.used | {a}, {b_prev}): + continue self.expansions += 1 d_log = (_safe_log(self.q_factor(a)) + _safe_log(self.q_factor(b)) @@ -320,6 +356,9 @@ def expand(self, state, k_target): for r in sorted(common): if r in state.used or r in (a, b): continue + if not self.couples_only_to(r, state.used | {a, b}, + {a, b}): + continue b_log = (_safe_log(self.q_factor(r)) + _safe_log(self.e_factor(a, r)) + _safe_log(self.e_factor(r, b))) @@ -412,8 +451,8 @@ def _entry_from_state(engine, alpha, beta, bridges, k): def _candidate_moves(engine, entry, k): """Every 1-opt neighbour of `entry`, as (label, new_layout_parts). - Three move families, all preserving the template by construction and - re-validated afterwards anyway: + Three move families. A move can bring in a coupler the template does not + have, so `refine_entry` re-validates every one with `validate_layout`: bridge — swap a bridge for another common unused neighbour of the two chain qubits it joins; diff --git a/iqmapper/plot.py b/iqmapper/plot.py index 5565de2..00c8e68 100644 --- a/iqmapper/plot.py +++ b/iqmapper/plot.py @@ -319,18 +319,20 @@ def refresh_plot(fig, state, widgets_ref): if not both_other: s_u, s_v = global_style[u], global_style[v] # Highlight only same-group edges (α-α, β-β, …) or - # ancilla-adjacent edges; α/β boundary stays grey. - # Same-group check compares (circuit, role) tuples - # — NOT fill colour (see qubit_group_key comment above). - if state.qubit_ids[u] in all_ancillas: + # ancilla-adjacent edges inside one circuit; α/β + # boundary and edges between circuits stay grey. + # Group checks compare (circuit, role) tuples — NOT + # fill colour (see qubit_group_key comment above). + gk_u = qubit_group_key.get(u) + gk_v = qubit_group_key.get(v) + same_circuit = (gk_u is not None and gk_v is not None + and gk_u[0] == gk_v[0]) + if same_circuit and state.qubit_ids[u] in all_ancillas: match_col = s_u['line'] - elif state.qubit_ids[v] in all_ancillas: + elif same_circuit and state.qubit_ids[v] in all_ancillas: match_col = s_v['line'] - else: - gk_u = qubit_group_key.get(u) - gk_v = qubit_group_key.get(v) - if gk_u is not None and gk_u == gk_v: - match_col = s_u['line'] + elif gk_u is not None and gk_u == gk_v: + match_col = s_u['line'] edge_colors.append(match_col if match_col else w.pp_gate_col.value) edge_widths.append(hl_w if match_col else base_w) @@ -1021,15 +1023,16 @@ def build_static_figure(state, opts, margin=40, crop_to_selection=False, annotat both_other = (state.qubit_ids[u] in all_others and state.qubit_ids[v] in all_others) if not both_other: s_u, s_v = global_style[u], global_style[v] - if state.qubit_ids[u] in all_ancillas: + gk_u = qubit_group_key.get(u) + gk_v = qubit_group_key.get(v) + same_circuit = (gk_u is not None and gk_v is not None + and gk_u[0] == gk_v[0]) + if same_circuit and state.qubit_ids[u] in all_ancillas: match_col = s_u['line'] - elif state.qubit_ids[v] in all_ancillas: + elif same_circuit and state.qubit_ids[v] in all_ancillas: match_col = s_v['line'] - else: - gk_u = qubit_group_key.get(u) - gk_v = qubit_group_key.get(v) - if gk_u is not None and gk_u == gk_v: - match_col = s_u['line'] + elif gk_u is not None and gk_u == gk_v: + match_col = s_u['line'] if match_col: edge_shapes.append(dict(type='line', x0=x0, y0=y0, x1=x1, y1=y1, diff --git a/tests/test_guided_induced.py b/tests/test_guided_induced.py new file mode 100644 index 0000000..092505a --- /dev/null +++ b/tests/test_guided_induced.py @@ -0,0 +1,164 @@ +"""The guided engine only produces induced embeddings of the LUCJ template. + +A layout must not contain two qubits joined by a coupler the template does +not have: the LQS counts every coupler between layout qubits, so such a +layout would be scored on a gate the circuit never runs. VF2 searches induced +subgraphs, so this keeps both engines in the same space. + +The check here reads the coupling graph directly instead of calling +`validate_layout`, so it does not test the validator with itself. +""" +from types import SimpleNamespace + +import numpy as np +import pytest +import rustworkx + +from iqmapper import guided_search as gs +from iqmapper.auto_lucj import _make_backend_cmap_pygraph +from iqmapper.guided_search import guided_sweep + + +def _backend_from(undirected): + graph = rustworkx.PyDiGraph() + n = 1 + max(max(e) for e in undirected) + for _ in range(n): + graph.add_node(None) + for u, v in undirected: + graph.add_edge(u, v, None) + graph.add_edge(v, u, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _SeededProps: + """Deterministic spread of readout and gate errors.""" + + def __init__(self, n, seed): + rng = np.random.default_rng(seed) + self._r = 0.005 + 0.03 * rng.random(n) + self._seed = seed + + def readout_error(self, q): + return float(self._r[int(q)]) + + def gate_error(self, _name, edge): + u, v = sorted((int(edge[0]), int(edge[1]))) + rng = np.random.default_rng((self._seed, u, v)) + return 0.002 + 0.02 * float(rng.random()) + + +def _extra_couplers(backend, entry, norb, k): + """Couplers between layout qubits that are not template edges.""" + graph = _make_backend_cmap_pygraph(backend=backend) + layout = list(entry['alpha']) + list(entry['beta']) + list(entry['ancillas']) + template = {frozenset((layout[u], layout[v])) + for u, v in gs.template_edges(norb, k)} + qubits = set(layout) + induced = {frozenset((u, v)) for u, v in graph.edge_list() + if u in qubits and v in qubits} + return sorted(tuple(sorted(e)) for e in induced - template) + + +def _entries(result): + for k, entries in result['strata'].items(): + for entry in entries: + yield k, entry + + +# ── growth and refinement never bring in an extra coupler ─────────── + +@pytest.mark.parametrize('d, norbs', [(5, (4, 6, 8)), (7, (8, 12))]) +def test_no_guided_entry_has_a_non_template_coupler_on_heavy_hex(d, norbs): + undirected = [tuple(e) for e in + rustworkx.generators.heavy_hex_graph(d).edge_list()] + backend = _backend_from(undirected) + props = _SeededProps(1 + max(max(e) for e in undirected), seed=d) + for norb in norbs: + res = guided_sweep(norb, backend, props, min_bridges=1, top_n=5, + circuit_score_fn=lambda e: e['product_score']) + assert res['strata'], f'no strata for d={d} norb={norb}' + for k, entry in _entries(res): + assert _extra_couplers(backend, entry, norb, k) == [], ( + f'd={d} norb={norb} k={k}: {entry["alpha"]} ' + f'{entry["beta"]} {entry["ancillas"]}') + + +def test_no_guided_entry_has_a_non_template_coupler_on_fake_fez(): + fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + backend = fake_provider.FakeFez() + props = backend.properties() + for norb in (8, 12, 16): + res = guided_sweep(norb, backend, props, min_bridges=1, top_n=10, + circuit_score_fn=lambda e: e['product_score']) + for k, entry in _entries(res): + assert _extra_couplers(backend, entry, norb, k) == [], ( + f'norb={norb} k={k}: {entry["alpha"]} {entry["beta"]} ' + f'{entry["ancillas"]}') + + +# ── the validator ─────────────────────────────────────────────────── + +def test_the_fake_fez_hexagon_wrap_is_rejected(): + """norb=12, k=1: alpha runs round a hexagon, so its two ends 109 and 108 + sit on one coupler. Every template edge is present; only the extra + coupler makes it invalid.""" + fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + graph = _make_backend_cmap_pygraph(backend=fake_provider.FakeFez()) + adjacency = {q: frozenset(graph.neighbors(q)) for q in graph.node_indices()} + alpha = [109, 110, 111, 98, 91, 90, 89, 88, 87, 97, 107, 108] + beta = [129, 128, 127, 126, 125, 124, 123, 136, 143, 142, 141, 140] + layout = alpha + beta + [118] + norb, k = 12, 1 + + assert all(layout[v] in adjacency[layout[u]] + for u, v in gs.template_edges(norb, k)) + assert 108 in adjacency[109] + assert gs.validate_layout(layout, norb, k, adjacency) is False + + +def _path_adjacency(edges): + adj = {} + for u, v in edges: + adj.setdefault(u, set()).add(v) + adj.setdefault(v, set()).add(u) + return {q: frozenset(n) for q, n in adj.items()} + + +# norb=2, k=1: alpha = 0-1, beta = 2-3, bridge 4 joins 0 and 2. +_TEMPLATE = [(0, 1), (2, 3), (0, 4), (4, 2)] +_LAYOUT = [0, 1, 2, 3, 4] + + +def test_validate_layout_accepts_an_induced_embedding(): + assert gs.validate_layout(_LAYOUT, 2, 1, _path_adjacency(_TEMPLATE)) + + +@pytest.mark.parametrize('extra, kind', [ + ((1, 3), 'alpha-beta direct'), + ((0, 2), 'chain heads under the bridge'), + ((4, 1), 'bridge to a non-bridge slot'), +]) +def test_validate_layout_rejects_an_extra_coupler(extra, kind): + adjacency = _path_adjacency(_TEMPLATE + [extra]) + assert gs.validate_layout(_LAYOUT, 2, 1, adjacency) is False, kind + + +def test_a_coupler_to_a_qubit_outside_the_layout_is_fine(): + adjacency = _path_adjacency(_TEMPLATE + [(1, 5), (4, 6)]) + assert gs.validate_layout(_LAYOUT, 2, 1, adjacency) + + +def test_seeds_never_pair_two_coupled_chain_heads(): + """A triangle 0-1-2: 1 and 2 both neighbour 0, but they are coupled to + each other, so (bridge 0, heads 1 and 2) is not a valid seed.""" + backend = _backend_from([(0, 1), (0, 2), (1, 2), (0, 3)]) + graph = _make_backend_cmap_pygraph(backend=backend) + engine = gs._GuidedEngine(1, graph, np.full(4, 0.01), + {frozenset(e): 0.01 for e in graph.edge_list()}) + for seed in engine.seeds(1): + a, b = seed.alpha[0], seed.beta[0] + assert b not in engine.adjacency[a], (seed.bridges, a, b) + assert {(s.bridges[0], frozenset((s.alpha[0], s.beta[0]))) + for s in engine.seeds(1)} == {(0, frozenset((1, 3))), + (0, frozenset((2, 3)))} diff --git a/tests/test_guided_search.py b/tests/test_guided_search.py index eb51f2d..775f6c3 100644 --- a/tests/test_guided_search.py +++ b/tests/test_guided_search.py @@ -170,7 +170,7 @@ def test_a_wider_beam_finds_a_superset_of_completed_layouts(): engine, norb = _engine_for(backend, props, norb=6) k = 2 - narrow = {s.key() for s in engine.run_beam(k, 40)} + narrow = {s.key() for s in engine.run_beam(k, 50)} engine.expansions = 0 wide = {s.key() for s in engine.run_beam(k, 200)} diff --git a/tests/test_link_gates_same_circuit.py b/tests/test_link_gates_same_circuit.py new file mode 100644 index 0000000..fefeeda --- /dev/null +++ b/tests/test_link_gates_same_circuit.py @@ -0,0 +1,50 @@ +"""Linked-gate highlighting: an ancilla colours its edges only towards +qubits of its own circuit, in the design view and in the PNG export. + +Scenario: C1 owns alpha 0 and ancilla 1, C2 owns alpha 2 and beta 3, on a +line 0-1-2-3. Edge (0,1) is C1's ancilla gate, edge (1,2) joins C1's ancilla +to C2, edge (2,3) is C2's alpha-beta boundary. +""" +import pytest + +pytest.importorskip('plotly') + +from iqmapper import plot # noqa: E402 + +from test_focus_isolate_boundary import _make_state, _opts, _wref # noqa: E402 + +_C1_LINE, _C2_LINE = '#aa0000', '#0000aa' + + +def _state(): + s = _make_state() + d0, d1 = s.layouts_data[0], s.layouts_data[1] + d0['alpha'], d0['beta'], d0['ancilla'] = ['0'], [], ['1'] + for q in ('0', '1'): + d0['styles'][q]['line'] = _C1_LINE + for q in ('2', '3'): + d1['styles'][q]['line'] = _C2_LINE + return s + + +def _highlighted(shapes): + """{(x0, x1): colour} of the highlighted edges on the 0..3 line.""" + return {(round(sh.x0), round(sh.x1)): sh.line.color for sh in shapes} + + +def test_design_view_highlights_the_ancilla_edge_only_inside_its_circuit(): + w = _wref() + w.view_mode.value = 'design' + w.chk_link_gates.value = True + fig = plot.create_figure() + state = _state() + plot.build_device_graph(fig, state, w) + plot.refresh_plot(fig, state, w) + assert _highlighted(fig.layout.shapes) == {(0, 1): _C1_LINE} + + +def test_png_export_highlights_the_ancilla_edge_only_inside_its_circuit(): + opts = _opts() + opts['is_error'], opts['link_gates'] = False, True + fig = plot.build_static_figure(_state(), opts) + assert _highlighted(fig.layout.shapes) == {(0, 1): _C1_LINE} From b6cf1752f0eada4ec8bf74bfe460ce7da5e26f11 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 6 Oct 2026 15:54:15 -0400 Subject: [PATCH 48/66] Batch scan: never re-search the active backend; show it as a QPU 1 reference row --- iqmapper/ui/lucj_panel.py | 77 ++++++++++++++--- tests/test_batch_scan_active.py | 145 ++++++++++++++++++++++++++++++++ 2 files changed, 211 insertions(+), 11 deletions(-) create mode 100644 tests/test_batch_scan_active.py diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 284ab9f..dac6d8f 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -1361,7 +1361,8 @@ def _scan_selector(rows, *, label_fn, detail_fn, open_ok_fn, payload_fn, """One Dropdown over scan rows (already ranked) + one detail line + one '🔗 open on QPU 2' button. Selecting a row updates the detail; the open button is disabled (with a tooltip) for rows that cannot be opened - (errors, or a batch that does not fully fit).""" + (errors, a batch that does not fully fit, the QPU 1 reference row). + `disabled_tip` is a string, or a callable(row) returning one.""" opts = [(label_fn(r), i) for i, r in enumerate(rows)] if not opts: return [] @@ -1378,7 +1379,8 @@ def _sync(idx): det.value = detail_fn(r) ok = open_ok_fn(r) btn.disabled = not ok - btn.tooltip = '' if ok else disabled_tip + tip = disabled_tip(r) if callable(disabled_tip) else disabled_tip + btn.tooltip = '' if ok else tip dd.observe(lambda ch: ch['new'] is not None and _sync(ch['new']), names='value') @@ -2081,12 +2083,48 @@ def _batch_line_html(res): parts.append(f"batch: {m * 100.0:.1f}%{' (template)' if is_tmpl else ''}") return ' | '.join(parts) - def _render_batch_results(scan_result): + def _local_batch_reference(norbs): + """The local multi-circuit result, if it was planned on the active + backend for these norbs; else None.""" + local = _multi_sweep['result'] + if not local: + return None + ctx = local.get('_context') or {} + if ctx.get('backend') is not state.active_backend: + return None + if list(ctx.get('norbs') or []) != list(norbs): + return None + return local + + def _with_reference_row(results, active_name, local): + """Scan rows without the active backend; with a local result, a + reference row for it at its rank among the ranked rows.""" + rows = [r for r in results if r.get('name') != active_name] + if local is None or not active_name: + return rows + metric, _ = _batch_metric(local) + ref = {'name': active_name, 'family': None, 'sweep': local, + 'best_lqs': metric, 'best_k': None, 'error': None, + 'reference': True} + pos = next((i for i, r in enumerate(rows) + if r.get('best_lqs') is None or r['best_lqs'] < metric), + len(rows)) + rows.insert(pos, ref) + return rows + + def _render_batch_results(scan_result, active_name=None, norbs=()): # ONE QPU selector over the scan_qpus-ranked batches: pick a backend, # see its per-circuit detail, open the whole batch on QPU 2. A batch - # that does not fully fit is selectable but not openable. + # that does not fully fit is selectable but not openable. The active + # backend is QPU 1: it appears only as a reference row built from the + # local multi-circuit result, never openable. + local = _local_batch_reference(norbs) + rows = _with_reference_row(scan_result['results'], active_name, local) + def _label(r): name = esc(str(r['name'])) + if r.get('reference'): + name += ' (this QPU)' if r.get('error'): return f"{name} — ✗ error" m, is_tmpl = _batch_metric(r.get('sweep') or {}) @@ -2102,18 +2140,28 @@ def _detail(r): def _open_ok(r): res = r.get('sweep') or {} - return (not r.get('error') and bool(res.get('circuits')) + return (not r.get('error') and not r.get('reference') + and bool(res.get('circuits')) and res.get('failed_at') is None) def _payload(r): res = r.get('sweep') or {} return [c['chosen'] for c in res.get('circuits', [])] - scan_batch_box.children = _scan_selector( - scan_result['results'], - label_fn=_label, detail_fn=_detail, open_ok_fn=_open_ok, - payload_fn=_payload, - disabled_tip='batch does not fully fit on this backend') + def _tip(r): + if r.get('reference'): + return 'already QPU 1' + return 'batch does not fully fit on this backend' + + children = _scan_selector( + rows, label_fn=_label, detail_fn=_detail, open_ok_fn=_open_ok, + payload_fn=_payload, disabled_tip=_tip) + if local is None and active_name: + children.append(HTML( + "
" + "this QPU not included — run Generate Multi-Circuit to " + "compare
")) + scan_batch_box.children = children def _on_scan_batch(b): if state.active_backend is None: @@ -2142,6 +2190,7 @@ def _on_scan_batch(b): lbl_lucj_multi.value = _joint_pending_html(len(norbs)) kwargs = _sweep_kwargs_from_ui() buffer = lucj_buffer_slider.value + active_name = getattr(state, 'active_backend_name', None) def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): excl = _batch_backend_exclusions(props, getattr(backend, 'name', None)) @@ -2176,6 +2225,12 @@ def _work(): targets = qpu_scan.list_scan_targets( state, norbs[0], same_family_as=family, include_other_families=chk_scan_other_families.value) + # Never re-search the active backend: it is QPU 1. No sweep, no + # fetch; the local multi-circuit result stands in for it. + for t in targets: + if t.get('name') == active_name: + t['eligible'] = False + t['reason'] = 'current backend — see local results above' get_backend = state.active_service.backend get_props = make_scan_get_props(state) return qpu_scan.scan_qpus( @@ -2185,7 +2240,7 @@ def _work(): def _done(result): _reset() - _render_batch_results(result) + _render_batch_results(result, active_name, norbs) def _err(exc): _reset() diff --git a/tests/test_batch_scan_active.py b/tests/test_batch_scan_active.py new file mode 100644 index 0000000..57ec605 --- /dev/null +++ b/tests/test_batch_scan_active.py @@ -0,0 +1,145 @@ +"""Batch scan and the active backend: QPU 1 is never re-searched by the batch +scan. A local multi-circuit result for the same batch appears as a reference +row " (this QPU)" at its rank, never openable; without one, a short line +says this QPU is not included. + +Headless: a real MapperUIBuilder; the multi-circuit planner is stubbed, so +every search, local or remote, is recorded by backend. +""" +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Button, Dropdown, HBox, HTML + +from test_floor_batch_ui import _build + +ACTIVE = 'stub' # test_floor_batch_ui's active backend +TOTALS = {ACTIVE: 0.5, 'ibm_a': 0.6, 'ibm_b': 0.4} + + +def _result(backend, norbs, total): + circuits = [{'circuit_idx': j, 'norb': n, + 'chosen': {'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4 + j], 'product_score': total, + 'lqs_circuit': total}, + 'strata': {1: []}, 'per_stratum': {}} + for j, n in enumerate(norbs)] + return {'circuits': circuits, 'total_product': total, + 'total_lqs_circuit': total, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': None, + '_context': {'backend': backend, 'norbs': list(norbs)}} + + +def _wire(monkeypatch, b, state): + """Stub planner, targets, backends and props; return the search log.""" + from iqmapper import multi_sweep as ms + from iqmapper import qpu_scan as qs + log = {'searched': [], 'fetched': []} + + def _plan(norbs, backend, props, **_kw): + name = getattr(backend, 'name', ACTIVE) + log['searched'].append(name) + return _result(backend, norbs, TOTALS[name]) + + def _backend(name): + log['fetched'].append(name) + return SimpleNamespace(name=name) + + monkeypatch.setattr(ms, 'sweep_multi_circuits', _plan) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in (ACTIVE, 'ibm_a', 'ibm_b')]) + monkeypatch.setattr('iqmapper.props_shim.make_scan_get_props', + lambda state: (lambda backend: SimpleNamespace( + _readout=np.full(16, 0.01), n_qubits=16, + vintage='live', + score_layout=lambda q: {'fidelity': 0.5}))) + state.active_service = SimpleNamespace(backend=_backend) + b.lucj_multi_norbs.value = '4, 4' + return log + + +def _selector(b): + kids = list(b.scan_batch_box.children) + dd = next(c for c in kids if isinstance(c, Dropdown)) + btn = next(c for w in kids if isinstance(w, HBox) + for c in w.children if isinstance(c, Button)) + return dd, btn + + +def _texts(b): + return [c.value for c in b.scan_batch_box.children if isinstance(c, HTML)] + + +# ── the active backend is never swept by the batch scan ───────────── + +def test_the_batch_scan_never_searches_the_active_backend(monkeypatch): + b, state = _build(monkeypatch) + log = _wire(monkeypatch, b, state) + b.btn_scan_batch.click() + assert ACTIVE not in log['fetched'] + assert log['searched'] == ['ibm_a', 'ibm_b'] + + +# ── reference row only with a local result ────────────────────────── + +def test_without_a_local_result_there_is_no_row_and_one_short_line( + monkeypatch): + b, state = _build(monkeypatch) + _wire(monkeypatch, b, state) + b.btn_scan_batch.click() + dd, _btn = _selector(b) + labels = [label for label, _ in dd.options] + assert labels[0].startswith('ibm_a') and labels[1].startswith('ibm_b') + assert not any(label.startswith(ACTIVE) for label in labels) + assert any('this QPU not included — run Generate Multi-Circuit to ' + 'compare' in t for t in _texts(b)) + + +def test_a_local_result_is_a_reference_row_at_its_rank(monkeypatch): + b, state = _build(monkeypatch) + log = _wire(monkeypatch, b, state) + b.btn_lucj_multi_sweep.click() # local result, batch 50% + assert log['searched'] == [ACTIVE] + b.btn_scan_batch.click() + assert log['searched'] == [ACTIVE, 'ibm_a', 'ibm_b'] # no re-search + + dd, btn = _selector(b) + labels = [label for label, _ in dd.options] + assert labels[1] == f'{ACTIVE} (this QPU) — batch 50.0%' + assert labels[0].startswith('ibm_a') and labels[2].startswith('ibm_b') + assert not any('not included' in t for t in _texts(b)) + + +def test_the_reference_row_cannot_be_opened(monkeypatch): + b, state = _build(monkeypatch) + _wire(monkeypatch, b, state) + staged = [] + b._inter_qpu_handoff[0] = (lambda name, payload, report=None: + staged.append(name)) + b.btn_lucj_multi_sweep.click() + b.btn_scan_batch.click() + dd, btn = _selector(b) + + dd.value = 1 # the reference row + assert btn.disabled is True and btn.tooltip == 'already QPU 1' + btn.click() + assert staged == [] + + dd.value = 0 # a real remote batch + assert btn.disabled is False + btn.click() + assert staged == ['ibm_a'] + + +def test_a_local_result_for_another_batch_is_not_a_reference(monkeypatch): + b, state = _build(monkeypatch) + log = _wire(monkeypatch, b, state) + b.lucj_multi_norbs.value = '4, 6' + b.btn_lucj_multi_sweep.click() + b.lucj_multi_norbs.value = '4, 4' + b.btn_scan_batch.click() + assert log['searched'] == [ACTIVE, 'ibm_a', 'ibm_b'] + dd, _btn = _selector(b) + assert not any(label.startswith(ACTIVE) for label, _ in dd.options) + assert any('not included' in t for t in _texts(b)) From 367b5988195d2a047428c7d1f7cc7b80e1220c09 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 6 Oct 2026 16:57:12 -0400 Subject: [PATCH 49/66] One search: exhaustive + guided on every ancilla count, keep the best (engine_select #18) --- CHANGELOG.md | 35 ++-- CODE_OVERVIEW.md | 4 +- README.md | 60 +++--- iqmapper/engine_select.py | 146 ++++++++++++++- iqmapper/ui/builder.py | 61 +++---- iqmapper/ui/lucj_panel.py | 125 ++++++------- tests/test_auto_panel_ui_polish.py | 156 +--------------- tests/test_auto_subpanels.py | 1 + tests/test_combined_sweep.py | 282 +++++++++++++++++++++++++++++ tests/test_floor_batch_ui.py | 1 + tests/test_joint_plan_ui.py | 49 ++--- tests/test_search_ui.py | 170 +++++++++++++++++ tests/test_sweep_notices.py | 1 + tests/test_sweep_ui.py | 15 +- tests/test_ui_cleanup.py | 1 + 15 files changed, 771 insertions(+), 336 deletions(-) create mode 100644 tests/test_combined_sweep.py create mode 100644 tests/test_search_ui.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e5e879e..3d2f1b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,11 +36,17 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). already kept no longer use up the search cap, so a capped search spreads across the chip instead of filling up with variations of the first region it finds. -- Guided search engine (opt-in via "Search engine"; Exhaustive stays the - default): a calibration-led beam search that grows layouts on the +- Guided search: a calibration-led beam search that grows layouts on the best-calibrated qubits, then polishes the finalists with small local moves (swap a bridge or chain-end qubit, shift a chain by one) kept only when they - raise the circuit-level LQS. + raise the circuit-level LQS. Every Auto search now runs it alongside the + exhaustive search and keeps the best of both for each ancilla count, so the + best layout is never worse than either engine alone. Each layout in the list + shows its source (`· E`, `· G`, `· E+G`), and the status line names the + ancilla counts where guided alone found the best one. One checkbox in + Advanced, "Guided search" (on by default), turns it off to search as 0.0.5 + did. The multi-QPU scan and the stability filter still use the exhaustive + search. - Opt-in stability filter that excludes qubits volatile across the cached calibration history, and an always-on quality floor (3σ by default, 0 turns it off) that removes outlier qubits from every search. @@ -50,23 +56,24 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). handoff that reopens the chosen layout on the second QPU. - Epoch-consistent scoring: fidelity and ranking read a single pinned calibration epoch, so comparisons within a sweep stay commensurable. -- Hybrid search engine (opt-in; the default stays exhaustive): guided search - for ancilla counts up to a threshold you set ("Guided up to k"), where the - exhaustive search hits its cap and only ranks a sample, and the exhaustive - search above it. -- Joint multi-circuit planner (opt-in; Sequential stays the default): keeps - several placement plans at once instead of placing each circuit greedily, - so the first circuit no longer takes a region the next one needed. Never - worse than the sequential planner, uses the selected search engine, and - reports couplers shared by two circuits at buffer 0 (with an optional - penalty to avoid them). +- Hybrid search engine (`engine_select.hybrid_sweep`, used by the engine + comparison harness, not offered in the UI): guided search for ancilla counts + up to a threshold, where the exhaustive search hits its cap and only ranks a + sample, and the exhaustive search above it. +- Joint multi-circuit placement ("Optimize placement jointly", off by + default, which keeps the sequential placement): keeps several placement + plans at once instead of placing each circuit greedily, so the first circuit + no longer takes a region the next one needed. Never worse than sequential + placement, searches each circuit with the combined search, and reports + couplers shared by two circuits at buffer 0 (with an optional penalty to + avoid them). - Engine comparison harness (`python -m iqmapper.evaluation`): replays the search engines over the cached calibrations, offline, and ranks with the app's real circuit-level LQS rebuilt for every calibration (`--scorer lqs`, the default; `proxy` uses the product score). It takes the coupling map from a saved session (`--session PATH`, or found in the working folder), can add a hybrid-engine column (`--hybrid-k`), and prints the suggested - "Guided up to k" for each orbital count (`--tol` sets how far guided may + hybrid threshold for each orbital count (`--tol` sets how far guided may trail and still count). - Shorter UI messages: status lines, notices and tooltips say what happened in one short sentence, and each is explained in the README section diff --git a/CODE_OVERVIEW.md b/CODE_OVERVIEW.md index d762bfe..b60afb4 100644 --- a/CODE_OVERVIEW.md +++ b/CODE_OVERVIEW.md @@ -65,7 +65,7 @@ which one ran. | `ancilla_sweep.py` | The exhaustive engine: one VF2 solve at the maximum ancilla count, a bridge-subtraction cascade down to the floor, optional direct VF2 per lower count, diversity selection. Capped at 2000 mappings per stratum. | | `reservoir.py` | Makes the VF2 cap count *distinct* candidates: near-duplicate layouts are discarded without using a slot, so the capped sample spreads across the chip. | | `guided_search.py` | The guided engine: calibration-led beam search that grows layouts on the best neighbours, then a 1-opt polish against the circuit-level LQS. | -| `engine_select.py` | The hybrid engine: guided for ancilla counts up to a threshold, exhaustive above it, merged into the shared result shape. | +| `engine_select.py` | Searches built from the two engines: `combined_sweep` (the UI's search) runs both on every ancilla count and keeps the best of both, tagging each entry's source; `hybrid_sweep` (used by the evaluation harness) takes guided up to a threshold and exhaustive above it. Both return the shared result shape. | | `stability_filter.py` | Stability-aware sweep: excludes qubits that are volatile across cached history (and statistical outliers), then runs the exhaustive sweep, relaxing the filter when the circuit would no longer fit. | | `multi_sweep.py` | Sequential multi-circuit placement: each circuit greedily on the best region left, with a buffer around placed ones; replan from any circuit. | | `joint_plan.py` | Joint multi-circuit planner: a beam over placement plans with an injected single-circuit search, memoised searches and boundary-coupler accounting. Same result shape as `multi_sweep`, never worse than it. | @@ -93,7 +93,7 @@ which one ran. | `time_panel.py` | Time navigation: live / point / intraday / multi-day modes, snapshot sliders, delta reference selection. | | `history.py` | Multi-day history fetch and the time-lapse GIF/MP4 export (optional `imageio` / `imageio-ffmpeg`). | | `analysis_panel.py` | LQS display, layout rankings, and the Stability Check section. | -| `lucj_panel.py` | LUCJ controls: the single dispatch points for the search engine (`_run_sweep`) and the multi-circuit planner (`_run_multi` / `_replan_multi`), the sweep and scan displays, and replan. | +| `lucj_panel.py` | LUCJ controls: the single dispatch points for the search (`_run_sweep`, the combined search) and the multi-circuit planner (`_run_multi` / `_replan_multi`), the sweep and scan displays, and replan. | | `benchmark_panel.py` | Sidebar section "5. Benchmark": targets, cost estimate, run, and applying the measured epoch. | | `inter_qpu.py` | Multi-backend comparison view. | | `png_export.py` | Publication PNG export (optional `kaleido`). | diff --git a/README.md b/README.md index 782a0d7..a093b9f 100644 --- a/README.md +++ b/README.md @@ -309,32 +309,46 @@ makes a difference where the cap is actually reached. ### Search engine -**Exhaustive** enumerates layouts that fit the template and only then asks how -good they are — thorough, but blind to calibration until the end. **Guided** -grows each layout using the calibration as it goes and polishes the finalists. -Guided is a heuristic: it can miss the best layout that exhaustive would find, -so it stays opt-in until the comparison harness says otherwise. - -**Hybrid** uses guided where exhaustive is capped (few ancillas: so many -layouts fit that exhaustive only ranks a sample) and exhaustive where it is -complete (many ancillas: few layouts fit, and all of them are checked). Set -**Guided up to k** to the highest ancilla count where guided does at least as -well as exhaustive in the engine comparison (`python -m iqmapper.evaluation`). -The status line names the split, e.g. `engine: hybrid (guided ≤ k1)`; the -`refined 2/5` tally counts the guided finalists the polish improved. +One search, two engines, and you get the best of both. The **exhaustive** +engine lists the layouts that fit the template and only then asks how good +they are. That is thorough, but at low ancilla counts on a large chip so many +layouts fit that it stops at the search cap and ranks only a sample. The +**guided** engine grows each layout on the best-calibrated qubits and polishes +the finalists. It is never capped, but it is a heuristic and can miss a layout +the exhaustive engine would find. + +For every ancilla count the two shortlists are merged, a layout both engines +found is listed once, and the usual ranking (LQS) and region-diversity choice +pick the final list. The best layout is therefore never worse than either +engine alone. Each entry in the layout list ends with where it came from: +`· E` exhaustive, `· G` guided, `· E+G` both. When guided alone found the best +layout for some ancilla counts, the status line says so, e.g. +`· best from guided at k=1,2`. + +**Guided search** (in Advanced, on by default) runs the guided engine. Turn it +off to search with the exhaustive engine alone, as 0.0.5 did. **Beam width** +and **Refine top** tune the guided engine and show only while it is on. + +The multi-QPU scan and the stability filter still use the exhaustive engine +only, and so does the multi-circuit planner unless **Optimize placement +jointly** is on. The engine comparison (`python -m iqmapper.evaluation`) still +offers the hybrid engine, guided up to a chosen ancilla count and exhaustive +above it, to compare against. ### Multi-circuit planner -**Sequential** places circuits one at a time, each on the best region left. -It is fast but short-sighted: the first circuit can take a region that leaves -the next one only a poor spot, or none at all. - -**Joint** keeps several partial plans instead of one. After each circuit it -tries **Candidates per circuit** layouts on every plan it holds and keeps the -best **Plans kept** of them. It also builds the sequential plan and returns -whichever is better, so it is never worse — only slower. It searches with the -selected search engine (Sequential always uses exhaustive). While it runs, the -status shows `joint plan · up to N searches`, the worst case. +By default circuits are placed one at a time (sequential), each on the best +region left, with the exhaustive engine. It is fast but short-sighted: the +first circuit can take a region that leaves the next one only a poor spot, or +none at all. + +**Optimize placement jointly** keeps several partial plans instead of one. +After each circuit it tries **Candidates per circuit** layouts on every plan it +holds and keeps the best **Plans kept** of them. It also builds the sequential +plan and returns whichever is better, so it is never worse — only slower. It +searches each circuit with the search described under *Search engine* (both +engines while **Guided search** is on). While it runs, the status shows +`joint plan · up to N searches`, the worst case. When it finishes, `joint plan · +X% vs sequential · N searches` compares the two plans' totals (the product of each circuit's LQS) and counts the searches diff --git a/iqmapper/engine_select.py b/iqmapper/engine_select.py index c9576a1..ff412d3 100644 --- a/iqmapper/engine_select.py +++ b/iqmapper/engine_select.py @@ -1,6 +1,11 @@ """ -engine_select.py — the hybrid search engine: guided below a bridge-count -threshold, exhaustive VF2 above it. +engine_select.py — searches built from the two frozen single-circuit engines. + +`combined_sweep` runs both engines over every stratum and keeps the best of +the two (the search the UI uses). `hybrid_sweep` splits the k range between +them at a threshold (used by the evaluation harness). + +HYBRID: guided below a bridge-count threshold, exhaustive VF2 above it. The two single-circuit engines fail in opposite places. With few bridges (low k) the LUCJ template is loose, VF2 finds far more embeddings on a large chip @@ -17,7 +22,9 @@ """ import time -from .ancilla_sweep import sweep_ancilla_layouts +from . import ancilla_sweep as _ancilla_sweep +from . import guided_search as _guided_search +from .ancilla_sweep import _select_with_diversity, sweep_ancilla_layouts from .auto_lucj import (_make_backend_cmap_pygraph, _remove_nodes_from_graph, create_lucj_zigzag_layout) from .guided_search import guided_sweep @@ -154,3 +161,136 @@ def _sum(key): 'expansions': guided.get('expansions', 0), 'elapsed_s': time.time() - started, } + + +# ── combined: both engines on every stratum, keep the best ────────── + +#: Keyword arguments both engines take. +SHARED_KWARGS = frozenset({'min_bridges', 'top_n', 'exclude_qubits', + 'circuit_score_fn', 'diversity_threshold'}) +#: Keyword arguments only the exhaustive (VF2) engine takes. +VF2_ONLY_KWARGS = frozenset({'hybrid', 'mapping_cap', 'shuffle_seed', + 'diverse_cap'}) +#: Keyword arguments only the guided engine takes. +GUIDED_ONLY_KWARGS = frozenset({'beam_width', 'refine_top', 'qubit_weight', + 'max_iter', 'seed'}) + + +def _identity(entry): + """Same layout in both engines: same qubits, same ancillas.""" + return (frozenset(entry['alpha']) | frozenset(entry['beta']) + | frozenset(entry['ancillas']), frozenset(entry['ancillas'])) + + +def _lqs_rank_key(entry): + """The VF2 sweep's displayed-metric order: LQS, None sinks, then product.""" + lqs = entry.get('lqs_circuit') + return (lqs is not None, lqs if lqs is not None else 0.0, + entry['product_score']) + + +def _product_rank_key(entry): + return entry['product_score'] + + +def combined_sweep(norb, backend, props, *, use_guided=True, **kwargs): + """Exhaustive and guided search on every stratum; keep the best of both. + + Runs `sweep_ancilla_layouts` and, when `use_guided`, `guided_sweep` with + the same floor, exclusions, scorer, top_n and diversity threshold. Per + stratum the two shortlists are merged, a layout found by both counted + once (same qubits, same ancillas; the exhaustive entry is kept), ranked + by `lqs_circuit` (by `product_score` without a scorer), and sliced with + the exhaustive sweep's own selection: top_n, or the region-diversity + quota of `ancilla_sweep._select_with_diversity` when a threshold is set. + The best layout of a stratum is therefore never worse than either + engine's best. + + Each kept entry gets `source` = 'exhaustive', 'guided' or 'both'. + + Args: + use_guided: False runs the exhaustive search alone and returns its + result unchanged apart from `source` and the run-level keys + below. + **kwargs: the shared arguments (`SHARED_KWARGS`) go to both engines, + the engine-specific ones (`VF2_ONLY_KWARGS`, + `GUIDED_ONLY_KWARGS`) to their engine only. + + Returns the exhaustive sweep's dict: `vf2_truncated`, `reservoir`, + `reservoir_notices`, `mapping_cap`, `per_stratum` and the counts come + from the exhaustive half. Added: `engine='combined'`, `use_guided`, + `guided_winners` (strata, k-descending, whose best layout only the guided + search found), `guided_error` (why the guided half produced nothing, or + None) and, when it ran, the guided half's `beam_width`, `refined_count`, + `refine_attempted` and `expansions`. + """ + unknown = set(kwargs) - SHARED_KWARGS - VF2_ONLY_KWARGS - GUIDED_ONLY_KWARGS + if unknown: + raise TypeError(f"combined_sweep got unexpected keyword argument(s): " + f"{', '.join(sorted(unknown))}") + # Engines are looked up on their modules at call time, so a caller that + # substitutes one (tests, the evaluation harness) is honoured here too. + vf2_res = _ancilla_sweep.sweep_ancilla_layouts( + norb, backend, props, + **{k: v for k, v in kwargs.items() if k not in GUIDED_ONLY_KWARGS}) + + guided_res, guided_error = None, None + if use_guided: + try: + guided_res = _guided_search.guided_sweep( + norb, backend, props, + **{k: v for k, v in kwargs.items() + if k not in VF2_ONLY_KWARGS}) + except RuntimeError as exc: # the beam completed nothing + guided_error = str(exc) + + out = dict(vf2_res) + out.update(engine='combined', use_guided=use_guided, guided_winners=[], + guided_error=guided_error) + for entries in vf2_res['strata'].values(): + for entry in entries: + entry['source'] = 'exhaustive' + if guided_res is None: + return out + + top_n = kwargs.get('top_n', 3) + threshold = kwargs.get('diversity_threshold') + rank_key = (_product_rank_key if kwargs.get('circuit_score_fn') is None + else _lqs_rank_key) + strata = {} + for k in sorted(set(vf2_res['strata']) | set(guided_res['strata']), + reverse=True): + # Either shortlist can hold one layout twice (same qubits reached by + # a different chain order); only a match against the exhaustive list + # makes an entry 'both'. + merged, exhaustive_keys = {}, set() + for entry in vf2_res['strata'].get(k, []): + key = _identity(entry) + if key not in merged: + merged[key] = entry + exhaustive_keys.add(key) + for entry in guided_res['strata'].get(k, []): + key = _identity(entry) + if key in exhaustive_keys: + merged[key]['source'] = 'both' + elif key not in merged: + entry['source'] = 'guided' + merged[key] = entry + ranked = sorted(merged.values(), key=rank_key, reverse=True) + if threshold is None: + entries = ranked[:top_n] + else: + entries = _select_with_diversity(ranked, top_n, threshold) + for rank, entry in enumerate(entries, start=1): + entry['rank_in_stratum'] = rank + strata[k] = entries + + out['strata'] = strata + out['guided_winners'] = [k for k, entries in strata.items() + if entries and entries[0]['source'] == 'guided'] + for key in ('n_raw_embeddings', 'n_candidates_scored'): + out[key] = (vf2_res.get(key) or 0) + (guided_res.get(key) or 0) + for key in ('beam_width', 'refined_count', 'refine_attempted', + 'expansions'): + out[key] = guided_res.get(key) + return out diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index 23878f9..7d6d7a4 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -325,10 +325,9 @@ def _run_pipeline(self): lucj_chk_score=self.lucj_chk_score, chk_deep_search=self.chk_deep_search, chk_lucj_diverse=self.chk_lucj_diverse, chk_diverse_cap=self.chk_diverse_cap, - dd_search_engine=self.dd_search_engine, + chk_guided_search=self.chk_guided_search, int_beam_width=self.int_beam_width, int_refine_top=self.int_refine_top, - int_guided_max_k=self.int_guided_max_k, guided_params_box=self.bench_guided_box, btn_lucj_run=self.btn_lucj_run, lbl_lucj_status=self.lbl_lucj_status, lbl_lucj_trunc=self.lbl_lucj_trunc, @@ -336,7 +335,8 @@ def _run_pipeline(self): dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, - dd_planner=self.dd_planner, int_plans_kept=self.int_plans_kept, + chk_joint_plan=self.chk_joint_plan, + int_plans_kept=self.int_plans_kept, int_cands_per_circuit=self.int_cands_per_circuit, ft_boundary_penalty=self.ft_boundary_penalty, joint_params_box=self.joint_params_box, @@ -1466,29 +1466,19 @@ def _build_auto_lucj_widgets(self, W): tooltip='Counts only distinct candidates toward the search ' 'cap · README: Diverse enumeration') - # ── Search engine (Advanced) ───────────────────────────── - # Default stays Exhaustive (VF2) until iqmapper.evaluation says the - # guided beam wins on real cached calibration — see the harness. - self.dd_search_engine = Dropdown( - options=[('Exhaustive (VF2)', 'vf2'), ('Guided (beam)', 'guided'), - ('Hybrid', 'hybrid')], - value='vf2', - description='Search engine:', - layout=Layout(width='280px'), - style={'description_width': '110px'}, - tooltip='Exhaustive = VF2; Guided = calibration-led beam; ' - 'Hybrid = both, split by k · README: Search engine') - # Own Layout: display is toggled at runtime (Hybrid only). - self.int_guided_max_k = BoundedIntText( - value=1, min=0, max=50, - description='Guided up to k:', - layout=Layout(width='220px', display='none'), - style={'description_width': '110px'}, - tooltip='ancilla counts up to this use Guided, above it ' - 'Exhaustive · README: Search engine') + # ── Search (Advanced) ──────────────────────────────────── + # Every search runs the exhaustive engine; this adds the guided one + # and keeps the best of both. Off = exhaustive only. + self.chk_guided_search = Checkbox( + value=True, + description='Guided search', + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width), + tooltip='also run the guided search and keep the best of both ' + '· README: Search engine') + # Own Layout: display is toggled at runtime (Guided search on only). _guided_layout = Layout(width=W.width, margin=W.margin, min_width=W.min_width) - _guided_layout.display = 'none' # shown for Guided and Hybrid self.bench_guided_box = VBox([], layout=_guided_layout) self.int_beam_width = BoundedIntText( value=200, min=10, max=5000, step=50, @@ -1511,7 +1501,7 @@ def _build_auto_lucj_widgets(self, W): self.lucj_advanced_acc = Accordion( children=[VBox([self.lucj_search_cap, self.chk_deep_search, self.chk_diverse_cap, - self.dd_search_engine, self.int_guided_max_k, + self.chk_guided_search, self.bench_guided_box])], layout=W) self.lucj_advanced_acc.set_title(0, '⚙️ Advanced') @@ -1612,16 +1602,15 @@ def _build_auto_lucj_widgets(self, W): layout=Layout(width='220px'), style={'description_width': '110px'}) # ── Multi-circuit planner ───────────────────────────────── - # Default Sequential = the greedy multi_sweep, unchanged. Each widget - # owns its Layout: the Joint-only box is toggled at runtime. - self.dd_planner = Dropdown( - options=[('Sequential', 'sequential'), ('Joint', 'joint')], - value='sequential', - description='Planner:', - layout=Layout(width='220px'), - style={'description_width': '110px'}, - tooltip='Sequential = best region per circuit in turn; Joint = ' - 'plan all together · README: Multi-circuit planner') + # Off (default) = Sequential, the greedy multi_sweep, unchanged. Each + # widget owns its Layout: the Joint-only box is toggled at runtime. + self.chk_joint_plan = Checkbox( + value=False, + description='Optimize placement jointly', + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width), + tooltip='plan all circuits together instead of one at a time ' + '· README: Multi-circuit planner') self.int_plans_kept = BoundedIntText( value=4, min=1, max=50, description='Plans kept:', @@ -2105,7 +2094,7 @@ def _build_auto_lucj_view(self): self.lucj_multi_norbs, self.lucj_multi_ancillas, self.lucj_buffer_slider, - self.dd_planner, + self.chk_joint_plan, self.joint_params_box, # Legacy btn_lucj_multi intentionally omitted — the sweep button is # the single generate action. Handler/engine remain wired + pinned. diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index dac6d8f..84aa8f7 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -191,10 +191,9 @@ def setup_lucj_callbacks(ctx): chk_deep_search = ctx.chk_deep_search chk_lucj_diverse = ctx.chk_lucj_diverse chk_diverse_cap = getattr(ctx, 'chk_diverse_cap', None) - dd_search_engine = getattr(ctx, 'dd_search_engine', None) + chk_guided_search = getattr(ctx, 'chk_guided_search', None) int_beam_width = getattr(ctx, 'int_beam_width', None) int_refine_top = getattr(ctx, 'int_refine_top', None) - int_guided_max_k = getattr(ctx, 'int_guided_max_k', None) guided_params_box = getattr(ctx, 'guided_params_box', None) btn_lucj_run = ctx.btn_lucj_run lbl_lucj_status = ctx.lbl_lucj_status @@ -206,7 +205,7 @@ def setup_lucj_callbacks(ctx): lucj_multi_norbs = ctx.lucj_multi_norbs lucj_multi_ancillas = ctx.lucj_multi_ancillas lucj_buffer_slider = ctx.lucj_buffer_slider - dd_planner = getattr(ctx, 'dd_planner', None) + chk_joint_plan = getattr(ctx, 'chk_joint_plan', None) int_plans_kept = getattr(ctx, 'int_plans_kept', None) int_cands_per_circuit = getattr(ctx, 'int_cands_per_circuit', None) ft_boundary_penalty = getattr(ctx, 'ft_boundary_penalty', None) @@ -479,14 +478,14 @@ def _sweep_kwargs_from_ui(): # 0.8 default when ON; None → exact top-N (byte-compatible). 'diversity_threshold': 0.8 if chk_lucj_diverse.value else None, # The cap counts distinct candidates (engine #17). VF2-only — - # the dispatcher drops it for the guided engine. + # combined_sweep passes it to the exhaustive half only. 'diverse_cap': bool(getattr(chk_diverse_cap, 'value', True)), } - # ── ONE dispatch point for the search engine ───────────────── - def _selected_engine(): - """'vf2' (default), 'guided' or 'hybrid'. Absent widget → 'vf2'.""" - return getattr(dd_search_engine, 'value', 'vf2') or 'vf2' + # ── ONE dispatch point for the search ──────────────────────── + def _guided_on(): + """Guided search checkbox; absent widget → on (the default).""" + return bool(getattr(chk_guided_search, 'value', True)) def _guided_params(): return { @@ -494,36 +493,17 @@ def _guided_params(): 'refine_top': int(getattr(int_refine_top, 'value', 5) or 5), } - _VF2_ONLY = ('hybrid', 'mapping_cap', 'shuffle_seed', 'diverse_cap') - def _run_sweep(norb, backend, props, **kwargs): - """Run the selected search engine. - - All engines return the same dict shape, so every caller below and all - the display code downstream is engine-agnostic. `hybrid` and - `mapping_cap` are VF2-only concepts (the beam is bounded by - construction and never truncates), so they are dropped for guided - rather than passed and ignored; the hybrid engine routes them to its - VF2 half only. + """Run the search: exhaustive, plus guided when its checkbox is on. + + `engine_select.combined_sweep` keeps the best of both engines per + ancilla count and returns the exhaustive sweep's dict shape, so every + caller below and all the display code downstream is unchanged. It + routes each engine-specific argument to its own engine. """ - engine = _selected_engine() - if engine not in ('guided', 'hybrid'): - from ..ancilla_sweep import sweep_ancilla_layouts - return sweep_ancilla_layouts(norb, backend, props, **kwargs) - - shared = {k: v for k, v in kwargs.items() if k not in _VF2_ONLY} - if engine == 'hybrid': - from ..engine_select import hybrid_sweep - vf2_kwargs = {k: v for k, v in kwargs.items() if k in _VF2_ONLY} - return hybrid_sweep( - norb, backend, props, - guided_max_k=int(getattr(int_guided_max_k, 'value', 1)), - vf2_kwargs=vf2_kwargs, guided_kwargs=_guided_params(), - **shared) - - from ..guided_search import guided_sweep - shared.update(_guided_params()) - return guided_sweep(norb, backend, props, **shared) + from ..engine_select import combined_sweep + return combined_sweep(norb, backend, props, use_guided=_guided_on(), + **kwargs, **_guided_params()) def _reservoir_suffix(res): """The per-stratum cap notice, when a cap was actually reached.""" @@ -532,38 +512,37 @@ def _reservoir_suffix(res): return "" return "
" + "
".join(f"\u2139 {esc(n)}" for n in notes) - def _engine_suffix(res): - """Status-line tail naming the engine, and the refinement tally.""" - engine = res.get('engine') if isinstance(res, dict) else None - if engine == 'guided': - name = "guided" - elif engine == 'hybrid': - name = f"hybrid (guided ≤ k{res.get('guided_max_k')})" - else: + def _guided_suffix(res): + """' · best from guided at k=1,2' when guided alone found a stratum's + best layout; '' otherwise.""" + ks = (res.get('guided_winners') if isinstance(res, dict) else None) or [] + if not ks: return "" - attempted = res.get('refine_attempted') or 0 - refined = res.get('refined_count') or 0 - return (f" · engine: {name} · refined {refined}/{attempted}" - if attempted else f" · engine: {name}") - - def _on_engine_change(_change=None): - """Beam params show for Guided and Hybrid; the threshold for Hybrid.""" - engine = _selected_engine() + return " · best from guided at k=" + ",".join(str(k) for k in ks) + + def _source_tag(entry): + """' · G' (guided only), ' · E+G' (both engines) or ' · E' + (exhaustive) for a search entry; '' for one with no source.""" + source = entry.get('source') + if not source: + return "" + return {'guided': ' · G', 'both': ' · E+G'}.get(source, ' · E') + + def _on_guided_toggle(_change=None): + """Beam parameters show only while Guided search is on.""" if guided_params_box is not None: - guided_params_box.layout.display = ( - '' if engine in ('guided', 'hybrid') else 'none') - if int_guided_max_k is not None: - int_guided_max_k.layout.display = ( - '' if engine == 'hybrid' else 'none') + guided_params_box.layout.display = '' if _guided_on() else 'none' - if dd_search_engine is not None: - dd_search_engine.observe(_on_engine_change, names='value') - _on_engine_change() + if chk_guided_search is not None: + chk_guided_search.observe(_on_guided_toggle, names='value') + _on_guided_toggle() - # ── ONE dispatch point for the multi-circuit planner ───────── + # ── Multi-circuit planner: Sequential (default) or Joint ───────── def _selected_planner(): - """'sequential' (default) or 'joint'. Absent widget → 'sequential'.""" - return getattr(dd_planner, 'value', 'sequential') or 'sequential' + """'joint' when "Optimize placement jointly" is checked, else + 'sequential' (also when the widget is absent).""" + return 'joint' if getattr(chk_joint_plan, 'value', False) \ + else 'sequential' def _joint_params(): return { @@ -579,7 +558,7 @@ def _run_multi(norbs, backend, props, *, sweep_kwargs, **seq_kwargs): Sequential passes `seq_kwargs` to `multi_sweep.sweep_multi_circuits` untouched, so each call site keeps its exact call. Joint plans with `joint_plan.plan_multi_circuits`, searching each circuit through - `_run_sweep` with `sweep_kwargs`, so the selected engine is used. + `_run_sweep` with `sweep_kwargs`, so it uses the combined search. """ if _selected_planner() != 'joint': from ..multi_sweep import sweep_multi_circuits @@ -639,13 +618,13 @@ def _joint_status_html(result): return line def _on_planner_change(_change=None): - """Joint-only params are hidden while Sequential is selected.""" + """Joint-only params show only while joint placement is checked.""" if joint_params_box is not None: joint_params_box.layout.display = ( '' if _selected_planner() == 'joint' else 'none') - if dd_planner is not None: - dd_planner.observe(_on_planner_change, names='value') + if chk_joint_plan is not None: + chk_joint_plan.observe(_on_planner_change, names='value') _on_planner_change() # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the @@ -765,10 +744,9 @@ def _generate_sweep(norb): for entry in strata[k]: pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - alt = " · alt region" if entry.get('diverse') else "" # region-diversity flag dd_opts.append(( f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" - f"{alt}", + f"{_source_tag(entry)}", len(flat), )) flat.append(entry) @@ -821,7 +799,7 @@ def _generate_sweep(norb): f"
✅ {_format_sweep_status(res)}{mode_txt}" - f"{cap_txt}{vin_txt}{_engine_suffix(res)}" + f"{cap_txt}{vin_txt}{_guided_suffix(res)}" f"{_reservoir_suffix(res)}
") else: lbl_lucj_status.value = ( @@ -904,11 +882,10 @@ def _rescore_current_candidates(): for i, entry in enumerate(ranked): pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - alt = " · alt region" if entry.get('diverse') else "" k = entry.get('n_ancillas', len(entry.get('ancillas') or [])) dd_opts.append(( f"k={k} · #{entry.get('rank_in_stratum', i + 1)} · " - f"LQS {pct}{suffix}{alt} · measured", i)) + f"LQS {pct}{suffix}{_source_tag(entry)} · measured", i)) _seed_layout_dropdown(ranked, dd_opts) circ = [e['lqs_circuit'] for e in ranked if e.get('lqs_circuit') is not None] @@ -1238,8 +1215,8 @@ def _entry_label(entry): k = len(entry['ancillas']) pct, is_tmpl = _entry_lqs_pct(entry) suffix = " (template)" if is_tmpl else "" - alt = " · alt region" if entry.get('diverse') else "" # region-diversity flag - return f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}{alt}" + return (f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" + f"{_source_tag(entry)}") def _short_reason(reason): """Map a full ineligibility reason to a compact form for the one-line diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 9007f8a..2dc3e02 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -42,6 +42,7 @@ def _build(monkeypatch): # build() returns the assembled tree rather than storing it; keep it so # tests can walk the real sidebar/figure widget graph. b._test_full_ui, _fig = b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only return b, state @@ -230,61 +231,7 @@ def test_benchmark_widgets_do_not_share_a_mutated_layout(monkeypatch): assert b.tb_bench_qpu.layout.display == 'none' -# ── t7: the search-engine selector ───────────────────────────────────────── - -def test_engine_selector_defaults_to_exhaustive(monkeypatch): - """Guided stays opt-in until iqmapper.evaluation says otherwise.""" - b, _ = _build(monkeypatch) - assert b.dd_search_engine.value == 'vf2' - assert [v for _label, v in b.dd_search_engine.options] == [ - 'vf2', 'guided', 'hybrid'] - # Guided-only params are hidden while Exhaustive is selected. - assert b.bench_guided_box.layout.display == 'none' - assert b.int_beam_width.value == 200 - assert b.int_refine_top.value == 5 - - b.dd_search_engine.value = 'guided' - assert b.bench_guided_box.layout.display == '' - b.dd_search_engine.value = 'vf2' - assert b.bench_guided_box.layout.display == 'none' - - -def test_engine_selector_lives_in_the_advanced_accordion(monkeypatch): - b, _ = _build(monkeypatch) - inside = _descendants(b.lucj_advanced_acc) - for widget, name in ((b.dd_search_engine, 'dd_search_engine'), - (b.bench_guided_box, 'guided params')): - assert any(w is widget for w in inside), f'{name} not in Advanced' - - -def test_selecting_guided_routes_the_sweep_to_guided_sweep(monkeypatch): - """The dispatch helper must call the guided engine with the beam params.""" - b, _ = _build(monkeypatch) - seen = {} - - def _spy(norb, backend, props, **kwargs): - seen['norb'] = norb - seen['kwargs'] = kwargs - return {'strata': {}, 'k_max_effective': 1, 'min_bridges': 1, - 'vf2_truncated': False, 'n_raw_embeddings': 0, - 'n_candidates_scored': 0, 'excluded_qubits': [], - 'per_stratum': {}, 'mapping_cap': None, 'engine': 'guided', - 'refined_count': 0, 'refine_attempted': 0} - - monkeypatch.setattr('iqmapper.guided_search.guided_sweep', _spy) - b.dd_search_engine.value = 'guided' - b.int_beam_width.value = 64 - b.int_refine_top.value = 2 - b.lucj_ancilla_dd.value = -1 # sweep mode - b.btn_lucj_run.click() - - assert seen, 'guided_sweep was never called' - assert seen['kwargs']['beam_width'] == 64 - assert seen['kwargs']['refine_top'] == 2 - # VF2-only knobs must not be forwarded to a bounded beam search. - assert 'mapping_cap' not in seen['kwargs'] - assert 'hybrid' not in seen['kwargs'] - +# ── t7: the search (engine widgets: see test_search_ui.py) ───────────────── def test_exhaustive_still_routes_to_the_frozen_sweep(monkeypatch): b, _ = _build(monkeypatch) @@ -322,105 +269,6 @@ def test_guided_results_render_through_the_existing_display(monkeypatch): assert best, 'best-per-k line empty for a guided result' -def test_status_line_names_the_engine_and_refinement_tally(monkeypatch): - b, _ = _build(monkeypatch) - seen = {} - - def _spy(norb, backend, props, **kwargs): - seen['called'] = True - entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], - 'ancillas': [4], 'bridge_slots': (0,), - 'product_score': 0.9, 'additive_score': 0.1, - 'lqs_circuit': 0.8, 'rank_in_stratum': 1, - 'source': 'guided', 'refined': True} - return {'strata': {1: [entry]}, 'k_max_effective': 1, 'min_bridges': 1, - 'vf2_truncated': False, 'n_raw_embeddings': 3, - 'n_candidates_scored': 3, 'excluded_qubits': [], - 'per_stratum': {1: {'n_direct': 3, 'n_derived': 0, - 'truncated': False, 'shuffled': False}}, - 'mapping_cap': None, 'engine': 'guided', - 'refined_count': 2, 'refine_attempted': 5} - - monkeypatch.setattr('iqmapper.guided_search.guided_sweep', _spy) - b.dd_search_engine.value = 'guided' - b.lucj_ancilla_dd.value = -1 - b.btn_lucj_run.click() - - assert seen.get('called') - status = b.lbl_lucj_status.value - assert 'engine: guided' in status, status - assert 'refined 2/5' in status, status - - -def test_hybrid_shows_the_threshold_and_the_beam_params(monkeypatch): - b, _ = _build(monkeypatch) - assert b.int_guided_max_k.value == 1 and b.int_guided_max_k.min == 0 - assert b.int_guided_max_k.layout.display == 'none' - # Toggled at runtime, so it must not share the builder-wide layout. - assert b.int_guided_max_k.layout is not b.txt_auto.layout - assert b.int_guided_max_k.layout is not b.bench_guided_box.layout - assert any(w is b.int_guided_max_k - for w in _descendants(b.lucj_advanced_acc)) - - b.dd_search_engine.value = 'hybrid' - assert b.int_guided_max_k.layout.display == '' - assert b.bench_guided_box.layout.display == '' - b.dd_search_engine.value = 'guided' - assert b.int_guided_max_k.layout.display == 'none' - assert b.bench_guided_box.layout.display == '' - b.dd_search_engine.value = 'vf2' - assert b.int_guided_max_k.layout.display == 'none' - assert b.txt_auto.layout.display != 'none' - - -def test_selecting_hybrid_routes_the_sweep_to_hybrid_sweep(monkeypatch): - b, _ = _build(monkeypatch) - seen = {} - - def _spy(norb, backend, props, **kwargs): - seen['kwargs'] = kwargs - return dict(_empty_sweep(), engine='hybrid', guided_max_k=2, - refined_count=0, refine_attempted=0) - - monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', _spy) - b.dd_search_engine.value = 'hybrid' - b.int_guided_max_k.value = 2 - b.int_beam_width.value = 64 - b.lucj_ancilla_dd.value = -1 - b.btn_lucj_run.click() - - kw = seen['kwargs'] - assert kw['guided_max_k'] == 2 - assert kw['guided_kwargs']['beam_width'] == 64 - # VF2-only knobs reach the VF2 half only. - assert {'hybrid', 'mapping_cap', 'diverse_cap'} <= set(kw['vf2_kwargs']) - for key in ('hybrid', 'mapping_cap', 'diverse_cap'): - assert key not in kw - assert 'top_n' in kw and 'circuit_score_fn' in kw - - -def test_status_line_names_the_hybrid_threshold(monkeypatch): - b, _ = _build(monkeypatch) - entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], - 'ancillas': [4], 'bridge_slots': (0,), - 'product_score': 0.9, 'additive_score': 0.1, - 'lqs_circuit': 0.8, 'rank_in_stratum': 1, 'source': 'guided'} - res = dict(_empty_sweep(), strata={1: [entry]}, - per_stratum={1: {'n_direct': 1, 'n_derived': 0, - 'truncated': False, 'shuffled': False, - 'engine': 'guided'}}, - engine='hybrid', guided_max_k=1, refined_count=1, - refine_attempted=3, reservoir_notices=[]) - monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', - lambda *a, **k: res) - b.dd_search_engine.value = 'hybrid' - b.lucj_ancilla_dd.value = -1 - b.btn_lucj_run.click() - status = b.lbl_lucj_status.value - assert 'engine: hybrid (guided ≤ k1)' in status, status - assert 'refined 1/3' in status, status - - # ── t8: diverse enumeration ──────────────────────────────────────────────── def test_diverse_enumeration_checkbox_defaults_on(monkeypatch): diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py index becacac..53ba600 100644 --- a/tests/test_auto_subpanels.py +++ b/tests/test_auto_subpanels.py @@ -52,6 +52,7 @@ def _build(monkeypatch): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only return b, state diff --git a/tests/test_combined_sweep.py b/tests/test_combined_sweep.py new file mode 100644 index 0000000..bcd8ada --- /dev/null +++ b/tests/test_combined_sweep.py @@ -0,0 +1,282 @@ +"""The combined search: exhaustive and guided on every stratum, best of both. + +The guarantee that matters is per stratum: the combined best is never worse +than either engine's best. Around it: a layout found by both is listed once, +every entry says where it came from, and with the guided half off the result +is the exhaustive sweep's own. +""" +import numpy as np +import pytest +import rustworkx + +from iqmapper import ancilla_sweep, engine_select, guided_search +from iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.auto_lucj import _make_backend_cmap_pygraph +from iqmapper.engine_select import combined_sweep +from iqmapper.guided_search import guided_sweep + +from test_ancilla_sweep import FakeProps, make_backend +from test_guided_induced import _SeededProps, _backend_from + +SOURCES = {'exhaustive', 'guided', 'both'} + +#: Keeps the exhaustive half quick on the larger lattices. A capped VF2 is +#: also where the guided half has the most to add. +CAP = 300 + + +def _identity(entry): + return (frozenset(entry['alpha']) | frozenset(entry['beta']) + | frozenset(entry['ancillas']), frozenset(entry['ancillas'])) + + +def _lqs_scorer(backend, props, gate='cz'): + """Circuit-level LQS shape: (1 - readout) over the layout's qubits times + (1 - gate error) over every coupler between two of them, once each.""" + graph = _make_backend_cmap_pygraph(backend=backend) + neighbours = {q: set(graph.neighbors(q)) for q in graph.node_indices()} + readout, gate_err = {}, {} + + def _r(q): + if q not in readout: + readout[q] = float(props.readout_error(q)) + return readout[q] + + def _e(u, v): + key = (u, v) if u < v else (v, u) + if key not in gate_err: + gate_err[key] = float(props.gate_error(gate, key)) + return gate_err[key] + + def _score(entry): + qubits = set(entry['alpha']) | set(entry['beta']) | set(entry['ancillas']) + fid = 1.0 + for q in qubits: + fid *= 1.0 - _r(q) + for n in neighbours.get(q, ()): + if n in qubits and q < n: + fid *= 1.0 - _e(q, n) + return fid + return _score + + +def _best(result, k): + entries = result['strata'].get(k) or [] + return max((e['lqs_circuit'] for e in entries + if e.get('lqs_circuit') is not None), default=None) + + +def _assert_best_of_both(norb, backend, props, **kw): + scorer = _lqs_scorer(backend, props) + args = dict(min_bridges=1, top_n=3, circuit_score_fn=scorer, **kw) + vf2 = sweep_ancilla_layouts(norb, backend, props, mapping_cap=CAP, **args) + guided = guided_sweep(norb, backend, props, **args) + combined = combined_sweep(norb, backend, props, mapping_cap=CAP, **args) + assert set(combined['strata']) == set(vf2['strata']) + for k in combined['strata']: + engines = [b for b in (_best(vf2, k), _best(guided, k)) if b is not None] + best = _best(combined, k) + assert best is not None and best >= max(engines), ( + f'norb={norb} k={k}: combined {best} < engines {engines}') + return vf2, guided, combined + + +# ── best of both, per stratum ─────────────────────────────────────── + +@pytest.mark.parametrize('d, norb', [(5, 6), (5, 8), (7, 12)]) +def test_combined_best_is_at_least_either_engine_on_heavy_hex(d, norb): + undirected = [tuple(e) for e in + rustworkx.generators.heavy_hex_graph(d).edge_list()] + backend = _backend_from(undirected) + props = _SeededProps(1 + max(max(e) for e in undirected), seed=d + norb) + _assert_best_of_both(norb, backend, props) + + +@pytest.mark.parametrize('norb', [8, 12]) +def test_combined_best_is_at_least_either_engine_on_fake_fez(norb): + fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + backend = fake_provider.FakeFez() + _assert_best_of_both(norb, backend, backend.properties()) + + +def test_combined_best_holds_with_the_diversity_quota(): + backend, props = make_backend(), FakeProps() + _assert_best_of_both(6, backend, props, diversity_threshold=0.8) + + +# ── dedupe and source tags ────────────────────────────────────────── + +def test_a_layout_found_by_both_engines_is_listed_once_as_both(): + backend, props = make_backend(), FakeProps() + scorer = _lqs_scorer(backend, props) + args = dict(min_bridges=1, top_n=5, circuit_score_fn=scorer) + vf2 = sweep_ancilla_layouts(4, backend, props, **args) + guided = guided_sweep(4, backend, props, **args) + combined = combined_sweep(4, backend, props, **args) + + saw_both = False + for k, entries in combined['strata'].items(): + keys = [_identity(e) for e in entries] + assert len(keys) == len(set(keys)), f'duplicate layout at k={k}' + in_vf2 = {_identity(e) for e in vf2['strata'][k]} + in_guided = {_identity(e) for e in guided['strata'][k]} + for entry, key in zip(entries, keys): + assert entry['source'] in SOURCES + expected = ('both' if key in in_vf2 and key in in_guided + else 'guided' if key in in_guided else 'exhaustive') + assert entry['source'] == expected, (k, key) + saw_both = saw_both or expected == 'both' + assert [e['rank_in_stratum'] for e in entries] == list( + range(1, len(entries) + 1)) + assert len(entries) <= 5 + assert saw_both, 'fixture no longer has a layout both engines find' + + +def _entry(alpha, beta, ancillas, lqs): + return {'layout': alpha + beta, 'alpha': alpha, 'beta': beta, + 'ancillas': ancillas, 'product_score': lqs, 'lqs_circuit': lqs, + 'rank_in_stratum': 1, 'source': 'stub'} + + +def _sweep(strata): + return {'strata': strata, 'k_max_effective': 2, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 1, + 'n_candidates_scored': 1, 'excluded_qubits': [], + 'per_stratum': {}, 'mapping_cap': 2000} + + +def test_guided_winners_lists_strata_whose_best_only_guided_found( + monkeypatch): + shared = ([0, 1], [2, 3], [4, 5]) + monkeypatch.setattr(ancilla_sweep, 'sweep_ancilla_layouts', + lambda *a, **k: _sweep({ + 2: [_entry(*shared, 0.5)], + 1: [_entry([0, 1], [2, 3], [4], 0.6)]})) + monkeypatch.setattr(guided_search, 'guided_sweep', + lambda *a, **k: _sweep({ + 2: [_entry(*shared, 0.5)], + 1: [_entry([6, 7], [8, 9], [10], 0.7)]})) + res = combined_sweep(2, None, None, min_bridges=1, top_n=3, + circuit_score_fn=lambda e: e['lqs_circuit']) + assert res['guided_winners'] == [1] + assert [e['source'] for e in res['strata'][2]] == ['both'] + assert [e['source'] for e in res['strata'][1]] == ['guided', 'exhaustive'] + assert [e['lqs_circuit'] for e in res['strata'][1]] == [0.7, 0.6] + + +def test_a_layout_guided_lists_twice_stays_guided(monkeypatch): + """Guided can return one layout twice (same qubits, another chain + order). The second copy must not turn the first into 'both'.""" + twin_a = _entry([6, 7], [8, 9], [10], 0.7) + twin_b = _entry([7, 6], [9, 8], [10], 0.7) + monkeypatch.setattr(ancilla_sweep, 'sweep_ancilla_layouts', + lambda *a, **k: _sweep({ + 1: [_entry([0, 1], [2, 3], [4], 0.6)]})) + monkeypatch.setattr(guided_search, 'guided_sweep', + lambda *a, **k: _sweep({1: [twin_a, twin_b]})) + res = combined_sweep(2, None, None, min_bridges=1, top_n=3, + circuit_score_fn=lambda e: e['lqs_circuit']) + assert [(e['lqs_circuit'], e['source']) for e in res['strata'][1]] == [ + (0.7, 'guided'), (0.6, 'exhaustive')] + assert res['guided_winners'] == [1] + + +def test_the_diversity_quota_is_the_exhaustive_sweeps_own(): + assert (engine_select._select_with_diversity + is ancilla_sweep._select_with_diversity) + + +# ── guided off reproduces the exhaustive sweep ────────────────────── + +def _strip(result, extra_keys): + out = {k: v for k, v in result.items() if k not in extra_keys} + out['strata'] = {k: [{f: v for f, v in e.items() if f != 'source'} + for e in entries] + for k, entries in result['strata'].items()} + return out + + +@pytest.mark.parametrize('kw', [ + {}, + {'circuit_score_fn': 'lqs'}, + {'circuit_score_fn': 'lqs', 'diversity_threshold': 0.8}, +]) +def test_without_guided_the_result_is_the_exhaustive_sweep(monkeypatch, kw): + backend, props = make_backend(), FakeProps() + if kw.get('circuit_score_fn') == 'lqs': + kw = dict(kw, circuit_score_fn=_lqs_scorer(backend, props)) + vf2 = sweep_ancilla_layouts(6, backend, props, min_bridges=1, top_n=4, + **kw) + monkeypatch.setattr(guided_search, 'guided_sweep', + lambda *a, **k: pytest.fail('guided ran')) + res = combined_sweep(6, backend, props, use_guided=False, min_bridges=1, + top_n=4, beam_width=50, **kw) + + added = {'engine', 'use_guided', 'guided_winners', 'guided_error'} + assert added <= set(res) + assert res['engine'] == 'combined' and res['use_guided'] is False + assert res['guided_winners'] == [] and res['guided_error'] is None + assert _strip(res, added) == _strip(vf2, set()) + assert all(e['source'] == 'exhaustive' + for entries in res['strata'].values() for e in entries) + + +# ── routing and failure ───────────────────────────────────────────── + +def test_engine_specific_arguments_reach_their_own_engine(monkeypatch): + seen = {} + + def _spy(name): + def _run(norb, backend, props, **k): + seen[name] = k + return {'strata': {}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': False, 'n_raw_embeddings': 0, + 'n_candidates_scored': 0, 'excluded_qubits': [], + 'per_stratum': {}, 'mapping_cap': 2000} + return _run + + monkeypatch.setattr(ancilla_sweep, 'sweep_ancilla_layouts', _spy('vf2')) + monkeypatch.setattr(guided_search, 'guided_sweep', _spy('guided')) + combined_sweep(8, None, None, min_bridges=1, top_n=3, exclude_qubits={2}, + circuit_score_fn=None, diversity_threshold=0.8, + hybrid=False, mapping_cap=500, diverse_cap=True, + beam_width=64, refine_top=2) + shared = {'min_bridges', 'top_n', 'exclude_qubits', 'circuit_score_fn', + 'diversity_threshold'} + assert set(seen['vf2']) == shared | {'hybrid', 'mapping_cap', + 'diverse_cap'} + assert set(seen['guided']) == shared | {'beam_width', 'refine_top'} + assert seen['vf2']['exclude_qubits'] == seen['guided']['exclude_qubits'] + + +def test_an_unknown_argument_is_refused(): + with pytest.raises(TypeError, match='beam_wdth'): + combined_sweep(4, make_backend(), FakeProps(), beam_wdth=3) + + +def test_a_guided_dead_end_leaves_the_exhaustive_result(): + """norb=6, k=2 on the ladder: a 5-wide beam completes nothing.""" + backend, props = make_backend(), FakeProps() + vf2 = sweep_ancilla_layouts(6, backend, props, min_bridges=2, top_n=3) + res = combined_sweep(6, backend, props, min_bridges=2, top_n=3, + beam_width=5) + assert 'no complete zigzag embedding' in res['guided_error'] + assert res['guided_winners'] == [] + assert ([[_identity(e) for e in v] for v in res['strata'].values()] + == [[_identity(e) for e in v] for v in vf2['strata'].values()]) + + +def test_run_level_fields_come_from_the_exhaustive_half(): + backend, props = make_backend(), FakeProps() + vf2 = sweep_ancilla_layouts(6, backend, props, min_bridges=1, top_n=3) + guided = guided_sweep(6, backend, props, min_bridges=1, top_n=3) + res = combined_sweep(6, backend, props, min_bridges=1, top_n=3) + for key in ('vf2_truncated', 'reservoir', 'reservoir_notices', + 'mapping_cap', 'k_max_effective', 'min_bridges', + 'excluded_qubits', 'per_stratum'): + assert res[key] == vf2[key], key + assert res['n_candidates_scored'] == (vf2['n_candidates_scored'] + + guided['n_candidates_scored']) + assert res['n_raw_embeddings'] == (vf2['n_raw_embeddings'] + + guided['n_raw_embeddings']) + assert res['beam_width'] == guided['beam_width'] diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index ce01be2..b34ca1b 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -64,6 +64,7 @@ def _build(monkeypatch, spawn=_sync_spawn): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only # current readout with one outlier at qubit 5 (16 samples → floor can judge). ro = np.array([0.01] * 16) ro[5] = 0.5 diff --git a/tests/test_joint_plan_ui.py b/tests/test_joint_plan_ui.py index 3d4aa5a..0925766 100644 --- a/tests/test_joint_plan_ui.py +++ b/tests/test_joint_plan_ui.py @@ -1,4 +1,4 @@ -"""The Planner selector: Sequential (default, unchanged) vs Joint. +"""The planner checkbox: Sequential (default, unchanged) vs Joint. Headless, offline. Planner engines are monkeypatched with canned results except in the batch-scan test, which runs the real joint planner on two stub @@ -39,21 +39,22 @@ def _spy(norbs, backend, props, **kwargs): def test_planner_defaults_to_sequential_with_joint_params_hidden(monkeypatch): b, _ = _build(monkeypatch) - assert b.dd_planner.value == 'sequential' - assert [v for _l, v in b.dd_planner.options] == ['sequential', 'joint'] + assert b.chk_joint_plan.value is False + assert b.chk_joint_plan.description == 'Optimize placement jointly' + assert not hasattr(b, 'dd_planner') assert b.int_plans_kept.value == 4 assert b.int_cands_per_circuit.value == 3 assert b.ft_boundary_penalty.value == 0.0 assert b.joint_params_box.layout.display == 'none' b.intra_qpu_mode.value = True b._build_auto_lucj_view() - for w in (b.dd_planner, b.joint_params_box): + for w in (b.chk_joint_plan, b.joint_params_box): assert any(c is w for c in b._auto_multi_panel.children) def test_planner_widgets_own_their_layouts(monkeypatch): b, _ = _build(monkeypatch) - widgets = (b.dd_planner, b.joint_params_box, b.int_plans_kept, + widgets = (b.chk_joint_plan, b.joint_params_box, b.int_plans_kept, b.int_cands_per_circuit, b.ft_boundary_penalty) for w in widgets: assert w.layout is not b.txt_auto.layout @@ -64,10 +65,10 @@ def test_planner_widgets_own_their_layouts(monkeypatch): def test_joint_reveals_its_params(monkeypatch): b, _ = _build(monkeypatch) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True assert b.joint_params_box.layout.display == '' assert b.txt_auto.layout.display != 'none' - b.dd_planner.value = 'sequential' + b.chk_joint_plan.value = False assert b.joint_params_box.layout.display == 'none' @@ -106,7 +107,7 @@ def test_joint_dispatches_with_its_params_and_reports_the_gain(monkeypatch): result, _ = _result() seen = _patch_joint(monkeypatch, _joint(result)) _patch_engine(monkeypatch, None) # must not be called - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True b.int_plans_kept.value = 6 b.int_cands_per_circuit.value = 2 b.ft_boundary_penalty.value = 0.25 @@ -128,7 +129,7 @@ def test_joint_that_places_more_circuits_says_so(monkeypatch): result, _ = _result() _patch_joint(monkeypatch, _joint(result, greedy_placed=1, greedy_total=0.9)) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() status = b.lbl_lucj_multi.value @@ -140,38 +141,39 @@ def test_joint_names_shared_couplers(monkeypatch): b, _ = _build(monkeypatch) result, _ = _result() _patch_joint(monkeypatch, _joint(result, boundary_couplers=[(47, 48)])) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() assert 'shared couplers: 47–48' in b.lbl_lucj_multi.value -def test_joint_search_fn_honours_the_selected_engine(monkeypatch): +@pytest.mark.parametrize('guided', [True, False]) +def test_joint_searches_with_the_combined_search(monkeypatch, guided): b, _ = _build(monkeypatch) result, _ = _result() seen = _patch_joint(monkeypatch, _joint(result)) - b.dd_planner.value = 'joint' - b.dd_search_engine.value = 'hybrid' - b.int_guided_max_k.value = 2 + b.chk_joint_plan.value = True + b.chk_guided_search.value = guided + b.int_beam_width.value = 64 b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() - hybrid_calls = [] - monkeypatch.setattr('iqmapper.engine_select.hybrid_sweep', + calls = [] + monkeypatch.setattr('iqmapper.engine_select.combined_sweep', lambda norb, backend, props, **k: - hybrid_calls.append((norb, k)) or {'strata': {}}) + calls.append((norb, k)) or {'strata': {}}) seen['kwargs']['search_fn'](8, exclude_qubits={3}, min_bridges=1) - norb, k = hybrid_calls[0] - assert norb == 8 and k['guided_max_k'] == 2 + norb, k = calls[0] + assert norb == 8 and k['use_guided'] is guided assert k['exclude_qubits'] == {3} and k['min_bridges'] == 1 - assert 'mapping_cap' in k['vf2_kwargs'] + assert k['beam_width'] == 64 and 'mapping_cap' in k def test_joint_pending_line_shows_the_worst_case_count(monkeypatch): queued = [] b, _ = _build(monkeypatch, spawn=lambda fn, on_done=None, on_error=None: queued.append(fn)) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True b.int_plans_kept.value = 4 b.lucj_multi_norbs.value = '8, 8, 8' b.btn_lucj_multi_sweep.click() @@ -191,7 +193,7 @@ def test_joint_replan_uses_the_joint_planner(monkeypatch): lambda r, i, c: called.append((r, i, c)) or joint) monkeypatch.setattr(ms, 'replan_from', lambda *a: pytest.fail( 'sequential replan used for a joint result')) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() _dropdowns(b.lucj_multi_detail_box)[0].value = 1 @@ -255,7 +257,8 @@ def _get_props(backend): real_scan = qs.scan_qpus monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: captured.setdefault( 'res', real_scan(*a, **k))) - b.dd_planner.value = 'joint' + b.chk_joint_plan.value = True + b.chk_guided_search.value = True # both engines, real ones b.lucj_multi_norbs.value = '4, 4' b.btn_scan_batch.click() diff --git a/tests/test_search_ui.py b/tests/test_search_ui.py new file mode 100644 index 0000000..547872a --- /dev/null +++ b/tests/test_search_ui.py @@ -0,0 +1,170 @@ +"""The search controls: one "Guided search" checkbox (default on) instead of +an engine selector, the combined search behind every Auto run, the source of +each candidate in its label, and no "alt region" suffix. + +Headless, offline; the combined search is stubbed where only the UI is under +test. +""" +import inspect + +import pytest + +from test_auto_panel_ui_polish import _descendants, _fake_device + + +def _build(monkeypatch): + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + state = SessionState() + for key, val in dict( + active_backend=object(), active_backend_name='ibm_here', + active_chip='stub_chip', active_service=None, + available_backends=[], props_warning=None, + initial_props=object(), active_ansatz='lucj', + active_vendor='IBM', active_coords=[], custom_colors=[], + cal_history_dates=['_seed_']).items(): + setattr(state, key, val) + b = MapperUIBuilder(state) + b._test_full_ui, _fig = b.build() + return b + + +def _entry(ancillas, lqs, source, rank=1): + return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': ancillas, 'bridge_slots': (0,), 'product_score': lqs, + 'additive_score': 0.1, 'lqs_circuit': lqs, 'rank_in_stratum': rank, + 'source': source, 'diverse': source == 'guided'} + + +def _result(strata, guided_winners=()): + return {'strata': strata, 'k_max_effective': max(strata), + 'min_bridges': min(strata), 'vf2_truncated': False, + 'n_raw_embeddings': 3, 'n_candidates_scored': 3, + 'excluded_qubits': [], + 'per_stratum': {k: {'n_direct': 1, 'n_derived': 0, + 'truncated': False, 'shuffled': False} + for k in strata}, + 'mapping_cap': 2000, 'reservoir': {}, 'reservoir_notices': [], + 'engine': 'combined', 'use_guided': True, + 'guided_winners': list(guided_winners), 'guided_error': None} + + +def _stub_combined(monkeypatch, result): + seen = [] + monkeypatch.setattr('iqmapper.engine_select.combined_sweep', + lambda norb, backend, props, **k: + seen.append(k) or result) + return seen + + +def _run(b): + b.lucj_ancilla_dd.value = -1 # sweep mode + b.btn_lucj_run.click() + + +# ── the checkbox ──────────────────────────────────────────────────── + +def test_guided_search_is_one_checkbox_on_by_default(monkeypatch): + b = _build(monkeypatch) + chk = b.chk_guided_search + assert chk.value is True and chk.description == 'Guided search' + assert 'README: Search engine' in chk.tooltip and len(chk.tooltip) <= 90 + assert any(w is chk for w in _descendants(b.lucj_advanced_acc)) + + +def test_the_engine_dropdown_and_threshold_are_gone(monkeypatch): + b = _build(monkeypatch) + assert not hasattr(b, 'dd_search_engine') + assert not hasattr(b, 'int_guided_max_k') + descriptions = [getattr(w, 'description', '') or '' + for w in _descendants(b._test_full_ui)] + assert not any('Search engine' in d for d in descriptions) + assert not any('Guided up to' in d for d in descriptions) + + +def test_the_checkboxes_own_their_layouts(monkeypatch): + b = _build(monkeypatch) + toggled = (b.chk_guided_search, b.bench_guided_box, b.chk_joint_plan, + b.joint_params_box) + shared = (b.txt_auto.layout, b.chk_diverse_cap.layout, + b.chk_deep_search.layout, b.lucj_buffer_slider.layout) + for w in toggled: + assert all(w.layout is not lay for lay in shared) + assert len({id(w.layout) for w in toggled}) == len(toggled) + + +def test_beam_parameters_show_only_while_guided_is_on(monkeypatch): + b = _build(monkeypatch) + assert b.bench_guided_box.layout.display == '' + b.chk_guided_search.value = False + assert b.bench_guided_box.layout.display == 'none' + assert b.txt_auto.layout.display != 'none' + b.chk_guided_search.value = True + assert b.bench_guided_box.layout.display == '' + + +# ── every Auto run is the combined search ────────────────────────── + +@pytest.mark.parametrize('guided', [True, False]) +def test_the_run_calls_the_combined_search(monkeypatch, guided): + b = _build(monkeypatch) + seen = _stub_combined(monkeypatch, _result({1: [_entry([4], 0.8, + 'exhaustive')]})) + b.chk_guided_search.value = guided + b.int_beam_width.value = 64 + b.int_refine_top.value = 2 + _run(b) + assert seen, 'combined_sweep was not called' + k = seen[0] + assert k['use_guided'] is guided + assert k['beam_width'] == 64 and k['refine_top'] == 2 + assert {'mapping_cap', 'hybrid', 'diverse_cap', 'top_n', + 'circuit_score_fn'} <= set(k) + + +# ── status line ───────────────────────────────────────────────────── + +def test_status_names_the_strata_guided_won(monkeypatch): + b = _build(monkeypatch) + _stub_combined(monkeypatch, _result( + {2: [_entry([4, 5], 0.7, 'guided')], 1: [_entry([4], 0.8, 'guided')]}, + guided_winners=[2, 1])) + _run(b) + status = b.lbl_lucj_status.value + assert '· best from guided at k=2,1' in status, status + assert 'engine:' not in status + + +def test_status_is_silent_when_guided_won_nothing(monkeypatch): + b = _build(monkeypatch) + _stub_combined(monkeypatch, _result( + {1: [_entry([4], 0.8, 'both'), _entry([4], 0.7, 'guided', rank=2)]})) + _run(b) + assert 'guided' not in b.lbl_lucj_status.value + + +# ── labels ────────────────────────────────────────────────────────── + +def test_each_candidate_label_shows_its_source(monkeypatch): + b = _build(monkeypatch) + _stub_combined(monkeypatch, _result({1: [ + _entry([4], 0.8, 'guided', rank=1), + _entry([5], 0.7, 'both', rank=2), + _entry([6], 0.6, 'exhaustive', rank=3)]}, guided_winners=[1])) + _run(b) + labels = [label for label, _ in b.dd_lucj_layout.options] + assert labels == ['k=1 · #1 · LQS 80.0% · G', + 'k=1 · #2 · LQS 70.0% · E+G', + 'k=1 · #3 · LQS 60.0% · E'] + + +def test_no_alt_region_suffix_anywhere(monkeypatch): + from iqmapper.ui import lucj_panel + assert 'alt region' not in inspect.getsource(lucj_panel) + b = _build(monkeypatch) + _stub_combined(monkeypatch, _result({1: [ + _entry([4], 0.8, 'guided'), _entry([5], 0.7, 'exhaustive', rank=2)]})) + _run(b) + assert not any('alt region' in label + for label, _ in b.dd_lucj_layout.options) diff --git a/tests/test_sweep_notices.py b/tests/test_sweep_notices.py index 20bbb73..9979c95 100644 --- a/tests/test_sweep_notices.py +++ b/tests/test_sweep_notices.py @@ -79,6 +79,7 @@ def _build(monkeypatch): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only return b diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index 9bc6574..7e335ed 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -44,6 +44,7 @@ def builder(monkeypatch): b = MapperUIBuilder(state) b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only return b @@ -116,9 +117,9 @@ def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): assert len(calls) == 1 # sweep path taken assert _labels(b.dd_lucj_layout) == [ - "k=3 · #1 · LQS 20.0%", - "k=2 · #1 · LQS 30.0%", - "k=1 · #1 · LQS 40.0%", + "k=3 · #1 · LQS 20.0% · E", + "k=2 · #1 · LQS 30.0% · E", + "k=1 · #1 · LQS 40.0% · E", ] # k descending, values are flat indices. assert [opt[1] for opt in b.dd_lucj_layout.options] == [0, 1, 2] @@ -309,9 +310,9 @@ def test_sweep_mode_label(): assert _sweep_mode_label(dv) == 'derived-only' -# ── diverse entries get a "· alt region" dropdown-label suffix ────────── +# ── a region-diversity pick carries no "alt region" suffix ────────────── -def test_diverse_entry_label_suffix(builder, monkeypatch): +def test_diverse_entry_has_no_alt_region_suffix(builder, monkeypatch): def _fake(*a, **k): def e(anc, prod, diverse): return {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], @@ -332,5 +333,5 @@ def e(anc, prod, diverse): b = builder b.btn_lucj_run.click() labels = _labels(b.dd_lucj_layout) - assert any('· alt region' in lab for lab in labels) # the diverse one - assert sum('· alt region' in lab for lab in labels) == 1 # only it + assert labels == ['k=2 · #1 · LQS 30.0% · E', 'k=2 · #2 · LQS 28.0% · E'] + assert not any('alt region' in lab for lab in labels) diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py index 33ccb72..8b3047c 100644 --- a/tests/test_ui_cleanup.py +++ b/tests/test_ui_cleanup.py @@ -63,6 +63,7 @@ def _build(monkeypatch): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only return b From b2a990dc9d1422b9b06272c09d67548dd969abd6 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Wed, 7 Oct 2026 22:12:58 -0400 Subject: [PATCH 50/66] Live-test fixes, part A: logs to a file, shorter status, complete batches first, Plans menu, joint placement by default --- CHANGELOG.md | 33 ++-- CODE_OVERVIEW.md | 2 + README.md | 70 +++++--- iqmapper/__init__.py | 9 +- iqmapper/fit_check.py | 91 ++++++++++ iqmapper/log_setup.py | 99 +++++++++++ iqmapper/mapper.py | 2 + iqmapper/ui/builder.py | 28 +-- iqmapper/ui/lucj_panel.py | 272 +++++++++++++++++++---------- tests/test_auto_panel_ui_polish.py | 38 +++- tests/test_batch_scan_active.py | 1 + tests/test_fit_check.py | 90 ++++++++++ tests/test_floor_batch_ui.py | 5 +- tests/test_joint_plan_ui.py | 78 ++++++--- tests/test_live_fixes_ui.py | 212 ++++++++++++++++++++++ tests/test_log_setup.py | 94 ++++++++++ tests/test_multi_sweep_ui.py | 23 ++- tests/test_search_ui.py | 18 +- tests/test_subpanel_persistence.py | 8 +- tests/test_sweep_notices.py | 7 +- 20 files changed, 978 insertions(+), 202 deletions(-) create mode 100644 iqmapper/fit_check.py create mode 100644 iqmapper/log_setup.py create mode 100644 tests/test_fit_check.py create mode 100644 tests/test_live_fixes_ui.py create mode 100644 tests/test_log_setup.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d2f1b4..2679d2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,9 +42,7 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). raise the circuit-level LQS. Every Auto search now runs it alongside the exhaustive search and keeps the best of both for each ancilla count, so the best layout is never worse than either engine alone. Each layout in the list - shows its source (`· E`, `· G`, `· E+G`), and the status line names the - ancilla counts where guided alone found the best one. One checkbox in - Advanced, "Guided search" (on by default), turns it off to search as 0.0.5 + shows its source (`· E`, `· G`, `· E+G`). One checkbox in Advanced, "Guided search" (on by default), turns it off to search as 0.0.5 did. The multi-QPU scan and the stability filter still use the exhaustive search. - Opt-in stability filter that excludes qubits volatile across the cached @@ -60,13 +58,13 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). comparison harness, not offered in the UI): guided search for ancilla counts up to a threshold, where the exhaustive search hits its cap and only ranks a sample, and the exhaustive search above it. -- Joint multi-circuit placement ("Optimize placement jointly", off by - default, which keeps the sequential placement): keeps several placement - plans at once instead of placing each circuit greedily, so the first circuit - no longer takes a region the next one needed. Never worse than sequential - placement, searches each circuit with the combined search, and reports - couplers shared by two circuits at buffer 0 (with an optional penalty to - avoid them). +- Joint multi-circuit placement (the default; "Fast: one circuit at a time" + in the Multi tab's Advanced places them one by one as 0.0.5 did): keeps + several placement plans at once instead of placing each circuit greedily, + so the first circuit no longer takes a region the next one needed. Never + worse than one-by-one placement, searches each circuit with the combined + search, and reports couplers shared by two circuits at buffer 0 (with an + optional penalty to avoid them). - Engine comparison harness (`python -m iqmapper.evaluation`): replays the search engines over the cached calibrations, offline, and ranks with the app's real circuit-level LQS rebuilt for every calibration (`--scorer lqs`, @@ -79,6 +77,21 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). in one short sentence, and each is explained in the README section "Understanding the messages". +### Changed +- Log messages no longer print under the notebook cell. They go to a + rotating log file in the user log directory, each distinct message once + per session; the bridge-count fallback and the search-cap statistics no + longer appear in the notices panel. +- The Auto-LUCJ result line is one short line, `✅ 12 layouts found · scored + on live · 20:41`; the layout list already shows k, LQS and source. +- Multi-circuit results open with a Plans menu of the best complete plans + (picking one places every circuit), and each circuit's alternatives list + only layouts that leave room for the circuits after it. +- Multi-circuit placement is joint by default (3 plans kept, 3 candidates per + circuit); "Fast: one circuit at a time" replaces the "Optimize placement + jointly" checkbox. The batch scan keeps one-by-one placement on every QPU + and ranks backends that fit the whole batch first. + ### Fixed - LQS counted every two-qubit gate twice on backends that list each coupler in both directions (CZ devices such as Heron), so their scores were too low diff --git a/CODE_OVERVIEW.md b/CODE_OVERVIEW.md index b60afb4..77bbf8c 100644 --- a/CODE_OVERVIEW.md +++ b/CODE_OVERVIEW.md @@ -51,6 +51,7 @@ Design rules that hold across the codebase: | `paths.py` | Path-traversal-safe file resolution (`commonpath` containment, symlink-aware) for every read/write the user can influence. | | `html_safe.py` | The one `esc()` used by every HTML widget sink. | | `async_util.py` | `default_spawn_bg`: background threads with callbacks marshaled to the main loop; errors are contained and always reach the `on_error` handler. | +| `log_setup.py` | Keeps package log records out of the notebook (a `NullHandler` on the `iqmapper` logger) and, when the UI starts, writes them to a rotating `iqmapper.log` in the user log directory, each distinct message once per session. | | `_upload.py` | Normalizes ipywidgets `FileUpload` payloads across widget versions into `(bytes, filename)`. | | `constants.py` | Device coordinate tables (Heron 156q, Nighthawk 120q), color mapping factories, palette persistence. | @@ -69,6 +70,7 @@ which one ran. | `stability_filter.py` | Stability-aware sweep: excludes qubits that are volatile across cached history (and statistical outliers), then runs the exhaustive sweep, relaxing the filter when the circuit would no longer fit. | | `multi_sweep.py` | Sequential multi-circuit placement: each circuit greedily on the best region left, with a buffer around placed ones; replan from any circuit. | | `joint_plan.py` | Joint multi-circuit planner: a beam over placement plans with an injected single-circuit search, memoised searches and boundary-coupler accounting. Same result shape as `multi_sweep`, never worse than it. | +| `fit_check.py` | Yes/no fit test for a LUCJ circuit on what is left of the chip (one induced subgraph-isomorphism check, same answer as "the sweep returns a layout"); the multi-circuit UI uses it to list only alternatives that leave room for the later circuits. | | `qpu_scan.py` | Multi-QPU scan: lists compatible backends and runs a sweep on each, isolating per-backend failures. | | `props_shim.py` | Cache-aware properties adapter for the scan: serves a backend's cached calibration arrays through the `readout_error` / `gate_error` / `score_layout` interface the engines read. | | `evaluation.py` | Offline engine comparison: replays VF2 and guided over cached calibration snapshots and tabulates per-stratum differences (CLI: `python -m iqmapper.evaluation`). | diff --git a/README.md b/README.md index a093b9f..ef9d98e 100644 --- a/README.md +++ b/README.md @@ -289,13 +289,25 @@ the reported value for that element with a notice, never a crash. The interface says what happened and what to do; the explanations live here. Tooltips that end with `· README: ` point at the matching entry below. +Technical messages (fallbacks, cap statistics, missing calibration values) go +to a log file, never under the notebook cell: `iqmapper.log` in the user log +directory (`platformdirs.user_log_dir("iqmapper")`, e.g. `~/Library/Logs/iqmapper` +on macOS), each distinct message once per session. + +### Search results + +A search ends with one line, e.g. `✅ 12 layouts found · scored on live · 20:41`: +how many layouts the list holds and which calibration scored them. Each entry +in the list carries its ancilla count, rank, LQS and source. ### Search cap The exhaustive engine enumerates candidate layouts and stops at this many. On a large chip there can be far more layouts than the cap, so it is normally -reached at low ancilla counts. When it is, the notices bar says so — raise the cap for a -more thorough (slower) search, or leave it and rely on diverse enumeration. +reached at low ancilla counts. When it is, the log file records it, and with +diverse enumeration off a ⚠️ line warns that the ranking may be +non-exhaustive — raise the cap for a more thorough (slower) search, or leave it +and rely on diverse enumeration. ### Diverse enumeration @@ -321,41 +333,51 @@ For every ancilla count the two shortlists are merged, a layout both engines found is listed once, and the usual ranking (LQS) and region-diversity choice pick the final list. The best layout is therefore never worse than either engine alone. Each entry in the layout list ends with where it came from: -`· E` exhaustive, `· G` guided, `· E+G` both. When guided alone found the best -layout for some ancilla counts, the status line says so, e.g. -`· best from guided at k=1,2`. +`· E` exhaustive, `· G` guided, `· E+G` both. **Guided search** (in Advanced, on by default) runs the guided engine. Turn it off to search with the exhaustive engine alone, as 0.0.5 did. **Beam width** and **Refine top** tune the guided engine and show only while it is on. The multi-QPU scan and the stability filter still use the exhaustive engine -only, and so does the multi-circuit planner unless **Optimize placement -jointly** is on. The engine comparison (`python -m iqmapper.evaluation`) still +only, and so does the multi-circuit planner with **Fast: one circuit at a +time** on. The engine comparison (`python -m iqmapper.evaluation`) still offers the hybrid engine, guided up to a chosen ancilla count and exhaustive above it, to compare against. ### Multi-circuit planner -By default circuits are placed one at a time (sequential), each on the best -region left, with the exhaustive engine. It is fast but short-sighted: the -first circuit can take a region that leaves the next one only a poor spot, or -none at all. - -**Optimize placement jointly** keeps several partial plans instead of one. -After each circuit it tries **Candidates per circuit** layouts on every plan it -holds and keeps the best **Plans kept** of them. It also builds the sequential -plan and returns whichever is better, so it is never worse — only slower. It -searches each circuit with the search described under *Search engine* (both -engines while **Guided search** is on). While it runs, the status shows -`joint plan · up to N searches`, the worst case. - -When it finishes, `joint plan · +X% vs sequential · N searches` compares the -two plans' totals (the product of each circuit's LQS) and counts the searches -actually run. If the joint plan fits more circuits than sequential could, it -says `places 3 vs 2 sequential` instead, since a total over more circuits is +Several circuits are planned together. Placing them one at a time, each on the +best region left, is short-sighted: the first circuit can take a region that +leaves the next one only a poor spot, or none at all. The planner keeps +several partial plans instead of one. After each circuit it tries +**Candidates per circuit** layouts (3) on every plan it holds and keeps the +best **Plans kept** (3) of them. It also builds the one-by-one plan and +returns whichever is better, so it is never worse — only slower. It searches +each circuit with the search described under *Search engine*. + +When it finishes, `✅ 2 circuits placed · +X% vs one-by-one` compares the two +plans' totals (the product of each circuit's LQS); the gain is left out when +there is none. If the joint plan fits more circuits than one-by-one could, it +says `places 3 vs 2 one-by-one` instead, since a total over more circuits is not comparable. +**Plans** lists the best complete plans, every circuit placed, e.g. +`Plan 1 · total 48.2% · C1 79.2% + C2 61.0%`; picking one places all its +circuits at once. Under it, each circuit's alternatives list only layouts +after which every later circuit still fits; the others are counted in one +line, e.g. `2 alternatives hidden: the other circuits would not fit`. + +**Fast: one circuit at a time** (in the Multi tab's Advanced, off by default) +skips the joint planning and places circuits one by one with the exhaustive +engine, as 0.0.5 did. **Plans kept**, **Candidates per circuit** and +**Boundary penalty** show only while it is off. + +**Scan batch on all QPUs** places the batch one circuit at a time on every +backend, since it runs once per QPU and speed matters there. Backends that fit +the whole batch rank first, by batch total; one that fits only part of it +reads `ibm_x — 1 of 2 circuits fit`, with no total, and cannot be opened. + **Boundary penalty** matters only at **Buffer qubits: 0**. With a buffer of 1 or more, two circuits can never touch. At 0 they can sit side by side, and a coupler between them carries gates of one circuit next to idle qubits of the diff --git a/iqmapper/__init__.py b/iqmapper/__init__.py index f7a3a9f..cd4c511 100644 --- a/iqmapper/__init__.py +++ b/iqmapper/__init__.py @@ -10,8 +10,12 @@ fires → builds a config dict → launch_mapper(config) creates SessionState and displays the main UI. """ -from .connection import _make_connection_ui -from .mapper import launch_mapper +from .log_setup import install_file_log, install_null_handler + +install_null_handler() # records never print under a notebook cell + +from .connection import _make_connection_ui # noqa: E402 +from .mapper import launch_mapper # noqa: E402 def run(): @@ -23,6 +27,7 @@ def run(): # build re-entering build() must not clobber this with a worker/None value). from .async_util import init_main_loop init_main_loop() + install_file_log() def _on_connect(vendor, backend_name, backend, chip, props, props_warning, ansatz, diff --git a/iqmapper/fit_check.py b/iqmapper/fit_check.py new file mode 100644 index 0000000..2c2aa62 --- /dev/null +++ b/iqmapper/fit_check.py @@ -0,0 +1,91 @@ +""" +fit_check.py — does a LUCJ circuit still fit? A yes/no without a search. + +The multi-circuit UI lists an alternative layout for circuit i only when every +later circuit still fits after it. Answering that with full sweeps would cost +one search per alternative per later circuit; this module answers it with one +subgraph-isomorphism test each. + +A circuit fits a graph exactly when the sweep would return at least one layout +for it: the LUCJ template with its minimum bridge count (`min_bridges`, or 1 +when unset, the sweep's own floor) embeds in the graph. Fewer bridges is a +subgraph of more, so that one test decides it. The template comes from +`guided_search.template_edges`, the graph and the exclusions from the same +`auto_lucj` helpers `multi_sweep` uses, and the test is the induced +subgraph check `auto_lucj.create_lucj_zigzag_layout` runs. +""" +import rustworkx + +from .auto_lucj import _exclude_with_buffer, _make_backend_cmap_pygraph +from .guided_search import template_edges +from .multi_sweep import _entry_qubits, _per_circuit + + +def template_graph(norb, n_bridges): + """The LUCJ zigzag template with `n_bridges` bridges, as a PyGraph.""" + graph = rustworkx.PyGraph() + graph.add_nodes_from(range(2 * norb + n_bridges)) + for u, v in template_edges(norb, n_bridges): + graph.add_edge(u, v, None) + return graph + + +def fits(norb, graph, min_bridges=None): + """True when a `norb` circuit with at least `min_bridges` bridges (1 when + None) embeds in `graph`.""" + n_bridges = 1 if min_bridges is None else int(min_bridges) + if graph.num_nodes() < 2 * norb + n_bridges: + return False + return rustworkx.is_subgraph_isomorphic(graph, + template_graph(norb, n_bridges)) + + +def remaining_graph(backend, exclude_qubits, placed, buffer_qubits): + """The coupling graph left after the hard exclusions and the circuits in + `placed` (chosen entries, in placement order), each with its buffer — + built as `multi_sweep` builds it.""" + remaining = _make_backend_cmap_pygraph(backend=backend) + for idx in remaining.node_indices(): + remaining[idx] = idx + stability = set(int(q) for q in (exclude_qubits or [])) + if stability: + remaining, _ = _exclude_with_buffer(remaining, stability, 0) + for entry in placed: + remaining, _ = _exclude_with_buffer( + remaining, set(_entry_qubits(entry)), buffer_qubits) + return remaining + + +class LaterFit: + """Answers "do circuits after i still fit if circuit i takes `entry`?" + for one multi-circuit result. Results without a usable planning context + (no backend) answer True, so nothing is hidden.""" + + def __init__(self, result): + self._ctx = (result or {}).get('_context') or {} + self._circuits = list((result or {}).get('circuits') or []) + self._cache = {} + + @property + def usable(self): + return self._ctx.get('backend') is not None and bool( + self._ctx.get('norbs')) + + def later_circuits_fit(self, index, entry): + if not self.usable: + return True + norbs = list(self._ctx['norbs']) + later = range(index + 1, len(norbs)) + if not later: + return True + placed = [c['chosen'] for c in self._circuits[:index]] + [entry] + key = tuple(frozenset(_entry_qubits(e)) for e in placed) + if key not in self._cache: + graph = remaining_graph(self._ctx['backend'], + self._ctx.get('exclude_qubits'), placed, + self._ctx.get('buffer_qubits', 1)) + self._cache[key] = all( + fits(norbs[j], graph, + _per_circuit(self._ctx.get('min_bridges'), j)) + for j in later) + return self._cache[key] diff --git a/iqmapper/log_setup.py b/iqmapper/log_setup.py new file mode 100644 index 0000000..928d064 --- /dev/null +++ b/iqmapper/log_setup.py @@ -0,0 +1,99 @@ +""" +log_setup.py — where the package's log records go. + +Records from every ``iqmapper.*`` logger stay out of the notebook: the package +logger carries a ``NullHandler``, so Python's last-resort stderr handler never +prints them under a cell. The root logger is left alone. + +When the UI starts, `install_file_log` adds a rotating log file (INFO and up) +in the user log directory and stops the package logger from propagating, so a +handler some environment put on the root logger cannot print the records +either. A message repeated with the same text is written once per session, so +a warning raised for every qubit of a chip takes one line. +""" +import logging +import logging.handlers +import os + +PACKAGE_LOGGER = 'iqmapper' +LOG_FILE_NAME = 'iqmapper.log' +MAX_BYTES = 1_000_000 +BACKUP_COUNT = 3 + +_file_handler = None + + +def install_null_handler(): + """Give the package logger a handler so records never fall through to + the last-resort stderr handler. Idempotent.""" + logger = logging.getLogger(PACKAGE_LOGGER) + if not any(isinstance(h, logging.NullHandler) for h in logger.handlers): + logger.addHandler(logging.NullHandler()) + + +class _OncePerMessage(logging.Filter): + """Lets each distinct message text through once.""" + + def __init__(self): + super().__init__() + self._seen = set() + + def filter(self, record): + try: + text = record.getMessage() + except Exception: + return True + if text in self._seen: + return False + self._seen.add(text) + return True + + +def default_log_dir(): + """The user log directory for iqmapper (platform-specific).""" + import platformdirs + return platformdirs.user_log_dir('iqmapper') + + +def install_file_log(log_dir=None): + """Attach the rotating file handler to the package logger, once. + + Returns the log file path, or None when the directory cannot be created + or the file cannot be opened; then nothing is attached and nothing is + printed. + """ + global _file_handler + if _file_handler is not None: + return _file_handler.baseFilename + try: + directory = log_dir or default_log_dir() + os.makedirs(directory, exist_ok=True) + handler = logging.handlers.RotatingFileHandler( + os.path.join(directory, LOG_FILE_NAME), maxBytes=MAX_BYTES, + backupCount=BACKUP_COUNT, encoding='utf-8', delay=True) + except Exception: + return None + handler.setLevel(logging.INFO) + handler.setFormatter(logging.Formatter( + '%(asctime)s %(levelname)s %(name)s: %(message)s')) + handler.addFilter(_OncePerMessage()) + logger = logging.getLogger(PACKAGE_LOGGER) + if logger.level == logging.NOTSET or logger.level > logging.INFO: + logger.setLevel(logging.INFO) + logger.addHandler(handler) + logger.propagate = False + _file_handler = handler + return handler.baseFilename + + +def remove_file_log(): + """Detach and close the file handler (tests, or a caller that wants the + file released).""" + global _file_handler + if _file_handler is None: + return + logger = logging.getLogger(PACKAGE_LOGGER) + logger.removeHandler(_file_handler) + logger.propagate = True + _file_handler.close() + _file_handler = None diff --git a/iqmapper/mapper.py b/iqmapper/mapper.py index a481cee..21735d7 100644 --- a/iqmapper/mapper.py +++ b/iqmapper/mapper.py @@ -21,6 +21,8 @@ def launch_mapper(config): """ from IPython.display import display, clear_output from .constants import load_custom_colors, resolve_coords + from .log_setup import install_file_log + install_file_log() backend = config.get('backend') vendor = config.get('vendor', '') diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index 7d6d7a4..5353591 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -335,7 +335,7 @@ def _run_pipeline(self): dd_lucj_layout=self.dd_lucj_layout, lbl_lucj_detail=self.lbl_lucj_detail, lucj_multi_norbs=self.lucj_multi_norbs, lucj_buffer_slider=self.lucj_buffer_slider, - chk_joint_plan=self.chk_joint_plan, + chk_fast_multi=self.chk_fast_multi, int_plans_kept=self.int_plans_kept, int_cands_per_circuit=self.int_cands_per_circuit, ft_boundary_penalty=self.ft_boundary_penalty, @@ -1602,17 +1602,18 @@ def _build_auto_lucj_widgets(self, W): layout=Layout(width='220px'), style={'description_width': '110px'}) # ── Multi-circuit planner ───────────────────────────────── - # Off (default) = Sequential, the greedy multi_sweep, unchanged. Each - # widget owns its Layout: the Joint-only box is toggled at runtime. - self.chk_joint_plan = Checkbox( + # Circuits are planned jointly by default; "Fast" places them one at a + # time (the greedy multi_sweep, unchanged). Each widget owns its + # Layout: the joint-only box is toggled at runtime. + self.chk_fast_multi = Checkbox( value=False, - description='Optimize placement jointly', + description='Fast: one circuit at a time', layout=Layout(width=W.width, margin=W.margin, min_width=W.min_width), - tooltip='plan all circuits together instead of one at a time ' - '· README: Multi-circuit planner') + tooltip='place circuits one by one instead of planning them ' + 'together · README: Multi-circuit planner') self.int_plans_kept = BoundedIntText( - value=4, min=1, max=50, + value=3, min=1, max=50, description='Plans kept:', layout=Layout(width='220px'), style={'description_width': '110px'}, @@ -1635,7 +1636,13 @@ def _build_auto_lucj_widgets(self, W): self.joint_params_box = VBox( [self.int_plans_kept, self.int_cands_per_circuit, self.ft_boundary_penalty], - layout=Layout(display='none')) + layout=Layout()) + self.multi_advanced_acc = Accordion( + children=[VBox([self.chk_fast_multi, self.joint_params_box])], + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width)) + self.multi_advanced_acc.set_title(0, '⚙️ Advanced') + self.multi_advanced_acc.selected_index = None # collapsed on open # Legacy multi-circuit button — no longer shown in the Multi subpanel # (the sweep is the single generate action). The widget + its handler # (_on_lucj_multi) and engine (get_multi_circuit_layouts) stay wired and @@ -2094,8 +2101,7 @@ def _build_auto_lucj_view(self): self.lucj_multi_norbs, self.lucj_multi_ancillas, self.lucj_buffer_slider, - self.chk_joint_plan, - self.joint_params_box, + self.multi_advanced_acc, # Legacy btn_lucj_multi intentionally omitted — the sweep button is # the single generate action. Handler/engine remain wired + pinned. self.btn_lucj_multi_sweep, diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 84aa8f7..8a440c8 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -74,10 +74,23 @@ def _k_cap_phrase(norb, k_effective): return "" +#: Message templates kept out of the notices panel. The behaviour behind them +#: is expected and needs no action, so they go to the log file only. +_LOG_ONLY_NOTICES = ( + 'Requested %d bridges does not fit on this backend', +) + + +def _log_only(record): + msg = record.msg if isinstance(record.msg, str) else '' + return any(msg.startswith(t) for t in _LOG_ONLY_NOTICES) + + class _ScanNoticeCapture(logging.Handler): """Captures WARNING+ records off the 'iqmapper' logger during a - scan, tagging each with the current backend context. emit() never raises - out — a logging hiccup must not break the scan.""" + scan, tagging each with the current backend context. Records matching + `_LOG_ONLY_NOTICES` are skipped (the log file still gets them). emit() + never raises out — a logging hiccup must not break the scan.""" def __init__(self, context_getter): super().__init__(level=logging.WARNING) @@ -86,6 +99,8 @@ def __init__(self, context_getter): def emit(self, record): try: + if _log_only(record): + return self.records.append((self._context_getter(), record.getMessage())) except Exception: pass @@ -205,7 +220,7 @@ def setup_lucj_callbacks(ctx): lucj_multi_norbs = ctx.lucj_multi_norbs lucj_multi_ancillas = ctx.lucj_multi_ancillas lucj_buffer_slider = ctx.lucj_buffer_slider - chk_joint_plan = getattr(ctx, 'chk_joint_plan', None) + chk_fast_multi = getattr(ctx, 'chk_fast_multi', None) int_plans_kept = getattr(ctx, 'int_plans_kept', None) int_cands_per_circuit = getattr(ctx, 'int_cands_per_circuit', None) ft_boundary_penalty = getattr(ctx, 'ft_boundary_penalty', None) @@ -505,20 +520,10 @@ def _run_sweep(norb, backend, props, **kwargs): return combined_sweep(norb, backend, props, use_guided=_guided_on(), **kwargs, **_guided_params()) - def _reservoir_suffix(res): - """The per-stratum cap notice, when a cap was actually reached.""" - notes = (res or {}).get('reservoir_notices') or [] - if not notes: - return "" - return "
" + "
".join(f"\u2139 {esc(n)}" for n in notes) - - def _guided_suffix(res): - """' · best from guided at k=1,2' when guided alone found a stratum's - best layout; '' otherwise.""" - ks = (res.get('guided_winners') if isinstance(res, dict) else None) or [] - if not ks: - return "" - return " · best from guided at k=" + ",".join(str(k) for k in ks) + def _log_reservoir_notices(res): + """The per-stratum cap notices go to the log file, not the UI.""" + for note in (res or {}).get('reservoir_notices') or []: + _log.info("%s", note) def _source_tag(entry): """' · G' (guided only), ' · E+G' (both engines) or ' · E' @@ -537,30 +542,31 @@ def _on_guided_toggle(_change=None): chk_guided_search.observe(_on_guided_toggle, names='value') _on_guided_toggle() - # ── Multi-circuit planner: Sequential (default) or Joint ───────── + # ── Multi-circuit planner: Joint (default) or Sequential (Fast) ── def _selected_planner(): - """'joint' when "Optimize placement jointly" is checked, else - 'sequential' (also when the widget is absent).""" - return 'joint' if getattr(chk_joint_plan, 'value', False) \ - else 'sequential' + """'sequential' when "Fast: one circuit at a time" is checked, else + 'joint' (also when the widget is absent).""" + return 'sequential' if getattr(chk_fast_multi, 'value', False) \ + else 'joint' def _joint_params(): return { - 'beam_width': int(getattr(int_plans_kept, 'value', 4) or 4), + 'beam_width': int(getattr(int_plans_kept, 'value', 3) or 3), 'branch': int(getattr(int_cands_per_circuit, 'value', 3) or 3), 'boundary_penalty': float( getattr(ft_boundary_penalty, 'value', 0.0) or 0.0), } - def _run_multi(norbs, backend, props, *, sweep_kwargs, **seq_kwargs): - """Place several circuits with the selected planner. + def _run_multi(norbs, backend, props, *, sweep_kwargs, planner=None, + **seq_kwargs): + """Place several circuits with `planner`, or the selected one. Sequential passes `seq_kwargs` to `multi_sweep.sweep_multi_circuits` untouched, so each call site keeps its exact call. Joint plans with `joint_plan.plan_multi_circuits`, searching each circuit through `_run_sweep` with `sweep_kwargs`, so it uses the combined search. """ - if _selected_planner() != 'joint': + if (planner or _selected_planner()) != 'joint': from ..multi_sweep import sweep_multi_circuits return sweep_multi_circuits(norbs, backend, props, **seq_kwargs) @@ -596,35 +602,37 @@ def _joint_pending_html(n_circuits): return (f"
" f"⏳ joint plan · up to {n} searches
") - def _joint_status_html(result): - """Gain over sequential and search count; shared couplers if any.""" + def _joint_gain_text(result): + """' · +X% vs one-by-one', ' · places 3 vs 2 one-by-one', or '' + (a sequential result, or no gain to report).""" if result.get('planner') != 'joint': return "" greedy, joint = result.get('greedy_total'), result.get('joint_total') placed = len(result.get('circuits') or []) greedy_placed = result.get('greedy_placed', placed) if placed > greedy_placed: - gain = f"places {placed} vs {greedy_placed} sequential" - elif greedy and joint is not None: - gain = f"+{(joint / greedy - 1.0) * 100.0:.1f}% vs sequential" - else: - gain = "no plan" - line = (f"
joint plan · {gain} · " - f"{result.get('n_searches', 0)} searches") + return f" · places {placed} vs {greedy_placed} one-by-one" + if greedy and joint is not None: + gain = (joint / greedy - 1.0) * 100.0 + if round(gain, 1) > 0.0: + return f" · +{gain:.1f}% vs one-by-one" + return "" + + def _shared_couplers_html(result): shared = result.get('boundary_couplers') or [] - if shared: - line += ("
shared couplers: " - + ", ".join(f"{u}–{v}" for u, v in shared)) - return line + if not shared: + return "" + return ("
shared couplers: " + + ", ".join(f"{u}–{v}" for u, v in shared)) def _on_planner_change(_change=None): - """Joint-only params show only while joint placement is checked.""" + """Joint-only params show only while Fast is off.""" if joint_params_box is not None: joint_params_box.layout.display = ( '' if _selected_planner() == 'joint' else 'none') - if chk_joint_plan is not None: - chk_joint_plan.observe(_on_planner_change, names='value') + if chk_fast_multi is not None: + chk_fast_multi.observe(_on_planner_change, names='value') _on_planner_change() # Best circuit-level LQS from the most recent LOCAL sweep — quoted as the @@ -785,12 +793,10 @@ def _generate_sweep(norb): else: lbl_lucj_trunc.value = "" - # One-line summary: per-stratum LQS gradient, NOT a single - # size-biased "best LQS" (product_score always favours fewer bridges). + # One short line: how many layouts the dropdown holds and when they + # were scored. The dropdown labels carry k, LQS and source. + _log_reservoir_notices(res) if flat: - cap = _k_cap_phrase(norb, res.get('k_max_effective')) - cap_txt = f" · {esc(cap)}" if cap else "" - mode_txt = f" · {esc(_sweep_mode_label(res))}" # Provenance stamp — mirrors the scan detail's 'live · HH:MM' so the # user can SEE this number and a scan row's number were taken at # DIFFERENT moments (calibration drift), not that one is wrong. @@ -798,9 +804,8 @@ def _generate_sweep(norb): lbl_lucj_status.value = ( f"
✅ {_format_sweep_status(res)}{mode_txt}" - f"{cap_txt}{vin_txt}{_guided_suffix(res)}" - f"{_reservoir_suffix(res)}
") + f"margin:3px 0;'>✅ {len(flat)} layout" + f"{'s' if len(flat) != 1 else ''} found{vin_txt}") else: lbl_lucj_status.value = ( f"")) if any(m.get('truncated') for m in c.get('per_stratum', {}).values()): widgets.append(HTML( f"
" @@ -1909,14 +1969,12 @@ def _build_multi_override_dropdowns(result): lucj_multi_detail_box.children = widgets def _render_multi_sweep_output(result): - summary = _multi_summary_html(result) + n = len(result['circuits']) lbl_lucj_multi.value = ( f"
🧺 " - f"{len(result['circuits'])} circuit(s) placed " - f"(buffer={lucj_buffer_slider.value})
{summary}" - f"{_joint_status_html(result)}
" + f"padding:4px 8px;border-radius:4px;border:1px solid #abebc6;" + f"margin:3px 0;'>✅ {n} circuit{'s' if n != 1 else ''} placed" + f"{_joint_gain_text(result)}{_shared_couplers_html(result)}
" + _multi_failed_banner(result)) _build_multi_override_dropdowns(result) @@ -2055,11 +2113,38 @@ def _batch_line_html(res): f"· {pct}{tmpl}") fa = res.get('failed_at') if fa is not None: + # A partial batch has no batch total: it would be a product over + # fewer circuits than a complete one. parts.append(f"C{fa + 1}: does not fit") + return ' | '.join(parts) m, is_tmpl = _batch_metric(res) parts.append(f"batch: {m * 100.0:.1f}%{' (template)' if is_tmpl else ''}") return ' | '.join(parts) + def _batch_complete(res, n_circuits): + """Every circuit of the batch placed.""" + res = res or {} + return (res.get('failed_at') is None + and len(res.get('circuits') or []) == n_circuits + and n_circuits > 0) + + def _rank_batch_rows(rows, n_circuits): + """Complete batches first, by batch metric; then partial batches (more + circuits placed first); then backends that were not scanned; errors + last. A partial batch's metric is a product over fewer circuits, so + it is never compared with a complete one.""" + def _key(r): + res = r.get('sweep') + if r.get('error'): + return (3, 0, 0.0) + if not res: + return (2, 0, 0.0) + metric, _ = _batch_metric(res) + if _batch_complete(res, n_circuits): + return (0, 0, -metric) + return (1, -len(res.get('circuits') or []), -metric) + return sorted(rows, key=_key) + def _local_batch_reference(norbs): """The local multi-circuit result, if it was planned on the active backend for these norbs; else None.""" @@ -2071,23 +2156,20 @@ def _local_batch_reference(norbs): return None if list(ctx.get('norbs') or []) != list(norbs): return None + if not _batch_complete(local, len(norbs)): + return None return local - def _with_reference_row(results, active_name, local): - """Scan rows without the active backend; with a local result, a - reference row for it at its rank among the ranked rows.""" + def _with_reference_row(results, active_name, local, n_circuits): + """Scan rows without the active backend, ranked by `_rank_batch_rows`; + with a complete local result, a reference row for it at its rank.""" rows = [r for r in results if r.get('name') != active_name] - if local is None or not active_name: - return rows - metric, _ = _batch_metric(local) - ref = {'name': active_name, 'family': None, 'sweep': local, - 'best_lqs': metric, 'best_k': None, 'error': None, - 'reference': True} - pos = next((i for i, r in enumerate(rows) - if r.get('best_lqs') is None or r['best_lqs'] < metric), - len(rows)) - rows.insert(pos, ref) - return rows + if local is not None and active_name: + metric, _ = _batch_metric(local) + rows.append({'name': active_name, 'family': None, 'sweep': local, + 'best_lqs': metric, 'best_k': None, 'error': None, + 'reference': True}) + return _rank_batch_rows(rows, n_circuits) def _render_batch_results(scan_result, active_name=None, norbs=()): # ONE QPU selector over the scan_qpus-ranked batches: pick a backend, @@ -2095,8 +2177,10 @@ def _render_batch_results(scan_result, active_name=None, norbs=()): # that does not fully fit is selectable but not openable. The active # backend is QPU 1: it appears only as a reference row built from the # local multi-circuit result, never openable. + n_circuits = len(norbs) local = _local_batch_reference(norbs) - rows = _with_reference_row(scan_result['results'], active_name, local) + rows = _with_reference_row(scan_result['results'], active_name, + local, n_circuits) def _label(r): name = esc(str(r['name'])) @@ -2104,7 +2188,13 @@ def _label(r): name += ' (this QPU)' if r.get('error'): return f"{name} — ✗ error" - m, is_tmpl = _batch_metric(r.get('sweep') or {}) + res = r.get('sweep') + if not res: + return f"{name} — skipped" + if not _batch_complete(res, n_circuits): + placed = len(res.get('circuits') or []) + return f"{name} — {placed} of {n_circuits} circuits fit" + m, is_tmpl = _batch_metric(res) return (f"{name} — batch {m * 100.0:.1f}%" f"{' (template)' if is_tmpl else ''}") @@ -2163,17 +2253,17 @@ def _on_scan_batch(b): btn_scan_batch.disabled = True btn_scan_batch.description = '⏳ Scanning batch...' scan_batch_box.children = [] - if _selected_planner() == 'joint': - lbl_lucj_multi.value = _joint_pending_html(len(norbs)) kwargs = _sweep_kwargs_from_ui() buffer = lucj_buffer_slider.value active_name = getattr(state, 'active_backend_name', None) def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): excl = _batch_backend_exclusions(props, getattr(backend, 'name', None)) + # One circuit at a time on every QPU: the scan runs a batch per + # backend, so it keeps the fast sequential plan. res = _run_multi( norbs, backend, props, sweep_kwargs=kwargs, - buffer_qubits=buffer, + planner='sequential', buffer_qubits=buffer, min_bridges=min_bridges_list, top_n=kwargs['top_n'], mapping_cap=kwargs['mapping_cap'], hybrid=kwargs['hybrid'], diversity_threshold=kwargs['diversity_threshold'], @@ -2188,8 +2278,6 @@ def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): def _reset(): btn_scan_batch.disabled = False btn_scan_batch.description = '🌐 Scan batch on all QPUs' - if _selected_planner() == 'joint': - lbl_lucj_multi.value = "" # drop the pending line def _work(): from .. import qpu_scan diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 2dc3e02..c2e37f0 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -10,6 +10,8 @@ * the legacy "Score layouts" checkbox is hidden in Auto/sweep mode rather than shown greyed out, since Auto is the default the user lands on. """ +import logging + import numpy as np @@ -305,7 +307,19 @@ def test_diverse_enumeration_reaches_the_sweep(monkeypatch): assert seen.get('diverse_cap') is False -def test_the_cap_notice_is_rendered_on_the_status_line(monkeypatch): +class _Collect(logging.Handler): + def __init__(self): + super().__init__(level=0) + self.messages = [] + + def emit(self, record): + self.messages.append(record.getMessage()) + + +def test_the_cap_notice_goes_to_the_log_not_the_ui(monkeypatch): + """The file handler sits on the package logger, so a handler there sees + what the log file gets (the sweep's notice capture stops propagation).""" + import logging b, _ = _build(monkeypatch) entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.9, @@ -326,10 +340,19 @@ def test_the_cap_notice_is_rendered_on_the_status_line(monkeypatch): 'reservoir_notices': [note]}) b.lucj_ancilla_dd.value = -1 - b.btn_lucj_run.click() + pkg = logging.getLogger('iqmapper') + collect = _Collect() + monkeypatch.setattr(pkg, 'level', logging.INFO) + pkg.addHandler(collect) + try: + b.btn_lucj_run.click() + finally: + pkg.removeHandler(collect) status = b.lbl_lucj_status.value - assert 'hybrid k=1: cap reached' in status, status - assert '34,812 near-duplicates' in status + assert 'cap reached' not in status and 'near-duplicates' not in status + assert 'cap reached' not in b.lbl_lucj_notices.value + assert status.endswith('✅ 1 layout found · ' + status.split(' · ', 1)[1]) + assert any('hybrid k=1: cap reached' in m for m in collect.messages) # ── t9: one cap notice per stratum, not two ──────────────────────────────── @@ -355,8 +378,8 @@ def _capped_result(*, reservoir, notices): def test_reservoir_replaces_the_truncation_warning(monkeypatch): - """One notice for one stratum. The ℹ line already says the cap was - reached and how much was seen, so the ⚠️ banner would contradict it.""" + """A stratum the reservoir covered gets no ⚠️ banner: its cap was + reached by design, and the cap line goes to the log file.""" b, _ = _build(monkeypatch) note = ('hybrid k=3: cap reached — kept 2,000 diverse candidates, ' 'skipped 2,498 near-duplicates (of 4,498 seen)') @@ -373,8 +396,7 @@ def test_reservoir_replaces_the_truncation_warning(monkeypatch): assert b.lbl_lucj_trunc.value == '', ( f'the ⚠️ banner was not suppressed: {b.lbl_lucj_trunc.value}') status = b.lbl_lucj_status.value - assert 'hybrid k=3: cap reached' in status, status - assert 'of 4,498 seen' in status, status + assert 'cap reached' not in status, status assert 'non-exhaustive' not in status diff --git a/tests/test_batch_scan_active.py b/tests/test_batch_scan_active.py index 57ec605..d6a337b 100644 --- a/tests/test_batch_scan_active.py +++ b/tests/test_batch_scan_active.py @@ -55,6 +55,7 @@ def _backend(name): vintage='live', score_layout=lambda q: {'fidelity': 0.5}))) state.active_service = SimpleNamespace(backend=_backend) + b.chk_fast_multi.value = True # local run on the stubbed planner b.lucj_multi_norbs.value = '4, 4' return log diff --git a/tests/test_fit_check.py b/tests/test_fit_check.py new file mode 100644 index 0000000..0201744 --- /dev/null +++ b/tests/test_fit_check.py @@ -0,0 +1,90 @@ +"""The fit test agrees with the sweep: a circuit fits a graph exactly when +`sweep_ancilla_layouts` returns at least one layout for it there.""" +from types import SimpleNamespace + +import pytest +import rustworkx + +from iqmapper import fit_check +from iqmapper.ancilla_sweep import sweep_ancilla_layouts + +from test_ancilla_sweep import FakeProps, make_backend + + +def _backend(undirected, n=None): + graph = rustworkx.PyDiGraph() + n = n if n is not None else 1 + max(max(e) for e in undirected) + for _ in range(n): + graph.add_node(None) + for u, v in undirected: + graph.add_edge(u, v, None) + graph.add_edge(v, u, None) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +def ladder(width): + """Top 0..w-1, bottom w..2w-1, rung qubit 2w+j joining column j.""" + edges = [] + for j in range(width - 1): + edges += [(j, j + 1), (width + j, width + j + 1)] + for j in range(width): + edges += [(j, 2 * width + j), (2 * width + j, width + j)] + return _backend(edges) + + +def _sweep_finds(norb, backend, exclude, min_bridges): + try: + res = sweep_ancilla_layouts(norb, backend, FakeProps(), + exclude_qubits=exclude or None, + min_bridges=min_bridges, top_n=1) + except (ValueError, RuntimeError): + return False + return any(res['strata'].values()) + + +CASES = [ + # (backend factory, norb, exclusions, min_bridges) + (make_backend, 4, set(), None), + (make_backend, 8, set(), None), + (make_backend, 8, set(), 2), + (make_backend, 8, {3}, None), # good block cut + (make_backend, 8, {3, 27}, None), # both blocks cut + (make_backend, 6, {16}, 1), # a bridge qubit gone + (make_backend, 9, set(), None), # longer than a block + (lambda: ladder(5), 3, set(), None), + (lambda: ladder(5), 3, {12}, None), # middle rung gone + (lambda: ladder(5), 5, {10}, None), # first rung gone + (lambda: ladder(5), 5, {10}, 2), + (lambda: ladder(5), 4, {2}, None), +] + + +@pytest.mark.parametrize('factory, norb, exclude, min_bridges', CASES) +def test_fits_agrees_with_the_sweep(factory, norb, exclude, min_bridges): + backend = factory() + graph = fit_check.remaining_graph(backend, exclude, [], 0) + assert fit_check.fits(norb, graph, min_bridges) == _sweep_finds( + norb, backend, exclude, min_bridges) + + +def test_both_outcomes_are_covered(): + outcomes = {_sweep_finds(n, f(), e, m) for f, n, e, m in CASES} + assert outcomes == {True, False} + + +def test_a_placed_circuit_and_its_buffer_are_taken_out(): + backend = ladder(8) + middle = {'alpha': [3, 4], 'beta': [11, 12], 'ancillas': [19]} + left = {'alpha': [0, 1], 'beta': [8, 9], 'ancillas': [16]} + assert not fit_check.fits( + 3, fit_check.remaining_graph(backend, None, [middle], 1)) + assert fit_check.fits( + 3, fit_check.remaining_graph(backend, None, [left], 1)) + + +def test_later_fit_without_a_context_hides_nothing(): + check = fit_check.LaterFit({'circuits': [], '_context': {'stub': True}}) + assert check.usable is False + assert check.later_circuits_fit(0, {'alpha': [0], 'beta': [1], + 'ancillas': []}) is True diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index b34ca1b..a30cfd8 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -198,7 +198,7 @@ def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): # scan_qpus returns a ready-ranked batch result (ibm_hi first). monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: {'results': [ _batch_result_row('ibm_hi', 0.61, 2), - _batch_result_row('ibm_lo', 0.40, 2, failed_at=1)], + _batch_result_row('ibm_lo', 0.40, 1, failed_at=1)], 'n_scanned': 2, 'n_failed': 0, 'n_skipped': 0}) b.lucj_multi_norbs.value = '8, 8' b.btn_scan_batch.click() @@ -214,7 +214,8 @@ def test_batch_scan_rows_sorted_and_failed_labeled(monkeypatch): labels = [o[0] for o in dd.options] assert not any('' in status, status def test_joint_that_places_more_circuits_says_so(monkeypatch): @@ -129,19 +148,19 @@ def test_joint_that_places_more_circuits_says_so(monkeypatch): result, _ = _result() _patch_joint(monkeypatch, _joint(result, greedy_placed=1, greedy_total=0.9)) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() status = b.lbl_lucj_multi.value - assert 'joint plan · places 2 vs 1 sequential · 7 searches' in status - assert '%' not in status.split('joint plan')[1] + assert '✅ 2 circuits placed · places 2 vs 1 one-by-one' in status + assert '%' not in status.split('placed')[1] def test_joint_names_shared_couplers(monkeypatch): b, _ = _build(monkeypatch) result, _ = _result() _patch_joint(monkeypatch, _joint(result, boundary_couplers=[(47, 48)])) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() assert 'shared couplers: 47–48' in b.lbl_lucj_multi.value @@ -152,7 +171,7 @@ def test_joint_searches_with_the_combined_search(monkeypatch, guided): b, _ = _build(monkeypatch) result, _ = _result() seen = _patch_joint(monkeypatch, _joint(result)) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.chk_guided_search.value = guided b.int_beam_width.value = 64 b.lucj_multi_norbs.value = '8, 8' @@ -173,7 +192,7 @@ def test_joint_pending_line_shows_the_worst_case_count(monkeypatch): queued = [] b, _ = _build(monkeypatch, spawn=lambda fn, on_done=None, on_error=None: queued.append(fn)) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.int_plans_kept.value = 4 b.lucj_multi_norbs.value = '8, 8, 8' b.btn_lucj_multi_sweep.click() @@ -193,7 +212,7 @@ def test_joint_replan_uses_the_joint_planner(monkeypatch): lambda r, i, c: called.append((r, i, c)) or joint) monkeypatch.setattr(ms, 'replan_from', lambda *a: pytest.fail( 'sequential replan used for a joint result')) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.lucj_multi_norbs.value = '8, 8' b.btn_lucj_multi_sweep.click() _dropdowns(b.lucj_multi_detail_box)[0].value = 1 @@ -227,8 +246,9 @@ def test_batch_sequential_call_is_unchanged(monkeypatch): assert set(seen['kwargs']) == SEQ_MULTI_KWARGS -def test_batch_joint_scores_each_backend_with_its_own_props(monkeypatch): - """Joint batch: real planner, per-backend scorer, through the helper.""" +def test_batch_scan_places_one_by_one_even_when_fast_is_off(monkeypatch): + """The batch scan keeps the sequential plan on every backend (real + planner, per-backend scorer, through the helper).""" from types import SimpleNamespace from test_floor_batch_ui import _build as _build_batch, _ladder_backend from iqmapper import qpu_scan as qs @@ -257,14 +277,14 @@ def _get_props(backend): real_scan = qs.scan_qpus monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: captured.setdefault( 'res', real_scan(*a, **k))) - b.chk_joint_plan.value = True + b.chk_fast_multi.value = False b.chk_guided_search.value = True # both engines, real ones b.lucj_multi_norbs.value = '4, 4' b.btn_scan_batch.click() for row in captured['res']['results']: sweep = row['sweep'] - assert sweep['planner'] == 'joint' and sweep['failed_at'] is None + assert sweep.get('planner') != 'joint' and sweep['failed_at'] is None expect = 1.0 for c in sweep['circuits']: ch = c['chosen'] diff --git a/tests/test_live_fixes_ui.py b/tests/test_live_fixes_ui.py new file mode 100644 index 0000000..22cec93 --- /dev/null +++ b/tests/test_live_fixes_ui.py @@ -0,0 +1,212 @@ +"""UI fixes from the 0.1.0 live tests: technical notices kept out of the UI, +complete batches ranked first, the Plans menu and compatible alternatives, +and joint placement by default. + +Headless, offline; engines are stubbed with canned results except where the +fit check needs a real coupling graph. +""" +import logging +from types import SimpleNamespace + +import numpy as np +from ipywidgets import Dropdown, HTML + +from test_fit_check import ladder +from test_multi_sweep_ui import (_build as _build_multi, _circuit, _dropdowns, + _entry, _patch_engine, _plans, _result) +from test_search_ui import _build as _build_auto + + +# ── A2: two technical notices stay out of the UI ──────────────────── + +def test_bridge_fallback_and_cap_line_never_reach_the_ui(monkeypatch): + b = _build_auto(monkeypatch) + entry = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.9, + 'additive_score': 0.1, 'lqs_circuit': 0.8, 'rank_in_stratum': 1, + 'source': 'exhaustive'} + + def _sweep(*a, **k): + logging.getLogger('iqmapper.auto_lucj').warning( + "Requested %d bridges does not fit on this backend; falling " + "back to auto (max-then-reduce). The result may use more " + "than %d bridges.", 6, 6) + logging.getLogger('iqmapper.ancilla_sweep').warning( + "VF2 truncating to %d mappings", 2000) + return {'strata': {1: [entry]}, 'k_max_effective': 1, + 'min_bridges': 1, 'vf2_truncated': False, + 'n_raw_embeddings': 1, 'n_candidates_scored': 1, + 'excluded_qubits': [], 'per_stratum': {}, 'mapping_cap': 2000, + 'reservoir': {1: {'kept': 2000, 'skipped_similar': 9}}, + 'reservoir_notices': [ + 'hybrid k=1: cap reached — kept 2,000 diverse ' + 'candidates, skipped 9 near-duplicates (of 2,009 seen)'], + 'engine': 'combined', 'guided_winners': []} + + monkeypatch.setattr('iqmapper.engine_select.combined_sweep', _sweep) + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + shown = b.lbl_lucj_status.value + b.lbl_lucj_notices.value + assert 'does not fit on this backend' not in shown + assert 'cap reached' not in shown and 'near-duplicates' not in shown + assert 'VF2 truncating to 2000 mappings' in b.lbl_lucj_notices.value + n = len(b.dd_lucj_layout.options) + assert f'✅ {n} layout found · scored on live' in b.lbl_lucj_status.value + + +# ── A4: complete batches rank first; partial ones carry no % ──────── + +def _row(name, total, placed, n=2): + circuits = [{'circuit_idx': j, 'norb': 8, + 'chosen': {'alpha': [0, 1], 'beta': [2, 3], + 'ancillas': [4 + j], 'product_score': total, + 'lqs_circuit': total}, + 'strata': {1: []}, 'per_stratum': {}} for j in range(placed)] + sweep = {'circuits': circuits, 'total_product': total, + 'total_lqs_circuit': total, 'placed_qubits': [], + 'buffer_qubits_used': [], + 'failed_at': None if placed == n else placed, '_context': {}, + 'strata': {0: [{'product_score': total}]}} + return {'name': name, 'family': 'Heron', 'sweep': sweep, + 'best_lqs': total, 'best_k': 0, 'error': None} + + +def test_a_complete_batch_outranks_a_partial_one(monkeypatch): + from test_floor_batch_ui import _build as _build_batch + from iqmapper import qpu_scan as qs + b, _state = _build_batch(monkeypatch) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: []) + monkeypatch.setattr(qs, 'scan_qpus', lambda *a, **k: {'results': [ + _row('ibm_pittsburgh', 0.759, 1), # scan_qpus put it first + _row('ibm_fez', 0.48, 2), + {'name': 'ibm_bad', 'family': 'Heron', 'sweep': None, + 'best_lqs': None, 'best_k': None, 'error': 'boom'}], + 'n_scanned': 2, 'n_failed': 1, 'n_skipped': 0}) + b.lucj_multi_norbs.value = '8, 8' + b.btn_scan_batch.click() + + dd = next(c for c in b.scan_batch_box.children + if isinstance(c, Dropdown)) + labels = [label for label, _ in dd.options] + assert labels == ['ibm_fez — batch 48.0%', + 'ibm_pittsburgh — 1 of 2 circuits fit', + 'ibm_bad — ✗ error'] + + +# ── A5: compatible alternatives only; the Plans menu ──────────────── + +def _blocking_result(): + """norbs [2, 3] on an 8-wide ladder, buffer 1. C1 on the left leaves room + for C2; C1 in the middle cuts the ladder into two 2-wide pieces.""" + backend = ladder(8) + left = _entry([16], 0.60, lqs=0.60, rank=1) + left.update(alpha=[0, 1], beta=[8, 9]) + middle = _entry([19], 0.59, lqs=0.59, rank=2) + middle.update(alpha=[3, 4], beta=[11, 12]) + right = _entry([22], 0.58, lqs=0.58, rank=3) + right.update(alpha=[6, 7], beta=[14, 15]) + c2 = _entry([19], 0.50, lqs=0.50, rank=1) + c2.update(alpha=[3, 4, 5], beta=[11, 12, 13]) + circuits = [_circuit(0, left, {1: [left, middle, right]}), + _circuit(1, c2, {1: [c2]})] + ctx = {'backend': backend, 'norbs': [2, 3], 'buffer_qubits': 1, + 'exclude_qubits': None, 'min_bridges': None} + return {'circuits': circuits, 'total_product': 0.30, + 'total_lqs_circuit': 0.30, 'placed_qubits': [], + 'buffer_qubits_used': [], 'failed_at': None, + '_context': ctx} + + +def test_an_alternative_that_blocks_a_later_circuit_is_hidden(monkeypatch): + b, _state = _build_multi(monkeypatch) + _patch_engine(monkeypatch, _blocking_result()) + b.lucj_multi_norbs.value = '2, 3' + b.btn_lucj_multi_sweep.click() + + c1, c2 = _dropdowns(b.lucj_multi_detail_box) + assert [label.split(' · ')[1] for label, _ in c1.options] == ['#1', '#3'] + lines = [c.value for c in b.lucj_multi_detail_box.children + if isinstance(c, HTML)] + assert any('1 alternative hidden: the other circuits would not fit' in v + for v in lines) + assert len(c2.options) == 1 # the last circuit: no filter + + +def test_selecting_a_plan_applies_every_circuit(monkeypatch): + b, state = _build_multi(monkeypatch) + result, _ = _result() + p2_c0 = _entry([5], 0.55, lqs=0.70, rank=2) + p2_c1 = _entry([7], 0.57, lqs=0.40, rank=2) + plan_2 = {'circuits': [_circuit(0, p2_c0, {1: [p2_c0]}), + _circuit(1, p2_c1, {1: [p2_c1]})], + 'total_product': 0.55 * 0.57, 'total_lqs_circuit': 0.28, + 'placed_qubits': [], 'buffer_qubits_used': [], + 'boundary_couplers': [], 'failed_at': None} + plan_1 = {k: result[k] for k in ('circuits', 'total_product', + 'total_lqs_circuit', 'placed_qubits', + 'buffer_qubits_used', 'failed_at')} + result['plans'] = [plan_1, plan_2] + _patch_engine(monkeypatch, result) + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + + plans = _plans(b.lucj_multi_detail_box) + assert [label for label, _ in plans.options] == [ + 'Plan 1 · total 35.7% · C1 61.2% + C2 58.4%', + 'Plan 2 · total 28.0% · C1 70.0% + C2 40.0%'] + plans.value = 1 + assert state.layouts_data[0]['ancilla'] == ['5'] + assert state.layouts_data[1]['ancilla'] == ['7'] + assert _plans(b.lucj_multi_detail_box).value == 1 # stays selected + c1, c2 = _dropdowns(b.lucj_multi_detail_box) + assert 'LQS 70.0%' in c1.options[0][0] and 'LQS 40.0%' in c2.options[0][0] + + +# ── A6: joint by default, B=3 and M=3 ─────────────────────────────── + +def test_the_default_run_plans_jointly_with_light_params(monkeypatch): + import iqmapper.joint_plan as jp + b, _state = _build_multi(monkeypatch) + b.chk_fast_multi.value = False # the shipped default + result, _ = _result() + seen = {} + monkeypatch.setattr(jp, 'plan_multi_circuits', + lambda norbs, backend, props, **k: + seen.update(k) or dict(result, planner='joint')) + _patch_engine(monkeypatch, None) # sequential must not run + b.lucj_multi_norbs.value = '8, 8' + b.btn_lucj_multi_sweep.click() + assert (seen['beam_width'], seen['branch']) == (3, 3) + + +def test_fast_is_off_by_default_and_owns_its_layout(monkeypatch): + from test_search_ui import _build + b = _build(monkeypatch) + assert b.chk_fast_multi.value is False + assert b.chk_fast_multi.layout is not b.txt_auto.layout + assert b.chk_fast_multi.layout is not b.joint_params_box.layout + assert b.multi_advanced_acc.layout is not b.txt_auto.layout + + +# ── A7: the "(this QPU)" row needs a complete local result ────────── + +def test_a_partial_local_result_gives_no_reference_row(monkeypatch): + from test_batch_scan_active import ACTIVE, _selector, _texts, _wire + from test_floor_batch_ui import _build as _build_batch + import iqmapper.multi_sweep as ms + b, state = _build_batch(monkeypatch) + _wire(monkeypatch, b, state) + real = ms.sweep_multi_circuits + + def _partial(norbs, backend, props, **k): + res = real(norbs, backend, props, **k) + if getattr(backend, 'name', ACTIVE) == ACTIVE: + res = dict(res, circuits=res['circuits'][:1], failed_at=1) + return res + + monkeypatch.setattr(ms, 'sweep_multi_circuits', _partial) + b.btn_lucj_multi_sweep.click() + b.btn_scan_batch.click() + dd, _btn = _selector(b) + assert not any(label.startswith(ACTIVE) for label, _ in dd.options) + assert any('not included' in t for t in _texts(b)) diff --git a/tests/test_log_setup.py b/tests/test_log_setup.py new file mode 100644 index 0000000..c3d52a4 --- /dev/null +++ b/tests/test_log_setup.py @@ -0,0 +1,94 @@ +"""Package log records never print into the notebook; the log file takes +them, once per distinct message.""" +import contextlib +import logging + +import pytest + +import iqmapper # noqa: F401 (importing the package installs the NullHandler) +from iqmapper import log_setup + + +@contextlib.contextmanager +def _bare_root(): + """No handler above the package logger, as in a plain notebook kernel. + pytest attaches its capture handlers to the root logger for the test + call, so they are taken off inside the test body, not in a fixture.""" + root = logging.getLogger() + saved = root.handlers[:] + root.handlers = [] + try: + yield + finally: + root.handlers = saved + + +@pytest.fixture(autouse=True) +def _no_file_log_left_behind(): + yield + log_setup.remove_file_log() + + +def _read(path): + for handler in logging.getLogger('iqmapper').handlers: + handler.flush() + with open(path, encoding='utf-8') as fh: + return fh.read().splitlines() + + +def test_the_package_logger_carries_a_null_handler(): + handlers = logging.getLogger('iqmapper').handlers + assert any(isinstance(h, logging.NullHandler) for h in handlers) + + +@pytest.mark.parametrize('name', ['iqmapper', 'iqmapper.auto_lucj', + 'iqmapper.data', 'iqmapper.ui.lucj_panel']) +def test_a_warning_writes_nothing_to_stderr(capsys, name): + with _bare_root(): + logging.getLogger(name).warning('Requested 6 bridges does not fit') + captured = capsys.readouterr() + assert captured.err == '' and captured.out == '' + + +def test_ten_identical_messages_are_written_once(tmp_path, capsys): + with _bare_root(): + path = log_setup.install_file_log(str(tmp_path / 'logs')) + log = logging.getLogger('iqmapper.data') + for _ in range(10): + log.warning("fetch_qubit_prop failed: qubit=%d prop='%s'", 72, 't2') + log.warning("fetch_qubit_prop failed: qubit=%d prop='%s'", 73, 't2') + logging.getLogger('iqmapper.reservoir').info('k=1: cap reached') + lines = _read(path) + assert sum("qubit=72 prop='t2'" in line for line in lines) == 1 + assert sum("qubit=73 prop='t2'" in line for line in lines) == 1 + assert sum('cap reached' in line for line in lines) == 1 # INFO kept + captured = capsys.readouterr() + assert captured.err == '' and captured.out == '' + + +def test_the_file_log_lives_in_the_user_log_directory(monkeypatch, tmp_path): + monkeypatch.setattr(log_setup, 'default_log_dir', + lambda: str(tmp_path / 'user-logs')) + path = log_setup.install_file_log() + assert path == str(tmp_path / 'user-logs' / 'iqmapper.log') + assert log_setup.install_file_log() == path # attached once + file_handlers = [h for h in logging.getLogger('iqmapper').handlers + if isinstance(h, logging.FileHandler)] + assert len(file_handlers) == 1 + + +def test_removing_the_file_log_restores_propagation(tmp_path): + log_setup.install_file_log(str(tmp_path / 'logs')) + assert logging.getLogger('iqmapper').propagate is False + log_setup.remove_file_log() + assert logging.getLogger('iqmapper').propagate is True + + +def test_an_unusable_directory_is_skipped_silently(tmp_path, capsys): + blocker = tmp_path / 'not-a-dir' + blocker.write_text('x') + assert log_setup.install_file_log(str(blocker / 'logs')) is None + assert not any(isinstance(h, logging.FileHandler) + for h in logging.getLogger('iqmapper').handlers) + captured = capsys.readouterr() + assert captured.err == '' and captured.out == '' diff --git a/tests/test_multi_sweep_ui.py b/tests/test_multi_sweep_ui.py index 929188c..b0feb4b 100644 --- a/tests/test_multi_sweep_ui.py +++ b/tests/test_multi_sweep_ui.py @@ -87,6 +87,7 @@ def _build(monkeypatch, spawn=_sync_spawn): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_fast_multi.value = True # the stubbed engine is the sequential one return b, state @@ -99,7 +100,14 @@ def _patch_engine(monkeypatch, result): def _dropdowns(box): - return [c for c in box.children if isinstance(c, Dropdown)] + """The per-circuit alternatives dropdowns (the Plans menu excluded).""" + return [c for c in box.children if isinstance(c, Dropdown) + and c.description != 'Plans:'] + + +def _plans(box): + return next(c for c in box.children if isinstance(c, Dropdown) + and c.description == 'Plans:') # ── happy path — both applied, summary exact, dropdowns collapsed ──────── @@ -116,11 +124,12 @@ def test_multi_sweep_happy_path(monkeypatch): assert state.layouts_data[0]['alpha'] == ['0', '1'] assert state.layouts_data[0]['ancilla'] == ['4'] assert state.layouts_data[1]['ancilla'] == ['6'] - # Summary format exact. + # Short status; the plan line carries the per-circuit numbers. v = b.lbl_lucj_multi.value - assert 'C1: k=1 · 61.2%' in v - assert 'C2: k=1 · 58.4%' in v - assert 'batch: 35.7%' in v # 0.612*0.584 = 0.3574 + assert '✅ 2 circuits placed' in v and 'vs one-by-one' not in v + plans = _plans(b.lucj_multi_detail_box) + assert [label for label, _ in plans.options] == [ + 'Plan 1 · total 35.7% · C1 61.2% + C2 58.4%'] # 0.612*0.584 # One collapsed dropdown per circuit, showing the chosen entry's label. dds = _dropdowns(b.lucj_multi_detail_box) assert len(dds) == 2 @@ -205,7 +214,7 @@ def test_multi_sweep_override(monkeypatch): # Re-applied: C0 now the alt (ancilla 5), C1 re-swept (ancilla 7). assert state.layouts_data[0]['ancilla'] == ['5'] assert state.layouts_data[1]['ancilla'] == ['7'] - assert 'C2: k=1 · 57.0%' in b.lbl_lucj_multi.value # summary refreshed + assert 'C2 57.0%' in _plans(b.lucj_multi_detail_box).options[0][0] # ── failed_at — banner + partial application ──────────────────────────── @@ -220,6 +229,8 @@ def test_multi_sweep_failed_at(monkeypatch): assert "Circuit doesn't fit after C1..C1" in v assert state.layouts_data[0]['ancilla'] == ['4'] # C1 still applied assert len(_dropdowns(b.lucj_multi_detail_box)) == 1 # only the placed one + assert not any(getattr(c, 'description', '') == 'Plans:' # no complete plan + for c in b.lucj_multi_detail_box.children) # ── in-flight guard — a second override during replan → single call ───── diff --git a/tests/test_search_ui.py b/tests/test_search_ui.py index 547872a..08b8e79 100644 --- a/tests/test_search_ui.py +++ b/tests/test_search_ui.py @@ -85,7 +85,7 @@ def test_the_engine_dropdown_and_threshold_are_gone(monkeypatch): def test_the_checkboxes_own_their_layouts(monkeypatch): b = _build(monkeypatch) - toggled = (b.chk_guided_search, b.bench_guided_box, b.chk_joint_plan, + toggled = (b.chk_guided_search, b.bench_guided_box, b.chk_fast_multi, b.joint_params_box) shared = (b.txt_auto.layout, b.chk_diverse_cap.layout, b.chk_deep_search.layout, b.lucj_buffer_slider.layout) @@ -125,23 +125,17 @@ def test_the_run_calls_the_combined_search(monkeypatch, guided): # ── status line ───────────────────────────────────────────────────── -def test_status_names_the_strata_guided_won(monkeypatch): +def test_status_is_one_short_line(monkeypatch): b = _build(monkeypatch) _stub_combined(monkeypatch, _result( {2: [_entry([4, 5], 0.7, 'guided')], 1: [_entry([4], 0.8, 'guided')]}, guided_winners=[2, 1])) _run(b) status = b.lbl_lucj_status.value - assert '· best from guided at k=2,1' in status, status - assert 'engine:' not in status - - -def test_status_is_silent_when_guided_won_nothing(monkeypatch): - b = _build(monkeypatch) - _stub_combined(monkeypatch, _result( - {1: [_entry([4], 0.8, 'both'), _entry([4], 0.7, 'guided', rank=2)]})) - _run(b) - assert 'guided' not in b.lbl_lucj_status.value + assert '✅ 2 layouts found · scored on live · ' in status, status + for gone in ('guided', 'embeddings', 'best per k', 'direct+derived', + 'capped', 'Sweep:'): + assert gone not in status, gone # ── labels ────────────────────────────────────────────────────────── diff --git a/tests/test_subpanel_persistence.py b/tests/test_subpanel_persistence.py index e6de83d..6c4648d 100644 --- a/tests/test_subpanel_persistence.py +++ b/tests/test_subpanel_persistence.py @@ -76,6 +76,7 @@ def _build(monkeypatch): state.cal_history_dates = ["_seed_"] b = MapperUIBuilder(state) b.build() + b.chk_fast_multi.value = True # the stubbed engine is the sequential one return b, state @@ -97,7 +98,7 @@ def test_multi_generate_keeps_multi_subpanel(monkeypatch): # Still on Multi (the fresh Tab from the rebuild carried the index over). assert b._auto_lucj_tabs.selected_index == 1 # Results rendered in place. - assert 'circuit(s) placed' in b.lbl_lucj_multi.value + assert 'circuits placed' in b.lbl_lucj_multi.value assert state.layouts_data[0]['ancilla'] == ['4'] # batch applied assert state.layouts_data[1]['ancilla'] == ['6'] @@ -200,7 +201,7 @@ def test_multi_generate_no_rebuild(monkeypatch): assert b._auto_lucj_tabs is tab_before assert b.content_box.children[0] is content_before assert b._auto_lucj_tabs.selected_index == 1 # still on Multi - assert 'circuit(s) placed' in b.lbl_lucj_multi.value # results rendered + assert 'circuits placed' in b.lbl_lucj_multi.value # results rendered # ── W3 t2: the targeted widgets ARE refreshed (no rebuild ≠ no update) ─────── @@ -216,7 +217,8 @@ def test_multi_generate_targeted_widgets_refreshed(monkeypatch): # Per-circuit override dropdowns reflect the 2-circuit result (in place). dds = [c for c in b.lucj_multi_detail_box.children if isinstance(c, Dropdown)] - assert len(dds) == 2 + assert [d.description for d in dds] == [ + 'Plans:', 'C1 alternatives:', 'C2 alternatives:'] # ancilla-tool options + manual per-circuit tabs re-seeded for the new count # (the targeted _build_dynamic_ui, done WITHOUT a content rebuild). anc_labels = [lbl for lbl, _ in b.ancilla_tool.options] diff --git a/tests/test_sweep_notices.py b/tests/test_sweep_notices.py index 9979c95..17178c5 100644 --- a/tests/test_sweep_notices.py +++ b/tests/test_sweep_notices.py @@ -80,6 +80,7 @@ def _build(monkeypatch): b = MapperUIBuilder(state) b.build() b.chk_guided_search.value = False # stubbed exhaustive engine only + b.chk_fast_multi.value = True # the stubbed engine is the sequential one return b @@ -201,8 +202,8 @@ def test_multi_sweep_notice_captured(monkeypatch): lg = logging.getLogger(_QLOG) def warn_multi(*a, **k): - lg.warning("Requested 6 bridges does not fit; falling back") - lg.warning("Requested 6 bridges does not fit; falling back") + lg.warning("circuit 2 search truncated") + lg.warning("circuit 2 search truncated") return _multi_result() monkeypatch.setattr("iqmapper.multi_sweep.sweep_multi_circuits", warn_multi) @@ -210,6 +211,6 @@ def warn_multi(*a, **k): b.btn_lucj_multi_sweep.click() notices = b.lbl_lucj_multi_notices.value - assert 'Requested 6 bridges does not fit; falling back ×2' in notices + assert 'circuit 2 search truncated ×2' in notices assert 'background:#fff3cd' in notices assert _capture_handlers() == [] From 52048aecba3e487e1550ba639bb7c2b35703d92f Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Thu, 8 Oct 2026 13:38:50 -0400 Subject: [PATCH 51/66] Properties: fetch only what the backend declares; one line per missing property; dropdowns list available properties; 'no data' in hovers --- CHANGELOG.md | 8 ++ iqmapper/constants.py | 20 ++- iqmapper/data.py | 107 ++++++++++++--- iqmapper/ui/builder.py | 37 +++++ iqmapper/ui/prop_options.py | 43 ++++++ tests/test_declared_props.py | 257 +++++++++++++++++++++++++++++++++++ 6 files changed, 444 insertions(+), 28 deletions(-) create mode 100644 iqmapper/ui/prop_options.py create mode 100644 tests/test_declared_props.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2679d2f..bc75df4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,14 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). other circuits too, so a coupler between two circuits looked like a gate of one of them. An ancilla now colours only edges to qubits of its own circuit, on the map and in the PNG export. +- Backends that report fewer calibration properties than Heron (Nighthawk + reports no RZZ or RX gates, Heron no MEASURE error) logged one "not found" + message per qubit or coupler on every load, and the property menus offered + properties the backend does not have, which painted the whole map black. + Only the properties the backend declares are fetched now; the menus list + only properties with values; a property with gaps logs one line ("t2: 1 of + 156 qubits without a value"); a missing value reads "no data" instead of + "NAN" or "N/A". ## [0.0.5] — 2026-08 diff --git a/iqmapper/constants.py b/iqmapper/constants.py index f25bfd6..07df51d 100644 --- a/iqmapper/constants.py +++ b/iqmapper/constants.py @@ -209,20 +209,28 @@ def _fmt_sci(v, prec=3): return f"{mant}E{'+' if e >= 0 else '-'}{abs(e)}" +#: Shown wherever a value is missing (NaN). +NO_DATA = "no data" + + def fmt_e(val): - """Format error value in scientific notation.""" + """Format error value in scientific notation; NaN → "no data".""" try: - return _fmt_sci(float(val)) + v = float(val) + if np.isnan(v): + return NO_DATA + return _fmt_sci(v) except Exception: return "N/A" def fmt_us(val): - """Format microsecond values: 248.3 µs instead of 2.483E+2.""" + """Format microsecond values: 248.3 µs instead of 2.483E+2; NaN → + "no data".""" try: v = float(val) if np.isnan(v): - return "N/A" + return NO_DATA if v >= 1000: return f"{v/1000:.1f} ms" if v >= 1: @@ -233,11 +241,11 @@ def fmt_us(val): def fmt_ns(val): - """Format gate length in nanoseconds.""" + """Format gate length in nanoseconds; NaN → "no data".""" try: v = float(val) if np.isnan(v): - return "N/A" + return NO_DATA return f"{v:.1f} ns" except Exception: return "N/A" diff --git a/iqmapper/data.py b/iqmapper/data.py index 9d78602..b69fb01 100644 --- a/iqmapper/data.py +++ b/iqmapper/data.py @@ -89,6 +89,80 @@ def _retry(fn, *args, retries=_MAX_RETRIES, **kwargs): } _TWO_Q_ERROR_GATES = {'cz_error': 'cz', 'rzz_error': 'rzz'} +#: What `properties()` must declare for each qubit key: a qubit parameter +#: name, or a tuple of gate names (any one is enough). +_QUBIT_KEY_SOURCE = { + 'readout_error': 'readout_error', 't1': 'T1', 't2': 'T2', + 'prob_meas0_prep1': 'prob_meas0_prep1', + 'prob_meas1_prep0': 'prob_meas1_prep0', + 'readout_length': 'readout_length', + 'id_error': ('id',), 'rx_error': ('rx',), 'sx_error': ('sx',), + 'rz_error': ('rz',), 'x_error': ('x',), + 'sq_gate_length': ('sx', 'x', 'id'), + 'measure_error': ('measure',), 'measure_2_error': ('measure_2',), +} +#: Gate names each gate key needs (any one is enough). +_GATE_KEY_SOURCE = { + 'cz_error': ('cz',), 'rzz_error': ('rzz',), 'gate_length': ('cz', 'rzz'), +} + + +def declared_keys(props): + """(qubit keys, gate keys) the backend's `properties()` declares, or None + when `props` does not expose its gate and qubit lists (then every key is + fetched).""" + try: + gates = {g.gate for g in props.gates} + params = {p.name for q in props.qubits for p in q} + except Exception: + return None + + def _has(source): + if isinstance(source, tuple): + return any(g in gates for g in source) + return source in params + + qubit = {k for k, src in _QUBIT_KEY_SOURCE.items() if _has(src)} + gate = {k for k, src in _GATE_KEY_SOURCE.items() if _has(src)} + return qubit, gate + + +def extract_props(props, n_qubits, edges): + """Every qubit and gate key as an array (qubit keys over `n_qubits`, gate + keys over `edges`). + + Keys the backend does not declare are NaN without being asked for, so a + backend without (say) RZZ gates costs no calls and no messages. A + declared key with missing values logs one line for the whole key, e.g. + "t2: 1 of 156 qubits without a value". Every key is always present, so + caches, history and sessions keep the same key set on every backend. + """ + declared = declared_keys(props) + q_keys, g_keys = declared if declared is not None else (None, None) + qp, gp = {}, {} + for _, pk in QUBIT_PROP_OPTIONS: + if q_keys is not None and pk not in q_keys: + qp[pk] = np.full(n_qubits, np.nan) + continue + qp[pk] = np.array([fetch_qubit_prop(props, i, pk) + for i in range(n_qubits)], dtype=float) + _log_holes(pk, qp[pk], 'qubits') + for _, pk in GATE_PROP_OPTIONS: + if g_keys is not None and pk not in g_keys: + gp[pk] = np.full(len(edges), np.nan) + continue + gp[pk] = np.array([fetch_gate_prop(props, e, pk) for e in edges], + dtype=float) + _log_holes(pk, gp[pk], 'edges') + return qp, gp + + +def _log_holes(key, arr, unit): + missing = int(np.isnan(arr).sum()) if len(arr) else 0 + if missing: + _log.warning("%s: %d of %d %s without a value", key, missing, + len(arr), unit) + # ── Property fetchers ──────────────────────────────────────────────── @@ -130,7 +204,9 @@ def fetch_qubit_prop(props, qubit_idx, prop_key): except Exception: return np.nan except Exception as exc: - _log.warning("fetch_qubit_prop failed: qubit=%d prop='%s' — %s", qubit_idx, prop_key, exc) + # One line per key is logged by extract_props, not one per qubit. + _log.debug("fetch_qubit_prop: qubit=%d prop='%s' — %s", + qubit_idx, prop_key, exc) return np.nan @@ -147,7 +223,9 @@ def fetch_gate_prop(props, edge, prop_key): continue return np.nan except Exception as exc: - _log.warning("fetch_gate_prop failed: edge=%s prop='%s' — %s", edge, prop_key, exc) + # One line per key is logged by extract_props, not one per edge. + _log.debug("fetch_gate_prop: edge=%s prop='%s' — %s", + edge, prop_key, exc) return np.nan @@ -515,14 +593,8 @@ def readout_error(self, *a, **kw): def _extract_and_cache(state, props, coords, edges, backend_name): """Extract all properties from a real props object, save to cache.""" - state.qubit_props_data = { - pk: np.array([fetch_qubit_prop(props, i, pk) for i in range(len(coords))]) - for _, pk in QUBIT_PROP_OPTIONS - } - state.gate_props_data = { - pk: np.array([fetch_gate_prop(props, e, pk) for e in edges]) - for _, pk in GATE_PROP_OPTIONS - } + state.qubit_props_data, state.gate_props_data = extract_props( + props, len(coords), edges) last_upd = _extract_last_update(props) if last_upd and backend_name: _save_calibration(backend_name, last_upd, @@ -599,10 +671,7 @@ def get_props_for_datetime(state, backend, cal_datetime): # Extract and cache n_q = len(state.qubit_ids) if state.qubit_ids else 0 edges = state.edges_list or [] - qp = {pk: np.array([fetch_qubit_prop(props, i, pk) for i in range(n_q)]) - for _, pk in QUBIT_PROP_OPTIONS} - gp = {pk: np.array([fetch_gate_prop(props, e, pk) for e in edges]) - for _, pk in GATE_PROP_OPTIONS} + qp, gp = extract_props(props, n_q, edges) if last_upd: _save_calibration(backend_name, last_upd, qp, gp) return _CachedPropsPlaceholder(last_upd or 'unknown'), qp, gp @@ -743,10 +812,7 @@ def scan_day_calibrations(state, backend, scan_date, progress_callback=None): cached = _load_calibration(backend_name, last_upd) if cached is None: try: - qp = {pk: np.array([fetch_qubit_prop(props, i, pk) for i in range(n_q)]) - for _, pk in QUBIT_PROP_OPTIONS} - gp = {pk: np.array([fetch_gate_prop(props, e, pk) for e in edges]) - for _, pk in GATE_PROP_OPTIONS} + qp, gp = extract_props(props, n_q, edges) _save_calibration(backend_name, last_upd, qp, gp) _log.info("Scanned & cached: %s @ %s", backend_name, last_upd) except Exception as exc: @@ -946,10 +1012,7 @@ def _fetch_one(dt): if props is None: return ds, None, None lu = _extract_last_update(props) - qp = {pk: np.array([fetch_qubit_prop(props, i, pk) for i in range(n_q)]) - for _, pk in QUBIT_PROP_OPTIONS} - gp = {pk: np.array([fetch_gate_prop(props, e, pk) for e in state.edges_list]) - for _, pk in GATE_PROP_OPTIONS} + qp, gp = extract_props(props, n_q, state.edges_list) if lu: _save_calibration(bname, lu, qp, gp) return ds, qp, gp diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index 5353591..fb6c7e6 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -2285,6 +2285,40 @@ def _build_error_view(self): getattr(self, '_err_tabs', None), _err_tabs) return _err_tabs + #: Property dropdowns re-listed from the loaded calibration, with the + #: value each falls back to: (attribute, qubit or gate list, default). + _PROP_DROPDOWNS = ( + ('dd_qubit_prop', 'qubit', 'readout_error'), + ('dd_rank_prop', 'qubit', 'readout_error'), + ('dd_trend_prop', 'qubit', 'readout_error'), + ('dd_stable_prop', 'qubit', 'readout_error'), + ('dd_gate_prop', 'gate', 'cz_error'), + ('dd_grank_prop', 'gate', 'cz_error'), + ('dd_gtrend_prop', 'gate', 'cz_error'), + ('dd_gstable_prop', 'gate', 'cz_error'), + ) + + def _sync_prop_dropdowns(self): + """List only the properties the loaded calibration has values for + (heatmap, rankings, trends, stable finder). Runs on every refresh, + so a new backend, snapshot or session is reflected at once; a + dropdown that already matches is left untouched.""" + from .prop_options import available_options, sync_dropdown + lists = { + 'qubit': available_options( + QUBIT_PROP_OPTIONS, getattr(self.state, 'qubit_props_data', None)), + 'gate': available_options( + GATE_PROP_OPTIONS, getattr(self.state, 'gate_props_data', None)), + } + self._syncing_props = True + try: + for attr, kind, default in self._PROP_DROPDOWNS: + dd = getattr(self, attr, None) + if dd is not None: + sync_dropdown(dd, lists[kind], default) + finally: + self._syncing_props = False + def _refresh(self, *args): """Central refresh — plot + counters + LQS banner + warnings. @@ -2305,6 +2339,9 @@ def _refresh(self, *args): 7. props-warning banner (red, only when set) 8. QPU 1 header label (inter-QPU mode only) """ + if getattr(self, '_syncing_props', False): + return # a dropdown being re-listed below + self._sync_prop_dropdowns() plot_mod.refresh_plot(self.fig, self.state, self.widgets_ref) self._update_all_counters() self._update_undo_btns() diff --git a/iqmapper/ui/prop_options.py b/iqmapper/ui/prop_options.py new file mode 100644 index 0000000..fd37fa4 --- /dev/null +++ b/iqmapper/ui/prop_options.py @@ -0,0 +1,43 @@ +""" +prop_options.py — property dropdowns list only what the loaded calibration has. + +A property belongs in a dropdown when its array holds at least one finite +value. The same test serves a fresh fetch and a cached snapshot, since both +carry the full key set with NaN where the backend reports nothing. When no +property has values yet (nothing loaded), the full list is kept. +""" +import numpy as np + + +def has_values(arr): + """True when `arr` holds at least one finite number.""" + if arr is None: + return False + try: + values = np.asarray(arr, dtype=float) + except (TypeError, ValueError): + return False + return values.size > 0 and bool(np.isfinite(values).any()) + + +def available_options(options, data): + """The (label, key) pairs of `options` whose array in `data` has values; + all of `options` when none has.""" + data = data or {} + kept = [(label, key) for label, key in options if has_values(data.get(key))] + return kept or list(options) + + +def sync_dropdown(dropdown, options, preferred): + """Give `dropdown` exactly `options`. Its value is kept when still listed, + else `preferred` when listed, else the first option. Returns True when + anything changed.""" + keys = [key for _label, key in options] + if list(dropdown.options) == list(options): + return False + value = dropdown.value + if value not in keys: + value = preferred if preferred in keys else keys[0] + dropdown.options = options + dropdown.value = value + return True diff --git a/tests/test_declared_props.py b/tests/test_declared_props.py new file mode 100644 index 0000000..80cd2e5 --- /dev/null +++ b/tests/test_declared_props.py @@ -0,0 +1,257 @@ +"""Only the properties a backend declares are fetched; the rest are NaN with no +calls and no messages, every key is still stored, a real hole logs one line, +the property dropdowns list what has values, and a missing value reads +"no data". +""" +import logging +from types import SimpleNamespace + +import numpy as np +import pytest + +from iqmapper import data +from iqmapper.constants import (GATE_PROP_OPTIONS, QUBIT_PROP_OPTIONS, + fmt_e, fmt_ns, fmt_us) + +fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + +# FakeNighthawk's own notice that its numbers are not typical Nighthawk values. +pytestmark = pytest.mark.filterwarnings( + 'ignore:Properties of fake_nighthawk are not intended:UserWarning') + +ALL_Q = {k for _, k in QUBIT_PROP_OPTIONS} +ALL_G = {k for _, k in GATE_PROP_OPTIONS} + +#: What each fake declares in properties() (qiskit-ibm-runtime fake data). +UNDECLARED = { + 'FakeNighthawk': ({'rx_error', 'measure_2_error'}, {'rzz_error'}), + 'FakeMiami': ({'measure_2_error'}, {'rzz_error'}), + 'FakeFez': ({'measure_error', 'measure_2_error'}, set()), +} + + +class _Collect(logging.Handler): + def __init__(self): + super().__init__(level=logging.DEBUG) + self.records = [] + + def emit(self, record): + self.records.append(record) + + +@pytest.fixture +def collect(): + handler = _Collect() + logger = logging.getLogger('iqmapper') + old_level = logger.level + logger.setLevel(logging.DEBUG) + logger.addHandler(handler) + yield handler + logger.removeHandler(handler) + logger.setLevel(old_level) + + +def _backend(name): + return getattr(fake_provider, name)() + + +def _edges(backend): + return list(backend.coupling_map.get_edges()) + + +# ── what is declared, what is fetched ─────────────────────────────── + +@pytest.mark.parametrize('name', sorted(UNDECLARED)) +def test_declared_keys_match_the_backend(name): + backend = _backend(name) + q_keys, g_keys = data.declared_keys(backend.properties()) + no_q, no_g = UNDECLARED[name] + assert q_keys == ALL_Q - no_q + assert g_keys == ALL_G - no_g + + +@pytest.mark.parametrize('name', sorted(UNDECLARED)) +def test_undeclared_keys_cost_no_calls_and_no_messages(name, collect, + monkeypatch): + backend = _backend(name) + props = backend.properties() + asked = [] + real_q, real_g = data.fetch_qubit_prop, data.fetch_gate_prop + monkeypatch.setattr(data, 'fetch_qubit_prop', lambda p, i, k: asked.append( + k) or real_q(p, i, k)) + monkeypatch.setattr(data, 'fetch_gate_prop', lambda p, e, k: asked.append( + k) or real_g(p, e, k)) + + qp, gp = data.extract_props(props, backend.num_qubits, _edges(backend)) + + no_q, no_g = UNDECLARED[name] + assert not (set(asked) & (no_q | no_g)), 'an undeclared key was fetched' + assert set(qp) == ALL_Q and set(gp) == ALL_G # full key set kept + for key in no_q: + assert np.isnan(qp[key]).all() and len(qp[key]) == backend.num_qubits + for key in no_g: + assert np.isnan(gp[key]).all() and len(gp[key]) == len(_edges(backend)) + noisy = [r for r in collect.records if r.levelno >= logging.INFO] + assert noisy == [], [r.getMessage() for r in noisy] + + +def test_the_app_load_of_a_nighthawk_logs_nothing(collect, monkeypatch, + tmp_path): + from iqmapper.state import SessionState + monkeypatch.setattr(data, '_CACHE_DIR', str(tmp_path)) + backend = _backend('FakeNighthawk') + state = SessionState() + state.active_backend, state.active_backend_name = backend, backend.name + state.initial_props = backend.properties() + data._generate_ibm(state, None) + assert [r for r in collect.records if r.levelno >= logging.INFO + and 'Cache' not in r.getMessage()] == [] + assert state.props_warning is None + + +# ── a real hole: one line for the whole key ───────────────────────── + +class _MissingT2: + """FakeFez properties with no T2 value for qubit 72.""" + + def __init__(self, props): + self._props = props + + def __getattr__(self, name): + return getattr(self._props, name) + + def t2(self, qubit): + if qubit == 72: + raise KeyError('T2') + return self._props.t2(qubit) + + +def test_a_hole_in_a_declared_property_logs_one_line(collect): + backend = _backend('FakeFez') + qp, _gp = data.extract_props(_MissingT2(backend.properties()), + backend.num_qubits, _edges(backend)) + assert np.isnan(qp['t2'][72]) and np.isfinite(qp['t2'][71]) + lines = [r.getMessage() for r in collect.records + if r.levelno >= logging.WARNING] + assert lines == ['t2: 1 of 156 qubits without a value'] + + +def test_props_without_gate_lists_fetch_every_key(): + """A props object that does not expose its gates (older objects, test + stand-ins) is asked for every key, as before.""" + assert data.declared_keys(SimpleNamespace()) is None + + +# ── caches ────────────────────────────────────────────────────────── + +def test_old_and_new_cache_files_load(monkeypatch, tmp_path): + monkeypatch.setattr(data, '_CACHE_DIR', str(tmp_path)) + # Written the old way: every key fetched per element (NaN where absent). + old_q = {k: np.full(4, 0.01) for k in ALL_Q} + old_g = {k: np.full(3, 0.02) for k in ALL_G} + data._save_calibration('ibm_old', '2026-01-01 00:00:00', old_q, old_g) + assert data._load_calibration('ibm_old', '2026-01-01 00:00:00') is not None + + backend = _backend('FakeMiami') + qp, gp = data.extract_props(backend.properties(), backend.num_qubits, + _edges(backend)) + data._save_calibration('fake_miami', '2026-01-02 00:00:00', qp, gp) + cached = data._load_calibration('fake_miami', '2026-01-02 00:00:00') + assert cached is not None + assert set(cached[0]) == ALL_Q and set(cached[1]) == ALL_G + assert np.isnan(cached[1]['rzz_error']).all() + + +# ── dropdowns ─────────────────────────────────────────────────────── + +def _build_on(monkeypatch, name, is_secondary=False): + """A real MapperUIBuilder whose device data is the fake backend's own + extraction (the same arrays a cached snapshot would hold).""" + backend = _backend(name) + n = backend.num_qubits + edges = _edges(backend) + qp, gp = data.extract_props(backend.properties(), n, edges) + + def _device(state, vendor, chip, date, prefetched_props=None): + state.qubit_props_data, state.gate_props_data = qp, gp + return (list(range(n)), [0.0] * n, edges, [str(i) for i in range(n)], + qp['readout_error'], gp['cz_error']) + + monkeypatch.setattr('iqmapper.data.generate_device_data', _device) + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + state = SessionState() + for key, val in dict( + active_backend=object(), active_backend_name=backend.name, + active_chip='stub_chip', active_service=None, + available_backends=[], props_warning=None, initial_props=object(), + active_ansatz='lucj', active_vendor='IBM', + active_coords=[(i, 0) for i in range(n)], custom_colors=[], + cal_history_dates=['_seed_']).items(): + setattr(state, key, val) + b = MapperUIBuilder(state, is_secondary=is_secondary) + b.build() + b._refresh() + return b + + +def _keys(dd): + return {key for _label, key in dd.options} + + +@pytest.mark.parametrize('name', sorted(UNDECLARED)) +@pytest.mark.parametrize('is_secondary', [False, True]) +def test_property_dropdowns_list_what_the_backend_has(monkeypatch, name, + is_secondary): + b = _build_on(monkeypatch, name, is_secondary) + no_q, no_g = UNDECLARED[name] + for attr in ('dd_qubit_prop', 'dd_rank_prop', 'dd_trend_prop', + 'dd_stable_prop'): + assert _keys(getattr(b, attr)) == ALL_Q - no_q, attr + for attr in ('dd_gate_prop', 'dd_grank_prop', 'dd_gtrend_prop', + 'dd_gstable_prop'): + assert _keys(getattr(b, attr)) == ALL_G - no_g, attr + assert b.dd_qubit_prop.value == 'readout_error' + assert b.dd_gate_prop.value == 'cz_error' + + +def test_a_selected_property_that_disappears_falls_back(monkeypatch): + b = _build_on(monkeypatch, 'FakeFez') + b.dd_gate_prop.value = 'rzz_error' + b.state.gate_props_data = dict(b.state.gate_props_data, + rzz_error=np.full(len(b.state.edges_list), + np.nan)) + b._refresh() + assert 'rzz_error' not in _keys(b.dd_gate_prop) + assert b.dd_gate_prop.value == 'cz_error' + + +def test_nothing_loaded_keeps_the_full_list(): + from iqmapper.ui.prop_options import available_options + assert available_options(QUBIT_PROP_OPTIONS, {}) == list(QUBIT_PROP_OPTIONS) + assert available_options(GATE_PROP_OPTIONS, None) == list(GATE_PROP_OPTIONS) + + +# ── "no data" ─────────────────────────────────────────────────────── + +def test_a_missing_value_reads_no_data(): + assert fmt_e(np.nan) == 'no data' + assert fmt_us(np.nan) == 'no data' + assert fmt_ns(np.nan) == 'no data' + assert fmt_e(1.23e-3) == '1.230E-3' and fmt_us(248.3) == '248.3 µs' + + +def test_the_heatmap_hover_says_no_data(): + pytest.importorskip('plotly') + from iqmapper import plot + from test_focus_isolate_boundary import _make_state, _wref + state = _make_state(single=True) + state.readout_errors = np.array([0.01, np.nan, 0.03, 0.04]) + state.qubit_props_data = {'readout_error': state.readout_errors} + fig = plot.create_figure() + plot.build_device_graph(fig, state, _wref(n_circuits=1)) + plot.refresh_plot(fig, state, _wref(n_circuits=1)) + hovers = [t for tr in fig.data for t in (getattr(tr, 'hovertext', None) + or getattr(tr, 'text', None) or ()) + if isinstance(t, str) and 'Qubit 1<' in t] + assert hovers and all('no data' in h and 'NAN' not in h for h in hovers) From 96c8bae6d9d760c3340821a1a768d0bf3a4b2e56 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Thu, 8 Oct 2026 14:25:28 -0400 Subject: [PATCH 52/66] Guided: no duplicate layouts per stratum; joint planner returns its complete plans for the Plans menu --- iqmapper/guided_search.py | 22 +++++ iqmapper/joint_plan.py | 71 +++++++++++--- iqmapper/ui/lucj_panel.py | 20 ---- tests/test_auto_panel_ui_polish.py | 4 - tests/test_engine_dedupe_plans.py | 146 +++++++++++++++++++++++++++++ tests/test_scan_ui.py | 12 --- tests/test_sweep_ui.py | 16 +--- 7 files changed, 229 insertions(+), 62 deletions(-) create mode 100644 tests/test_engine_dedupe_plans.py diff --git a/iqmapper/guided_search.py b/iqmapper/guided_search.py index 3cb4e31..5ab49bc 100644 --- a/iqmapper/guided_search.py +++ b/iqmapper/guided_search.py @@ -561,6 +561,23 @@ def refine_entry(engine, entry, k, circuit_score_fn, max_iter=DEFAULT_MAX_ITER): return current, changed +def _layout_identity(entry): + """One layout, however its chains are walked: all qubits + ancillas.""" + return (frozenset(entry['alpha']) | frozenset(entry['beta']) + | frozenset(entry['ancillas']), frozenset(entry['ancillas'])) + + +def _distinct_layouts(ranked): + """`ranked` without repeated layouts, the first (best-ranked) copy kept.""" + seen, out = set(), [] + for entry in ranked: + key = _layout_identity(entry) + if key not in seen: + seen.add(key) + out.append(entry) + return out + + # ── public API ────────────────────────────────────────────────────── def guided_sweep(norb, backend, props, *, min_bridges=None, top_n=3, @@ -759,6 +776,11 @@ def _add(alpha, beta, bridges, k, source): else 0.0, e['product_score']), reverse=True) + # A refined finalist can land on a layout another window entry + # already holds (same qubits and ancillas, chains walked in another + # order). Keep the higher-ranked copy so the freed slot goes to a + # different layout. + window = _distinct_layouts(window) if diversity_threshold is None: entries = window[:top_n] diff --git a/iqmapper/joint_plan.py b/iqmapper/joint_plan.py index 44a60c1..bfb524d 100644 --- a/iqmapper/joint_plan.py +++ b/iqmapper/joint_plan.py @@ -147,7 +147,11 @@ def _final_key(plan, penalty): def _beam(ctx, prefix, beam_width, branch): - """Run the beam from a fixed prefix. Returns (best_plan, failed_at).""" + """Run the beam from a fixed prefix. + + Returns (best_plan, failed_at, final_beam); `final_beam` holds the plans + alive after the last circuit that fitted. + """ norbs = ctx['norbs'] penalty = ctx['boundary_penalty'] buffer_qubits = ctx['buffer_qubits'] @@ -185,7 +189,7 @@ def _beam(ctx, prefix, beam_width, branch): beam = sorted(children.values(), key=lambda p: (-p.score(penalty), p.path))[:beam_width] best = min(beam, key=lambda p: _final_key(p, penalty)) - return best, failed_at + return best, failed_at, beam def _search(ctx, i, excluded): @@ -210,8 +214,8 @@ def _search(ctx, i, excluded): return res -def _result(ctx, plan, failed_at, greedy_plan, plan_source, n_searches): - penalty = ctx['boundary_penalty'] +def _plan_fields(plan, penalty): + """The result keys that describe one placement plan.""" chosen_list = [r['chosen'] for r in plan.records] total_product = None if chosen_list: @@ -230,32 +234,71 @@ def _result(ctx, plan, failed_at, greedy_plan, plan_source, n_searches): 'total_lqs_circuit': total_lqs, 'placed_qubits': list(plan.placed), 'buffer_qubits_used': list(plan.buffers), + 'boundary_couplers': [tuple(e) for e in plan.boundary], + 'joint_total': plan.score(penalty), + } + + +def _complete_plans(ctx, plans): + """Up to `beam_width` distinct plans that place every circuit, best first + by the planner's own ranking. Each is a dict of the plan keys plus + `chosen` (one entry per circuit), `total` (the plan score) and + `failed_at` (None).""" + penalty = ctx['boundary_penalty'] + n_circuits = len(ctx['norbs']) + distinct = {} + for plan in plans: + if len(plan.records) == n_circuits: + distinct.setdefault(plan.qkey(), plan) + ranked = sorted(distinct.values(), key=lambda p: _final_key(p, penalty)) + out = [] + for plan in ranked[:ctx['beam_width']]: + fields = _plan_fields(plan, penalty) + fields.update(chosen=[r['chosen'] for r in plan.records], + total=plan.score(penalty), failed_at=None) + out.append(fields) + return out + + +def _result(ctx, plan, failed_at, greedy_plan, plan_source, n_searches, + plans): + penalty = ctx['boundary_penalty'] + fields = _plan_fields(plan, penalty) + return { + 'circuits': fields['circuits'], + 'total_product': fields['total_product'], + 'total_lqs_circuit': fields['total_lqs_circuit'], + 'placed_qubits': fields['placed_qubits'], + 'buffer_qubits_used': fields['buffer_qubits_used'], 'failed_at': failed_at, 'planner': 'joint', 'beam_width': ctx['beam_width'], 'branch': ctx['branch'], 'boundary_penalty': penalty, - 'boundary_couplers': [tuple(e) for e in plan.boundary], + 'boundary_couplers': fields['boundary_couplers'], 'greedy_total': greedy_plan.score(penalty), 'greedy_placed': len(greedy_plan.records), - 'joint_total': plan.score(penalty), + 'joint_total': fields['joint_total'], 'plan_source': plan_source, 'n_searches': n_searches, + 'plans': plans, '_context': ctx, } def _run(ctx, prefix): calls_before = ctx['_calls'][0] - greedy, greedy_failed = _beam(ctx, prefix, 1, 1) - joint, joint_failed = _beam(ctx, prefix, ctx['beam_width'], ctx['branch']) + greedy, greedy_failed, greedy_beam = _beam(ctx, prefix, 1, 1) + joint, joint_failed, joint_beam = _beam(ctx, prefix, ctx['beam_width'], + ctx['branch']) penalty = ctx['boundary_penalty'] if _final_key(greedy, penalty) < _final_key(joint, penalty): plan, failed_at, source = greedy, greedy_failed, 'greedy' else: plan, failed_at, source = joint, joint_failed, 'beam' return _result(ctx, plan, failed_at, greedy, source, - ctx['_calls'][0] - calls_before) + ctx['_calls'][0] - calls_before, + _complete_plans(ctx, list(joint_beam) + list(greedy_beam))) def plan_multi_circuits(norbs, backend, props, *, search_fn=None, @@ -287,8 +330,14 @@ def plan_multi_circuits(norbs, backend, props, *, search_fn=None, `joint_total` is the returned plan's), `greedy_placed` (circuits the greedy plan placed — when the joint plan places more, its score is a product of more factors and the two totals are not comparable), - `plan_source` ('beam' | 'greedy'), and `n_searches` (actual `search_fn` - calls after memoisation). + `plan_source` ('beam' | 'greedy'), `n_searches` (actual `search_fn` + calls after memoisation), and `plans`: up to `beam_width` distinct + plans that place every circuit, best first, the returned plan first + when it is complete. Each holds `chosen` (one entry per circuit), + `total` (plan score, penalty included), `circuits`, `total_product`, + `total_lqs_circuit`, `placed_qubits`, `buffer_qubits_used`, + `boundary_couplers`, `joint_total` and `failed_at` (None), so a caller + can swap any of them in for the returned plan. """ if not (0.0 <= boundary_penalty < 1.0): raise ValueError(f"boundary_penalty={boundary_penalty} must be in " diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index 8a440c8..a5e84a6 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -44,26 +44,6 @@ def _format_best_per_k(strata): return ' · '.join(parts) -def _sweep_mode_label(res): - """'direct+derived' when any lower stratum got a direct-VF2 hit, - else 'derived-only'.""" - kmax = res.get('k_max_effective') - ps = res.get('per_stratum', {}) - direct = any(v.get('n_direct', 0) > 0 for k, v in ps.items() - if kmax is not None and k < kmax) - return 'direct+derived' if direct else 'derived-only' - - -def _format_sweep_status(res): - """One-line sweep summary: 'Sweep: k=6..3 · 214 embeddings · - best per k: ...'. All interpolations esc()'d.""" - k_range = f"{res['k_max_effective']}..{res['min_bridges']}" - emb = f"{res['n_raw_embeddings']:,}" - per_k = _format_best_per_k(res.get('strata', {})) - return (f"Sweep: k={esc(k_range)} · {esc(emb)} embeddings · " - f"best per k: {esc(per_k)}") - - def _k_cap_phrase(norb, k_effective): """'k capped at E (requested R)' when the geometric request ceil(norb/4) exceeds what actually fit; '' otherwise. Pure metadata — diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index c2e37f0..2332df2 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -262,10 +262,6 @@ def test_guided_results_render_through_the_existing_display(monkeypatch): b, _ = _build(monkeypatch) res = guided_sweep(4, make_backend(), FakeProps(), min_bridges=1, top_n=3) - from iqmapper.ui.lucj_panel import _format_sweep_status - line = _format_sweep_status(res) - assert line and 'Sweep:' in line - from iqmapper.ui.lucj_panel import _format_best_per_k best = _format_best_per_k(res['strata']) assert best, 'best-per-k line empty for a guided result' diff --git a/tests/test_engine_dedupe_plans.py b/tests/test_engine_dedupe_plans.py new file mode 100644 index 0000000..f91989d --- /dev/null +++ b/tests/test_engine_dedupe_plans.py @@ -0,0 +1,146 @@ +"""Guided lists each layout once; the joint planner hands back its complete +plans. + +B1: the 1-opt polish can turn a finalist into a layout another candidate +already is (same qubits and ancillas, chains walked differently). The guided +sweep keeps the better-ranked copy, so the slot goes to a different layout. + +B2: `plan_multi_circuits` returns `plans`, the distinct complete plans of its +final beams, best first, each carrying what a caller needs to swap it in. +""" +from collections import Counter + +import pytest +import rustworkx + +from iqmapper import guided_search as gs +from iqmapper.guided_search import guided_sweep +from iqmapper.joint_plan import plan_multi_circuits, replan_from + +from test_combined_sweep import _lqs_scorer +from test_engine_select import heavy_hex_backend +from test_guided_induced import _SeededProps, _backend_from +from test_joint_plan import _myopia_host, _qubits +from test_multi_sweep import _Props, _make_backend + +fake_provider = pytest.importorskip('qiskit_ibm_runtime.fake_provider') + + +def _identity(entry): + return (frozenset(entry['alpha']) | frozenset(entry['beta']) + | frozenset(entry['ancillas']), frozenset(entry['ancillas'])) + + +def _duplicates(result): + return {k: sum(n - 1 for n in Counter(map(_identity, es)).values()) + for k, es in result['strata'].items()} + + +# ── B1: no repeated layout in a stratum ───────────────────────────── + +def _fez(): + backend = fake_provider.FakeFez() + return backend, backend.properties() + + +def _heavy_hex(d, seed): + undirected = [tuple(e) for e in + rustworkx.generators.heavy_hex_graph(d).edge_list()] + backend = _backend_from(undirected) + return backend, _SeededProps(1 + max(max(e) for e in undirected), seed) + + +@pytest.mark.parametrize('host, norbs', [ + (lambda: _heavy_hex(5, 3), (6, 8)), + (lambda: _heavy_hex(7, 11), (8, 12)), + (_fez, (8, 12)), +]) +def test_no_stratum_lists_a_layout_twice(host, norbs): + backend, props = host() + scorer = _lqs_scorer(backend, props) + for norb in norbs: + res = guided_sweep(norb, backend, props, min_bridges=1, top_n=10, + circuit_score_fn=scorer) + assert set(_duplicates(res).values()) == {0}, (norb, _duplicates(res)) + + +def test_a_repeated_layout_frees_its_slot_for_another(monkeypatch): + """FakeFez norb=8: without the dedupe, k=2 repeats layouts. With it, the + list keeps every layout it had and fills the freed slots with others.""" + backend, props = _fez() + scorer = _lqs_scorer(backend, props) + args = dict(min_bridges=1, top_n=10, circuit_score_fn=scorer) + + with monkeypatch.context() as m: + m.setattr(gs, '_distinct_layouts', lambda ranked: list(ranked)) + before = guided_sweep(8, backend, props, **args) + after = guided_sweep(8, backend, props, **args) + + assert _duplicates(before)[2] > 0, 'fixture no longer repeats a layout' + old = set(map(_identity, before['strata'][2])) + new = [_identity(e) for e in after['strata'][2]] + assert len(new) == len(set(new)) == 10 + assert old <= set(new) and set(new) - old + assert [e['rank_in_stratum'] for e in after['strata'][2]] == list( + range(1, 11)) + + +def test_distinct_layouts_keeps_the_first_copy(): + a = {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [4]} + a_again = {'alpha': [1, 0], 'beta': [3, 2], 'ancillas': [4]} + b = {'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [5]} + assert gs._distinct_layouts([a, a_again, b]) == [a, b] + + +# ── B2: the joint planner's complete plans ────────────────────────── + +PLAN_KEYS = {'chosen', 'total', 'circuits', 'total_product', + 'total_lqs_circuit', 'placed_qubits', 'buffer_qubits_used', + 'boundary_couplers', 'joint_total', 'failed_at'} + + +def _check_plans(res, n_circuits, beam_width): + plans = res['plans'] + assert 1 <= len(plans) <= beam_width + for plan in plans: + assert set(plan) == PLAN_KEYS + assert plan['failed_at'] is None and len(plan['chosen']) == n_circuits + assert [c['chosen'] for c in plan['circuits']] == plan['chosen'] + assert plan['total'] == pytest.approx(plan['joint_total']) + footprints = [tuple(frozenset(_qubits(e)) for e in p['chosen']) + for p in plans] + assert len(footprints) == len(set(footprints)), 'a plan is listed twice' + totals = [p['total'] for p in plans] + assert totals == sorted(totals, reverse=True) + return plans + + +def test_plans_are_complete_distinct_and_best_first(): + backend, props = heavy_hex_backend(5, seed=2) + res = plan_multi_circuits([5, 5], backend, props, min_bridges=1, + beam_width=4) + plans = _check_plans(res, 2, 4) + assert len(plans) > 1, 'fixture gives only one complete plan' + + +def test_the_returned_plan_is_plans_first(): + backend, props, _parts = _myopia_host() + res = plan_multi_circuits([4, 8], backend, props) + plans = _check_plans(res, 2, 4) + assert plans[0]['chosen'] == [c['chosen'] for c in res['circuits']] + assert plans[0]['total'] == pytest.approx(res['joint_total']) + + +def test_an_incomplete_run_has_no_complete_plans(): + backend, props = _make_backend(), _Props() + res = plan_multi_circuits([8, 8, 8, 8], backend, props) + assert res['failed_at'] == 2 and res['plans'] == [] + + +def test_a_replan_hands_back_plans_for_its_own_prefix(): + backend, props = heavy_hex_backend(5, seed=2) + res = plan_multi_circuits([5, 5], backend, props, min_bridges=1) + alt = res['plans'][-1]['chosen'][0] + new = replan_from(res, 0, alt) + plans = _check_plans(new, 2, res['beam_width']) + assert all(_qubits(p['chosen'][0]) == _qubits(alt) for p in plans) diff --git a/tests/test_scan_ui.py b/tests/test_scan_ui.py index 21e46fc..71228b8 100644 --- a/tests/test_scan_ui.py +++ b/tests/test_scan_ui.py @@ -10,7 +10,6 @@ import numpy as np -from iqmapper.ui.lucj_panel import _format_sweep_status def _fake_device_data(state, vendor, chip, date, prefetched_props=None): @@ -245,17 +244,6 @@ def test_m1_score_checkbox_toggle(monkeypatch): assert b.lucj_chk_score.disabled is True -# ── per-stratum status line format ───────────────────────────────────── - -def test_m2_status_line_format(): - res = _sweep(0.40, 0.30) - res['k_max_effective'] = 2 - res['min_bridges'] = 1 - res['n_raw_embeddings'] = 214 - line = _format_sweep_status(res) - assert line == "Sweep: k=2..1 · 214 embeddings · best per k: 2→30.0% · 1→40.0%" - - # ── circuit-LQS annotation (success → number, failure → template) ─────── def test_scan_circuit_lqs_annotated(monkeypatch): diff --git a/tests/test_sweep_ui.py b/tests/test_sweep_ui.py index 7e335ed..4e08ee1 100644 --- a/tests/test_sweep_ui.py +++ b/tests/test_sweep_ui.py @@ -280,7 +280,7 @@ def boom(*a, **k): assert b.btn_lucj_run.disabled is False -# ── the deep-search checkbox wires hybrid= and the per-stratum mode label ──────── +# ── the deep-search checkbox wires hybrid= ─────────────────────────────── def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): calls = [] @@ -296,20 +296,6 @@ def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): assert calls[-1]['hybrid'] is True -def test_sweep_mode_label(): - from iqmapper.ui.lucj_panel import _sweep_mode_label - hy = {'k_max_effective': 3, - 'per_stratum': {3: {'n_direct': 5, 'n_derived': 0}, - 2: {'n_direct': 2, 'n_derived': 3}, - 1: {'n_direct': 0, 'n_derived': 4}}} - assert _sweep_mode_label(hy) == 'direct+derived' # k=2 got direct hits - dv = {'k_max_effective': 3, - 'per_stratum': {3: {'n_direct': 5, 'n_derived': 0}, - 2: {'n_direct': 0, 'n_derived': 3}, - 1: {'n_direct': 0, 'n_derived': 4}}} - assert _sweep_mode_label(dv) == 'derived-only' - - # ── a region-diversity pick carries no "alt region" suffix ────────────── def test_diverse_entry_has_no_alt_region_suffix(builder, monkeypatch): From cc00d473611e495ff63e1335c4f707edeeb30008 Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Thu, 8 Oct 2026 16:58:44 -0400 Subject: [PATCH 53/66] Tests: keep the app's log file in tmp and detach it after every test --- tests/conftest.py | 13 +++++++++++++ tests/test_log_isolation.py | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/test_log_isolation.py diff --git a/tests/conftest.py b/tests/conftest.py index 50694c9..79b97b1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -63,3 +63,16 @@ def make_slot(): @pytest.fixture def make_state(): return _make_state + + +@pytest.fixture(autouse=True) +def _file_log_in_tmp(tmp_path, monkeypatch): + """Keep the app's log file out of the user's log directory and detach it + after every test. A test that starts the UI (Refresh rebuilds through + `launch_mapper`) would otherwise write the real log and leave the handler + attached, with propagation off, for every test after it.""" + from iqmapper import log_setup + monkeypatch.setattr(log_setup, 'default_log_dir', + lambda: str(tmp_path / 'logs')) + yield + log_setup.remove_file_log() diff --git a/tests/test_log_isolation.py b/tests/test_log_isolation.py new file mode 100644 index 0000000..79bac14 --- /dev/null +++ b/tests/test_log_isolation.py @@ -0,0 +1,17 @@ +"""Starting the UI inside a test leaves no log file behind and no handler on +the package logger for the tests that follow (order matters here: the second +test checks what the first one left).""" +import logging + + +def test_a_ui_start_writes_its_log_under_tmp(tmp_path): + from iqmapper import log_setup + path = log_setup.install_file_log() # what run()/launch_mapper do + assert path == str(tmp_path / 'logs' / 'iqmapper.log') + assert logging.getLogger('iqmapper').propagate is False + + +def test_the_next_test_starts_with_a_clean_package_logger(): + logger = logging.getLogger('iqmapper') + assert logger.propagate is True + assert not any(isinstance(h, logging.FileHandler) for h in logger.handlers) From 4e615ea360aff87b00a6f432dfedbc52a711582a Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Thu, 8 Oct 2026 16:58:44 -0400 Subject: [PATCH 54/66] Multi-QPU scans: list chips the map cannot open as 'not supported' --- CHANGELOG.md | 4 +- README.md | 10 +++- iqmapper/ui/lucj_panel.py | 102 ++++++++++++++++++++++++++++----- tests/test_scan_unsupported.py | 98 +++++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+), 18 deletions(-) create mode 100644 tests/test_scan_unsupported.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bc75df4..1c0b9e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,9 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - Multi-circuit sweep: places several circuits one after another; picking a different layout for one circuit re-plans the circuits after it. - Multi-QPU scan across the available backends, with one-click inter-QPU - handoff that reopens the chosen layout on the second QPU. + handoff that reopens the chosen layout on the second QPU. Backends whose + chip the map cannot open (anything but 156-qubit Heron and 120-qubit + Nighthawk) are listed last as "not supported", never searched or opened. - Epoch-consistent scoring: fidelity and ranking read a single pinned calibration epoch, so comparisons within a sweep stay commensurable. - Hybrid search engine (`engine_select.hybrid_sweep`, used by the engine diff --git a/README.md b/README.md index ef9d98e..cbd250a 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ inspectable, and reproducible**. qubits *stay* good across a 7/14/30-day window. - 🎯 **Two operating modes** — a general-purpose mode for arbitrary circuits, and a dedicated mode for the **LUCJ ansatz** (quantum chemistry), with one-click - auto-placement on heavy-hex topologies. + auto-placement. - 🏆 **Layout scoring & ranking (LQS)** — an error-aware quality score to compare candidate layouts before spending QPU time. - 📦 **Import & export** — import layouts from JSON / `.npy` / QPY; export @@ -66,6 +66,9 @@ inspectable, and reproducible**. ## Requirements - Python **3.10+** +- An IBM backend with a **156-qubit Heron** (r2, r3) or a **120-qubit Nighthawk** + processor — the chips the map has a layout for. Other chips appear in the + multi-QPU scans as "not supported". - An [IBM Quantum](https://quantum.ibm.com) account with a saved `QiskitRuntimeService` credential (see [Set up your IBM Quantum account](#set-up-your-ibm-quantum-account)) @@ -527,7 +530,10 @@ For a guided tour of the modules and data flow, see quality. - The LQS score is a first-order heuristic for *relative* layout comparison, not an absolute fidelity prediction. -- Heavy-hex auto-placement currently targets IBM Heron/Nighthawk-class devices. +- The device map, and therefore connecting, covers 156-qubit Heron (r2, r3) and + 120-qubit Nighthawk processors. Other chips (133-qubit Heron r1, 127-qubit + Eagle) are listed in the multi-QPU scans as "not supported" and never + searched.
diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index a5e84a6..ed87f5f 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -1011,6 +1011,43 @@ def _window_txt(): f"margin:3px 0;'>🛡 filtered {esc(str(n_vol))} volatile" f"{floor_txt} qubits (window {_window_txt()})") + #: Detail line for a backend the map cannot open. + _UNSUPPORTED_DETAIL = ('not supported: this app has no map layout for ' + 'this chip (supported: 156-qubit Heron, ' + '120-qubit Nighthawk)') + + def _mark_unsupported(targets, get_backend): + """Fetch each eligible target's backend once and mark the ones the + map cannot open (no coordinate layout) as not eligible, so they are + never searched. Returns (memoised get_backend, unsupported names). + A backend that cannot be fetched is left to the scan, which reports + it as an error row.""" + from ..constants import resolve_coords + fetched = {} + + def _get(name): + if name not in fetched: + fetched[name] = get_backend(name) + return fetched[name] + + unsupported = set() + for t in targets: + if not t.get('eligible'): + continue + try: + backend = _get(t['name']) + except Exception: + continue + if not getattr(backend, 'num_qubits', None): + continue # nothing to judge the chip by; scan it + try: + resolve_coords(backend) + except NotImplementedError: + t['eligible'] = False + t['reason'] = 'not supported by this app' + unsupported.add(t['name']) + return _get, unsupported + def _cached_history_for(backend_name): """Assemble a per-backend history dict from the DISK CACHE ONLY (no remote fetch). Empty when the backend has no cached snapshots.""" @@ -1166,6 +1203,7 @@ def _clear_scan_results(): _scan['order'].clear() _scan['current'] = None _scan['active'] = None + _scan['unsupported'] = set() btn_scan_qpus.disabled = False btn_scan_qpus.description = '🌐 Scan all QPUs' btn_scan_clear.on_click(lambda b: _clear_scan_results()) @@ -1209,6 +1247,8 @@ def _short_reason(reason): r = str(reason or '') if r.startswith('current backend'): return 'current' + if r.startswith('not supported'): + return 'not supported' if r.startswith('different family'): lo, hi = r.find('('), r.rfind(')') return r[lo + 1:hi] if 0 <= lo < hi else 'other family' @@ -1381,7 +1421,12 @@ def _scan_detail_line2(r): return " · ".join(segs) def _render_results(scan_result): - results = scan_result['results'] + unsupported = _scan.get('unsupported') or set() + # Backends the map cannot open go to the bottom, after every other row. + results = ([r for r in scan_result['results'] + if r.get('name') not in unsupported] + + [r for r in scan_result['results'] + if r.get('name') in unsupported]) children = [] # when a PAST date is active locally, the local backend was scored @@ -1402,6 +1447,8 @@ def _render_results(scan_result): # / no-candidate rows are selectable but their open button is disabled. def _single_label(r): name = esc(str(r['name'])) + if r.get('name') in unsupported: + return f"{name} — not supported" if r.get('error'): return f"{name} — ✗ error" if r.get('best_lqs') is None: @@ -1411,6 +1458,8 @@ def _single_label(r): def _single_detail(r): box = ("
") + if r.get('name') in unsupported: + return box + f"{esc(_UNSUPPORTED_DETAIL)}
" if r.get('error'): return box + f"✗ {esc(str(r['error']))}" sweep = r.get('sweep') or {} @@ -1431,9 +1480,13 @@ def _single_detail(r): results, label_fn=_single_label, detail_fn=_single_detail, - open_ok_fn=lambda r: not r.get('error') and r.get('best_lqs') is not None, + open_ok_fn=lambda r: (not r.get('error') + and r.get('name') not in unsupported + and r.get('best_lqs') is not None), payload_fn=lambda r: _best_scan_entry(r.get('sweep') or {}), - disabled_tip='no candidates to open on QPU 2') + disabled_tip=lambda r: ('not supported by this app' + if r.get('name') in unsupported + else 'no candidates to open on QPU 2')) children.extend(selector) scan_results_box.children = children @@ -1544,11 +1597,14 @@ def _work(): # them leaking under the cell — the same context every sweep uses. with _capture_qpu_notices( lambda: _scan.get('current') or 'general') as handler: + # A chip the map cannot open is listed, never searched. + get_b, unsupported = _mark_unsupported(eligible, get_backend) + _scan['unsupported'] = unsupported # One scan path, one param source — forwards hybrid. - result = _scan_backends(eligible, norb, get_backend, + result = _scan_backends(eligible, norb, get_b, get_props, use_scan_filter) # Circuit-level LQS per backend — one scale everywhere. - _annotate_scan_circuit_lqs(result, get_backend, get_props) + _annotate_scan_circuit_lqs(result, get_b, get_props) return (result, list(handler.records)) scan_spawn_bg(_work, on_done=_on_scan_done, on_error=_on_scan_error) @@ -2108,13 +2164,16 @@ def _batch_complete(res, n_circuits): and len(res.get('circuits') or []) == n_circuits and n_circuits > 0) - def _rank_batch_rows(rows, n_circuits): + def _rank_batch_rows(rows, n_circuits, unsupported=()): """Complete batches first, by batch metric; then partial batches (more - circuits placed first); then backends that were not scanned; errors - last. A partial batch's metric is a product over fewer circuits, so - it is never compared with a complete one.""" + circuits placed first); then backends that were not scanned; then + errors; backends the map cannot open last. A partial batch's metric is + a product over fewer circuits, so it is never compared with a complete + one.""" def _key(r): res = r.get('sweep') + if r.get('name') in unsupported: + return (4, 0, 0.0) if r.get('error'): return (3, 0, 0.0) if not res: @@ -2140,7 +2199,8 @@ def _local_batch_reference(norbs): return None return local - def _with_reference_row(results, active_name, local, n_circuits): + def _with_reference_row(results, active_name, local, n_circuits, + unsupported=()): """Scan rows without the active backend, ranked by `_rank_batch_rows`; with a complete local result, a reference row for it at its rank.""" rows = [r for r in results if r.get('name') != active_name] @@ -2149,9 +2209,10 @@ def _with_reference_row(results, active_name, local, n_circuits): rows.append({'name': active_name, 'family': None, 'sweep': local, 'best_lqs': metric, 'best_k': None, 'error': None, 'reference': True}) - return _rank_batch_rows(rows, n_circuits) + return _rank_batch_rows(rows, n_circuits, unsupported) - def _render_batch_results(scan_result, active_name=None, norbs=()): + def _render_batch_results(scan_result, active_name=None, norbs=(), + unsupported=()): # ONE QPU selector over the scan_qpus-ranked batches: pick a backend, # see its per-circuit detail, open the whole batch on QPU 2. A batch # that does not fully fit is selectable but not openable. The active @@ -2160,12 +2221,14 @@ def _render_batch_results(scan_result, active_name=None, norbs=()): n_circuits = len(norbs) local = _local_batch_reference(norbs) rows = _with_reference_row(scan_result['results'], active_name, - local, n_circuits) + local, n_circuits, unsupported) def _label(r): name = esc(str(r['name'])) if r.get('reference'): name += ' (this QPU)' + if r.get('name') in unsupported: + return f"{name} — not supported" if r.get('error'): return f"{name} — ✗ error" res = r.get('sweep') @@ -2181,6 +2244,8 @@ def _label(r): def _detail(r): box = ("
") + if r.get('name') in unsupported: + return box + f"{esc(_UNSUPPORTED_DETAIL)}
" if r.get('error'): return box + f"✗ {esc(str(r['error']))}" return box + f"{esc(_batch_line_html(r.get('sweep') or {}))}" @@ -2198,6 +2263,8 @@ def _payload(r): def _tip(r): if r.get('reference'): return 'already QPU 1' + if r.get('name') in unsupported: + return 'not supported by this app' return 'batch does not fully fit on this backend' children = _scan_selector( @@ -2236,6 +2303,7 @@ def _on_scan_batch(b): kwargs = _sweep_kwargs_from_ui() buffer = lucj_buffer_slider.value active_name = getattr(state, 'active_backend_name', None) + batch = {'unsupported': set()} def _batch_sweep_fn(norb, backend, props, *, min_bridges=None, top_n=3): excl = _batch_backend_exclusions(props, getattr(backend, 'name', None)) @@ -2276,7 +2344,10 @@ def _work(): if t.get('name') == active_name: t['eligible'] = False t['reason'] = 'current backend — see local results above' - get_backend = state.active_service.backend + # A chip the map cannot open is listed, never searched. + get_backend, unsupported = _mark_unsupported( + targets, state.active_service.backend) + batch['unsupported'] = unsupported get_props = make_scan_get_props(state) return qpu_scan.scan_qpus( targets, norbs[0], get_backend, get_props, @@ -2285,7 +2356,8 @@ def _work(): def _done(result): _reset() - _render_batch_results(result, active_name, norbs) + _render_batch_results(result, active_name, norbs, + batch['unsupported']) def _err(exc): _reset() diff --git a/tests/test_scan_unsupported.py b/tests/test_scan_unsupported.py new file mode 100644 index 0000000..bd85906 --- /dev/null +++ b/tests/test_scan_unsupported.py @@ -0,0 +1,98 @@ +"""A backend the map cannot open (no coordinate layout for its chip) is listed +as " — not supported" at the bottom of both multi-QPU scans: never +searched, never ranked, never openable. +""" +from types import SimpleNamespace + +from ipywidgets import Button, HBox + +from test_scan_ui import (_build, _detail_by_name, _labels, _patch_scan, + _sweep, _StubProps) + +HERON_156 = {'family': 'Heron', 'revision': '2'} +HERON_R1_133 = {'family': 'Heron', 'revision': '1'} + + +def _backends(): + """ibm_a / ibm_b: 156-qubit Heron (supported); ibm_torino: 133-qubit + Heron r1 (no map layout).""" + return { + 'ibm_a': SimpleNamespace(name='ibm_a', num_qubits=156, + processor_type=HERON_156), + 'ibm_b': SimpleNamespace(name='ibm_b', num_qubits=156, + processor_type=HERON_156), + 'ibm_torino': SimpleNamespace(name='ibm_torino', num_qubits=133, + processor_type=HERON_R1_133), + } + + +def _targets(): + return [{'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in ('ibm_torino', 'ibm_a', 'ibm_b')] + + +def _open_button(box): + return next(c for w in box.children if isinstance(w, HBox) + for c in w.children if isinstance(c, Button)) + + +# ── single-circuit scan ───────────────────────────────────────────── + +def test_single_scan_lists_an_unsupported_chip_last_and_never_searches_it( + monkeypatch): + b = _build(monkeypatch) + backends = _backends() + b.state.active_service = SimpleNamespace(backend=lambda n: backends[n]) + searched = [] + sweeps = {'ibm_a': _sweep(0.40, 0.30), 'ibm_b': _sweep(0.60, 0.50), + 'ibm_torino': _sweep(0.99, 0.99)} + _patch_scan(monkeypatch, sweeps=sweeps, targets=_targets(), + props={'ibm_a': _StubProps(0.40), 'ibm_b': _StubProps(0.60), + 'ibm_torino': _StubProps(0.99)}) + import iqmapper.ancilla_sweep as asw + real = asw.sweep_ancilla_layouts + monkeypatch.setattr(asw, 'sweep_ancilla_layouts', + lambda norb, backend, props, **k: + searched.append(backend.name) or real( + norb, backend, props, **k)) + b.btn_scan_qpus.click() + + labels = _labels(b) + assert labels[-1] == 'ibm_torino — not supported' + assert labels[0].startswith('ibm_b') and labels[1].startswith('ibm_a') + assert 'ibm_torino' not in searched + assert 'supported: 156-qubit Heron, 120-qubit Nighthawk' in \ + _detail_by_name(b, 'ibm_torino') + button = _open_button(b.scan_results_box) + assert button.disabled is True + assert button.tooltip == 'not supported by this app' + + +# ── batch scan ────────────────────────────────────────────────────── + +def test_batch_scan_lists_an_unsupported_chip_last_and_never_searches_it( + monkeypatch): + from test_batch_scan_active import _selector, _wire + from test_floor_batch_ui import _build as _build_batch + import iqmapper.qpu_scan as qs + b, state = _build_batch(monkeypatch) + log = _wire(monkeypatch, b, state) + backends = _backends() + state.active_service = SimpleNamespace( + backend=lambda n: log['fetched'].append(n) or backends[n]) + monkeypatch.setattr(qs, 'list_scan_targets', lambda *a, **k: [ + {'name': n, 'family': 'Heron', 'eligible': True, 'reason': None} + for n in ('ibm_torino', 'ibm_a', 'ibm_b')]) + from test_batch_scan_active import TOTALS + monkeypatch.setitem(TOTALS, 'ibm_torino', 0.99) + b.btn_scan_batch.click() + + dd, button = _selector(b) + labels = [label for label, _ in dd.options] + assert labels[0].startswith('ibm_a') and labels[1].startswith('ibm_b') + assert labels[-1] == 'ibm_torino — not supported' + assert 'ibm_torino' not in log['searched'] + dd.value = len(labels) - 1 + assert button.disabled is True + assert button.tooltip == 'not supported by this app' + From 5239e523049b17c3e0736c6f6e5d5f325eba9a1b Mon Sep 17 00:00:00 2001 From: Milana Bazayeva Date: Tue, 27 Oct 2026 16:11:28 -0400 Subject: [PATCH 55/66] Cleanup before 0.1.0: remove dead code, comments describe the code as it is, docs match the UI --- README.md | 14 +- TUTORIAL.md | 28 ++- iqmapper/connection.py | 2 +- iqmapper/export/layout_io.py | 2 +- iqmapper/paths.py | 2 +- iqmapper/ui/backend_switch.py | 7 +- iqmapper/ui/benchmark_panel.py | 45 ++-- iqmapper/ui/builder.py | 58 ++--- iqmapper/ui/color_picker.py | 12 +- iqmapper/ui/history.py | 11 +- iqmapper/ui/lucj_panel.py | 322 ++----------------------- iqmapper/ui/pretty_json.py | 5 +- iqmapper/ui/time_panel.py | 212 ++-------------- tests/test_ancilla_sweep.py | 4 +- tests/test_async_util.py | 16 +- tests/test_audit_section3_fixes.py | 2 +- tests/test_auto_panel_ui_polish.py | 16 +- tests/test_auto_subpanels.py | 22 +- tests/test_benchmark.py | 58 +++-- tests/test_benchmark_integration.py | 24 +- tests/test_benchmark_ui.py | 41 ++-- tests/test_calibration_epoch.py | 10 +- tests/test_combined_sweep.py | 1 - tests/test_copy_lengths.py | 1 - tests/test_engine_dedupe_plans.py | 4 +- tests/test_error_tab_backend_switch.py | 3 +- tests/test_export_layout_io.py | 4 +- tests/test_failures_logged.py | 61 +++++ tests/test_floor_batch_ui.py | 24 +- tests/test_html_safe.py | 7 +- tests/test_import_export_ui.py | 5 +- tests/test_inter_qpu_dispose.py | 14 +- tests/test_inter_qpu_handoff.py | 5 +- tests/test_inter_qpu_live_model.py | 11 +- tests/test_live_fixes_ui.py | 12 +- tests/test_multi_sweep_ui.py | 24 -- tests/test_paths.py | 16 +- tests/test_plot_node_guard.py | 3 +- tests/test_png_colorbars.py | 1 - tests/test_qpu_scan.py | 1 - tests/test_reservoir.py | 1 - tests/test_scan_notices.py | 1 - tests/test_scan_targets_line.py | 6 +- tests/test_scan_ui.py | 5 +- tests/test_scan_ui_pass.py | 20 +- tests/test_scoring_core.py | 2 +- tests/test_stability_ui.py | 1 - tests/test_subpanel_persistence.py | 40 +-- tests/test_sweep_notices.py | 8 +- tests/test_sweep_ui.py | 2 +- tests/test_ui_cleanup.py | 2 - 51 files changed, 319 insertions(+), 879 deletions(-) create mode 100644 tests/test_failures_logged.py diff --git a/README.md b/README.md index cbd250a..ce7d988 100644 --- a/README.md +++ b/README.md @@ -200,8 +200,8 @@ live in your own `qiskit-ibm-runtime` account store. I-QMapper normally ranks layouts on the calibration IBM *reports*, which is refreshed about once a day. Qubits drift inside that window, so a layout chosen -at 14:00 can sit on a qubit that degraded at 11:00. The Benchmark section in the -**Auto** tab re-measures the hardware and feeds the result back as a "measured" +at 14:00 can sit on a qubit that degraded at 11:00. The Benchmark section +re-measures the hardware and feeds the result back as a "measured" calibration epoch — the heatmap, LQS, candidate ranking and exports all read it exactly as they read the reported one. @@ -260,8 +260,10 @@ single-qubit error lands on the two-qubit gate and every edge reads a few times worse than reported. After every run I-QMapper compares the measured values with the reported ones -per property and shows the result (`cz_error: ×1.1 median vs reported · 3 of -351 >2× worse`). If a property's median is more than 2× away in either +per property and says what it found: "✅ Benchmark applied — measured values +are in line with IBM's reported calibration.", or that some properties "differ +by a constant factor (×1.3) and are shown on IBM's scale"; the figures are in +the **Details** table. If a property's median is more than 2× away in either direction, that is a systematic offset rather than drift — a whole chip does not degrade uniformly overnight — and the epoch is applied in **relative mode**: each value is rescaled so the median matches the reported one, which removes the @@ -279,8 +281,8 @@ values. If both come back offset it is the estimator; if only the parallel run is offset it is crosstalk between simultaneously driven pairs. A run reports what it actually measured: `measured 156/156 qubits` when complete, -`⚠ partial` when some elements failed to fit, and `⚠ no usable measurements — -reported epoch kept` when nothing came back. A rejected or failed job shows IBM's +`⚠ partial` when some elements failed to fit, and "⚠ Nothing usable was +measured — IBM's reported calibration is still in use." when nothing came back. A rejected or failed job shows IBM's own error text and the job ids. Nothing is ever labelled "measured" unless it was. Measured values replace reported ones only for the elements actually measured; diff --git a/TUTORIAL.md b/TUTORIAL.md index 3925e4f..1974821 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -67,9 +67,10 @@ Two ways: - **By hand** — click qubits on the map to add/remove them from the current circuit's layout. In LUCJ mode, qubits get roles (α system / β system / ancilla bridges) with distinct colors. -- **Auto-place (LUCJ mode)** — one click runs the zig-zag placer, which scans - the heavy-hex topology for the lowest-error chain using the current - calibration data, and places the whole ansatz for you. +- **Auto-place (LUCJ mode)** — **🤖 Generate LUCJ Layout** searches every + ancilla count, scores each candidate on the current calibration data, and + places the best one; the **Layout** dropdown lists the others, ranked by + LQS. Multiple circuits can coexist, each with its own color; undo/redo covers every placement action. @@ -78,13 +79,13 @@ placement action. ## 4. Score & compare -Open the **Analysis** panel: - -- **LQS (Layout-Quality Score)** — an error-aware fidelity estimate for each - placed circuit, computed from the readout and two-qubit errors of exactly - the qubits and couplings you're using. Use it to compare candidate layouts - *before* spending QPU time. -- **Rankings** — see alternative placements ordered by score. +- **LQS (Layout-Quality Score)** — the **Estimated Layout-Quality** box in the + sidebar gives an error-aware fidelity estimate for each placed circuit, + computed from the readout and two-qubit errors of exactly the qubits and + couplings you're using. Use it to compare candidate layouts *before* + spending QPU time. +- **Rankings** — **🔍 Error → Analysis** ranks qubits and gates by error + (🏆 Qubit Ranking, 🔗 Gate Ranking). The score is a first-order, *relative* heuristic — treat differences between layouts as meaningful, not the absolute number. @@ -96,7 +97,7 @@ layouts as meaningful, not the absolute number. The **Time** panel changes *which calibration snapshot* the whole map shows: - **Live** — the current calibration (default). -- **Point** — a specific past date/time. +- **Snapshot** — a specific past date/time. - **Intraday** — scan one day and slide through its calibration updates. - **Multi-day** — fetch a date range and slide day by day. @@ -109,7 +110,8 @@ still the right ones today. ## 6. Check stability -In the **Analysis** panel, enable **Stability Check** and pick a window +In the sidebar card **⚠️ Stability check**, tick **⚠️ Enable Stability check** +and pick a window (7 / 14 / 30 days). For the qubits and couplings of your placed layout, the tool analyses the cached history and flags which elements are *stable* and which are *volatile* — because the best qubit today is not always the best @@ -173,7 +175,7 @@ multi-QPU scan. ## 8. Import & export -From the **Export** tab: +From **📁 I/O → 📤 Export**: - **Layout JSON** — export your layouts (including LUCJ role partitions) and re-import them later or on another backend. diff --git a/iqmapper/connection.py b/iqmapper/connection.py index e387316..8a51760 100644 --- a/iqmapper/connection.py +++ b/iqmapper/connection.py @@ -245,7 +245,7 @@ def _refresh_connect_btn(): [step2_lbl, txt_account, btn_load_account, status_w[2]], layout=_ROW_LAYOUT, ) - # Passive status message under the row (no longer clickable). Indented + # Passive status message under the row (not clickable). Indented # to align under the text input column. lbl_account_status = widgets.HTML( "", layout=widgets.Layout(margin='0 0 0 168px'), diff --git a/iqmapper/export/layout_io.py b/iqmapper/export/layout_io.py index 124bdad..78ec72e 100644 --- a/iqmapper/export/layout_io.py +++ b/iqmapper/export/layout_io.py @@ -511,7 +511,7 @@ def _extract_layout_from_qpy(file_bytes): # parser — that's well outside the scope of this tool. We strip the two # QASM comment flavours (//... line comments and /*...*/ block comments) # before the qubit-count regex runs, so a register declaration sitting -# behind a `// qreg q[64];` line comment no longer counts. +# behind a `// qreg q[64];` line comment does not count. _QASM_LINE_COMMENT_RE = re.compile(r'//[^\n]*') _QASM_BLOCK_COMMENT_RE = re.compile(r'/\*.*?\*/', re.DOTALL) _QASM2_QREG_RE = re.compile(r'\bqreg\s+\w+\s*\[\s*(\d+)\s*\]\s*;') diff --git a/iqmapper/paths.py b/iqmapper/paths.py index 18331e2..76bcf1b 100644 --- a/iqmapper/paths.py +++ b/iqmapper/paths.py @@ -65,7 +65,7 @@ def safe_path(raw_path: str, default_ext: str = '') -> str: tools and is a known smuggling vector against C-level open(). - Any '..' COMPONENT (separated by '/' or '\\\\') rejected. Plain names like 'my..file.json' that happen to contain the literal - characters are allowed (previously these were also rejected). + characters are allowed. - Absolute paths ('/...') rejected. - Home-expansion ('~...') rejected. - Path components longer than 255 bytes rejected — matches the diff --git a/iqmapper/ui/backend_switch.py b/iqmapper/ui/backend_switch.py index 62c8eb1..c2bf3b4 100644 --- a/iqmapper/ui/backend_switch.py +++ b/iqmapper/ui/backend_switch.py @@ -32,7 +32,6 @@ not a thread synchronisation primitive — `threading.Event`'s blocking semantics would be wrong here. """ -import contextlib import logging from ..html_safe import esc @@ -149,9 +148,11 @@ def _refresh_qpu1_label(): if refresh_qpu1_label_cell else None) if hook is None: return - with contextlib.suppress(Exception): - _log.debug("Refreshing QPU-1 toggle label after backend switch") + _log.debug("Refreshing QPU-1 toggle label after backend switch") + try: hook() + except Exception: + _log.debug("QPU-1 toggle label refresh failed", exc_info=True) # Optional: best-effort callable to re-render the Time/Delta panel so the # Error-tab header reflects the switched backend. Absent in callers/tests diff --git a/iqmapper/ui/benchmark_panel.py b/iqmapper/ui/benchmark_panel.py index 364de9a..b23ffa3 100644 --- a/iqmapper/ui/benchmark_panel.py +++ b/iqmapper/ui/benchmark_panel.py @@ -226,8 +226,8 @@ def refresh_summary(*_a): f"{esc(gate.warning)}
") if gate.warning else '' # A plan that cannot be split under IBM's per-job shot limit must - # not be submittable: sending it costs a round trip and, before - # v3, ended in a false success. Computed BEFORE the summary is + # not be submittable: sending it only costs a round trip. + # Computed BEFORE the summary is # written so the reason is visible, not just a greyed button. ok, reason = bench.plan_is_submittable(plan, plan.shots) if not ok: @@ -514,9 +514,8 @@ def _install_epoch(epoch, *, source): An epoch that measured NOTHING is a failure, not a successful no-op. Applying one overwrites the reported calibration with an identical - copy and labels it "measured" — which is exactly what happened after - IBM rejected the 18 Sept submission, and is the single outcome this - feature must never produce. + copy and labels it "measured" — the single outcome this feature must + never produce. """ state, refresh_fn = active_target() _check_consistency(state, epoch) @@ -628,11 +627,9 @@ def _is_edge_prop(key): def _result_sentence(epoch, stats, rescaled): """One plain sentence. No jargon, no warning glyph, no method talk. - The panel used to print the engine's own vocabulary — "estimator - mismatch suspected; measured values applied in RELATIVE mode" — which - describes the implementation rather than what the user now has. This - says what happened to their numbers and why, and leaves the figures - to the Details table. + Says what happened to the user's numbers and why, in plain words + rather than the engine's vocabulary, and leaves the figures to the + Details table. """ in_band = [k for k in stats if k not in rescaled] # stats order parts = ['\u2705 Benchmark applied'] @@ -882,9 +879,9 @@ def _on_run(_b=None): def _record_jobs(chunk_index, job_ids, status): """Persist ids the moment they exist, not at the end. - The 18 Sept run left no record of what had been submitted because - it never completed. With this, an interrupted or rejected run can - still be diagnosed and — via reanalyze_from_jobs — recovered. + A run that never completes would otherwise leave no record of what + was submitted. With this, an interrupted or rejected run can still + be diagnosed and — via reanalyze_from_jobs — recovered. """ job_ids_seen[str(chunk_index)] = list(job_ids) if backend_name: @@ -910,7 +907,7 @@ def _done(payload): else (payload, [])) # The raw dump is saved BEFORE anything can go wrong in folding, # and regardless of whether the epoch turns out usable: it is the - # diagnostic artefact that did not exist on 18 Sept. + # diagnostic artefact for a run that goes wrong. if backend_name and expdata: try: bench.save_raw_results(backend_name, started_at, expdata) @@ -918,11 +915,9 @@ def _done(payload): _log.debug('raw dump failed', exc_info=True) try: # `when=started_at` deliberately: the epoch, its _jobs.json and - # its _raw.json must share one timestamp. On 20 Sept they did - # not — the dumps were named by submission time (12:38:08) and - # the epoch by completion time (12:50:10), so the three - # artifacts of a single run looked like unrelated files and the - # raw dump appeared to be missing. + # its _raw.json must share one timestamp. Naming the dumps by + # submission time and the epoch by completion time would make + # the three artifacts of one run look like unrelated files. epoch = bench.results_to_epoch(raw, plan, reported_q, reported_g, edges, when=started_at) @@ -1080,8 +1075,7 @@ def _phase_key(key): btn_bench_reanalyze.disabled = False _log.exception('reanalysis failed') # Persist whatever exists even on the failure path: a reanalysis - # that leaves nothing behind cannot be diagnosed, which is - # exactly how the 20 Sept attempt became a dead end. + # that leaves nothing behind cannot be diagnosed. _persist_attempt(name, attempt_at, expdata, [f'reanalysis failed: {exc}']) lbl_bench_status.value = _err(exc) @@ -1090,8 +1084,7 @@ def _phase_key(key): if btn_bench_reanalyze is not None: btn_bench_reanalyze.disabled = False # Raw dump and notices FIRST, unconditionally — an empty epoch is - # precisely the case where the artefacts are needed, and the old code - # returned before writing them. + # precisely the case where the artefacts are needed. _persist_attempt(name, attempt_at, expdata, epoch.notices) if _install_epoch(epoch, source=f'Reanalysis of L{plan.level} run (no QPU)') \ @@ -1101,10 +1094,8 @@ def _phase_key(key): def _persist_attempt(backend_name, when, expdata, notices): """Write the raw dump and the notices for ANY attempt. - Including one that produced nothing. The 20 Sept reanalysis wrote no - file at all because the empty-epoch branch returned before the dump, - so there was no way to tell whether it had failed on the composite - metadata or on something else. + Including one that produced nothing: without its files there is no way + to tell why an attempt came back empty. """ if not backend_name: return diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index fb6c7e6..c3f3731 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/ui/builder.py @@ -341,7 +341,6 @@ def _run_pipeline(self): ft_boundary_penalty=self.ft_boundary_penalty, joint_params_box=self.joint_params_box, lucj_multi_ancillas=self.lucj_multi_ancillas, - btn_lucj_multi=self.btn_lucj_multi, btn_lucj_multi_sweep=self.btn_lucj_multi_sweep, btn_scan_batch=self.btn_scan_batch, scan_batch_box=self.scan_batch_box, @@ -352,10 +351,6 @@ def _run_pipeline(self): set_num_circuits=self._set_num_circuits_silent, lucj_all_layouts=self._lucj_all_layouts, rescore_cell=self._bench_rescore, - lucj_multi_results=self._lucj_multi_results, - lucj_multi_norbs_list=self._lucj_multi_norbs, - lucj_multi_ancillas_list=self._lucj_multi_ancillas, - lucj_multi_dropdowns=self._lucj_multi_dropdowns, refresh=self._refresh, get_export=self._get_export, update_view=lambda: self._update_view(), chk_line_only=self.chk_line_only, # Multi-QPU scan. @@ -1260,21 +1255,17 @@ def _build_auto_lucj_widgets(self, W): (rank by error), btn_lucj_run, lbl_lucj_status. Inspect Layouts: dd_lucj_layout (ranked selector, disabled until - populated — also drives cascading re-optimization for - multi-circuit) + lbl_lucj_detail. + populated) + lbl_lucj_detail. Multi-Circuit: lucj_multi_norbs (Text '8, 8' default), - lucj_buffer_slider (0..5 buffer qubits), btn_lucj_multi, + lucj_buffer_slider (0..5 buffer qubits), btn_lucj_multi_sweep, lbl_lucj_multi, lucj_multi_detail_box (VBox populated per packed circuit). - Mutable backing stores on ``self.*`` (mutated by + Mutable backing store on ``self.*`` (mutated by ``setup_lucj_callbacks`` via ``.append()`` / ``.clear()`` — identity must remain stable across the builder's lifetime): - ``_lucj_all_layouts``, ``_lucj_multi_results``, - ``_lucj_multi_norbs`` (for cascading re-optimization on dropdown - change), ``_lucj_multi_dropdowns`` - (``circuit_idx → (dropdown, label, candidates)``). + ``_lucj_all_layouts``. Click handlers + cascading observer in ``setup_lucj_callbacks``. ``_load_device_graph`` resets the @@ -1578,10 +1569,6 @@ def _build_auto_lucj_widgets(self, W): # Mutable container for all computed single-circuit layouts. self._lucj_all_layouts = [] - self._lucj_multi_results = [] - self._lucj_multi_norbs = [] - self._lucj_multi_ancillas = [] - self._lucj_multi_dropdowns = {} # ── Multi-Circuit (intra-QPU multi-programming) cluster ── self.lucj_multi_norbs = Text( @@ -1643,15 +1630,8 @@ def _build_auto_lucj_widgets(self, W): min_width=W.min_width)) self.multi_advanced_acc.set_title(0, '⚙️ Advanced') self.multi_advanced_acc.selected_index = None # collapsed on open - # Legacy multi-circuit button — no longer shown in the Multi subpanel - # (the sweep is the single generate action). The widget + its handler - # (_on_lucj_multi) and engine (get_multi_circuit_layouts) stay wired and - # test-pinned; it is simply omitted from the layout below. - self.btn_lucj_multi = Button( - description='🤖 Generate Multi-Circuit', - button_style='success', layout=W) - # Sweep-based multi-circuit (the ONLY multi generate action in the UI): - # greedy auto-best per circuit with a per-circuit override dropdown. + # The multi-circuit generate action: best placement per circuit with + # a per-circuit override dropdown. self.btn_lucj_multi_sweep = Button( description='🧺 Generate Multi-Circuit', button_style='info', layout=W) @@ -1667,7 +1647,7 @@ def _build_auto_lucj_widgets(self, W): # bar); empty when nothing was emitted. self.lbl_lucj_multi_notices = HTML("") # Populated dynamically with per-circuit dropdowns when the - # user clicks btn_lucj_multi. + # user clicks btn_lucj_multi_sweep. self.lucj_multi_detail_box = VBox() # Roles offered by the legend panel — must match plot._LEGEND_ROLE_ORDER. @@ -1747,8 +1727,7 @@ def _legend_panel(self): rows = [self.legend_rows[r] for r in self._LEGEND_ROLES] controls = VBox([self.chk_legend_enabled, *rows]) # Collapse into an Accordion so the controls don't clutter the - # sidebar by default. Accordion provides its own header so the - # inline "🏷️ Legend" HTML title is no longer needed. + # sidebar by default. The Accordion header is the section title. accordion = Accordion(children=[controls]) accordion.set_title(0, '🏷️ Legend') accordion.selected_index = None # collapsed on open @@ -2102,8 +2081,6 @@ def _build_auto_lucj_view(self): self.lucj_multi_ancillas, self.lucj_buffer_slider, self.multi_advanced_acc, - # Legacy btn_lucj_multi intentionally omitted — the sweep button is - # the single generate action. Handler/engine remain wired + pinned. self.btn_lucj_multi_sweep, self.btn_scan_batch, self.lbl_lucj_multi, @@ -2349,8 +2326,8 @@ def _refresh(self, *args): try: self._ext_fns["update_fidelity"]() except Exception: - # Was a silent debug log — bumped to WARNING because it used - # to hide real bugs in estimate_circuit_fidelity. + # Logged with the traceback: a failure here is a real bug in + # estimate_circuit_fidelity. _log.exception("update_fidelity failed during _refresh") if self.state.calibration_data_label: self.lbl_calibration_date.value = ( @@ -2648,7 +2625,7 @@ def _on_auto_map(self, b): """ try: self.state.push_undo() - # parse_auto_text now returns (count, autodetect_stats). The stats + # parse_auto_text returns (count, autodetect_stats). The stats # let us tell the user whether alpha/beta were topologically # auto-detected or fell back to midpoint split. count, stats = export_mod.parse_auto_text( @@ -2887,9 +2864,6 @@ def _load_device_graph(self, change=None, force=False): self.lbl_lucj_status.value = "" self.lbl_lucj_notices.value = "" self.lbl_lucj_detail.value = "" - self._lucj_multi_results.clear() - self._lucj_multi_norbs.clear() - self._lucj_multi_dropdowns.clear() self.lbl_lucj_multi.value = "" self.lbl_lucj_multi_notices.value = "" self.lucj_multi_detail_box.children = () @@ -2991,7 +2965,7 @@ def _update_view(self, change=None): # dd_mode changes arrive with a non-nav owner, and _toggle_intra_qpu # / bootstrap call with change=None — all of those still rebuild so # the manual view is correct the next time it opens. A bare nav to - # auto/export/error used to reallocate every per-circuit tab VBox for + # auto/export/error would reallocate every per-circuit tab VBox for # a view that doesn't display them (flicker + wasted work); skip it. _nav_only = change is not None and getattr(change, 'owner', None) is self.nav_bar if mode == 'manual' or not _nav_only: @@ -3092,13 +3066,13 @@ def _enable_export_gif(self): def _set_num_circuits_silent(self, n): """Set ``num_circuits`` WITHOUT the full ``_update_view`` rebuild its - observer would fire — used when a multi-circuit sweep/legacy apply + observer would fire — used when a multi-circuit generate or apply changes the count as a RESULT of its own action. The visible Multi subpanel is already updated in place (its summary and per-circuit override dropdowns are persistent widgets refreshed by the caller), so rebuilding ``content_box`` would only repaint an identical - panel — the flicker X2b targets. A count change genuinely needs just the + panel and make it flicker. A count change genuinely needs just the OFF-SCREEN refresh: the per-circuit manual UI + the ancilla-tool options — exactly what ``_build_dynamic_ui`` does (it never touches ``content_box``). The nav options don't depend on ``num_circuits`` (only @@ -3526,8 +3500,8 @@ def _mk_fill_swatch(self, idx, color): def on_click(b): # Set current_fill BEFORE the picker value — the picker's - # observer guard then sees new == current_fill and no-ops, - # avoiding the old double-rebuild. Borders flip in place. + # observer guard then sees new == current_fill and no-ops, so + # nothing is rebuilt twice. Borders flip in place. self.state.layouts_data[idx]['current_fill'] = color self.state.layouts_data[idx]['cp_fill_advanced'].value = color self._sync_manual_swatch_borders(idx) diff --git a/iqmapper/ui/color_picker.py b/iqmapper/ui/color_picker.py index 503b292..f8394d7 100644 --- a/iqmapper/ui/color_picker.py +++ b/iqmapper/ui/color_picker.py @@ -108,9 +108,8 @@ def __init__( layout=_TOGGLE_BTN_LAYOUT, icon='plus', ) - # Explicit reference to the header preview swatch. The old code - # mutated this widget via `self.widget.children[0].children[1]`, - # which broke silently if the VBox/HBox order ever changed. + # Explicit reference to the header preview swatch, so it does not + # depend on the VBox/HBox child order. self._swatch_preview = HTML(_preview_swatch_html(self.current_color)) self.widget = VBox([ @@ -229,12 +228,9 @@ def set_color(self, hex_color): return self.current_color = hex_color self.advanced_picker.value = hex_color - # Direct reference — was previously self.widget.children[0].children[1]. self._swatch_preview.value = _preview_swatch_html(hex_color) - # Selection change flips at most two borders — no full rebuild. The - # old refresh_swatches() here tore down/recreated every Button and, - # with the previously-shared swatch Layout, cascaded a re-render - # across all swatches: the visible "salto" on neighbouring boxes. + # Selection change flips at most two borders — no full rebuild, so + # neighbouring swatches do not re-render or jump. self._sync_swatch_borders() if self.on_change_callback: self.on_change_callback(hex_color) diff --git a/iqmapper/ui/history.py b/iqmapper/ui/history.py index 04fb30a..711a5da 100644 --- a/iqmapper/ui/history.py +++ b/iqmapper/ui/history.py @@ -18,12 +18,6 @@ _log = logging.getLogger(__name__) -# Per-frame display time in the exported GIF (seconds). 0.5s ≈ 2 fps — -# readable date overlay without a 30-day history running a full minute. -# imageio applies this to *every* frame; no per-frame variation here. -GIF_FRAME_DURATION_S = 0.5 - - def setup_history_callbacks(ctx): """Wire history/GIF callbacks. Returns dict of helper functions.""" @@ -43,9 +37,8 @@ def setup_history_callbacks(ctx): hist_slider_box = ctx.hist_slider_box btn_export_gif = ctx.btn_export_gif fname_img = ctx.fname_img - # Time-lapse export controls (new in v6+). Optional on ctx for backward - # compat: if absent, fall back to the legacy fname_img-based name and - # GIF format with the constant frame duration. + # Time-lapse export controls, optional on ctx: if absent, the export + # falls back to the fname_img-based name, GIF format and 2 fps. fname_timelapse = getattr(ctx, 'fname_timelapse', None) dd_timelapse_format = getattr(ctx, 'dd_timelapse_format', None) slider_timelapse_fps = getattr(ctx, 'slider_timelapse_fps', None) diff --git a/iqmapper/ui/lucj_panel.py b/iqmapper/ui/lucj_panel.py index ed87f5f..eff2c86 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -174,7 +174,6 @@ def setup_lucj_callbacks(ctx): # Unpack context for readability state = ctx.state - out = ctx.out W = ctx.W lucj_norb_slider = ctx.lucj_norb_slider @@ -205,7 +204,6 @@ def setup_lucj_callbacks(ctx): int_cands_per_circuit = getattr(ctx, 'int_cands_per_circuit', None) ft_boundary_penalty = getattr(ctx, 'ft_boundary_penalty', None) joint_params_box = getattr(ctx, 'joint_params_box', None) - btn_lucj_multi = ctx.btn_lucj_multi btn_lucj_multi_sweep = ctx.btn_lucj_multi_sweep btn_scan_batch = ctx.btn_scan_batch scan_batch_box = ctx.scan_batch_box @@ -217,10 +215,6 @@ def setup_lucj_callbacks(ctx): intra_qpu_mode = ctx.intra_qpu_mode _lucj_all_layouts = ctx.lucj_all_layouts - _lucj_multi_results = ctx.lucj_multi_results - _lucj_multi_norbs_list = ctx.lucj_multi_norbs_list - _lucj_multi_ancillas_list = ctx.lucj_multi_ancillas_list - _lucj_multi_dropdowns = ctx.lucj_multi_dropdowns def _refresh(): ctx.refresh() @@ -253,7 +247,7 @@ def _apply_multi_candidate(circ_idx, candidate): d['styles'][q] = {'fill': beta_fill, 'line': _line, 'width': _width, 'text_color': _text} # Sweep entries carry per-circuit ancillas; paint them as the ancilla - # role. Legacy candidates have no 'ancillas' key → nothing changes. + # role. anc_fill = 'none' if line_only else hex_to_rgba(d['defaults']['fill_anc'], 1.0) d['ancilla'] = [str(q) for q in candidate.get('ancillas', []) if str(q) in state.qubit_ids] @@ -374,10 +368,9 @@ def _on_lucj_layout_select(change): # The LQS shown here is the circuit-level score — the same number # the Estimated Layout-Quality box reports. '(template)' flags the # internal heuristic used only when circuit scoring is unavailable. - with contextlib.suppress(Exception): - dd_lucj_layout.tooltip = ( - 'LQS = circuit-level fidelity; "(template)" = fallback ' - 'heuristic \u00b7 README: LQS') + dd_lucj_layout.tooltip = ( + 'LQS = circuit-level fidelity; "(template)" = fallback ' + 'heuristic \u00b7 README: LQS') dd_lucj_layout.observe(_on_lucj_layout_select, names='value') # ── Dropdown re-seed helper (observer-safe) ────────────────── @@ -389,8 +382,7 @@ def _seed_layout_dropdown(entries, dd_opts): _lucj_all_layouts.extend(entries) # Suppress observer firing while re-seeding: otherwise setting # value=0 fires _on_lucj_layout_select → apply, then we apply again - # below — double push_undo + redundant refresh. Same unobserve → - # set → observe dance as _reoptimize_downstream. + # below — double push_undo + redundant refresh. dd_lucj_layout.unobserve(_on_lucj_layout_select, names='value') dd_lucj_layout.options = dd_opts dd_lucj_layout.value = 0 if dd_opts else None @@ -672,9 +664,8 @@ def _generate_legacy(norb, requested_ancillas): f"✅ {len(all_layouts)} layouts found (norb={norb}, " f"ancillas={num_ab}). Best: err={sc}{ancilla_note}{_epoch_suffix()}") - # ── Stratified ancilla sweep (new default) ─────────────────── + # ── Stratified ancilla sweep (the default) ─────────────────── def _generate_sweep(norb): - from ..ancilla_sweep import sweep_ancilla_layouts # exact same params the scan uses (min_bridges / top_n / hybrid). kwargs = _sweep_kwargs_from_ui() @@ -788,9 +779,9 @@ def _generate_sweep(norb): f"{'s' if len(flat) != 1 else ''} found{vin_txt}") else: lbl_lucj_status.value = ( - f"
⚠️ Sweep produced no candidates.
") + "
⚠️ Sweep produced no candidates.
") # ── Single circuit LUCJ generate ───────────────────────────── def _on_lucj_generate(b): @@ -1110,7 +1101,9 @@ def _annotate_scan_circuit_lqs(scan_result, get_backend, get_props): continue try: props = get_props(get_backend(r['name'])) - except Exception: + except Exception as exc: + _log.warning("circuit scores unavailable for %s: properties " + "could not be loaded: %s", r['name'], exc) continue # Surface the calibration provenance the shim used. r['vintage'] = getattr(props, 'vintage', None) @@ -1342,9 +1335,7 @@ def _scan_best_lqs(r): (annotation failed). Falls back to the product heuristic — flagged '(template)' — only when NOTHING was circuit-scored. Returns (value, is_template) so the comparison-table cell, the selector label - and the detail line all quote the SAME number (previously the label - quoted best_lqs = max product_score, diverging from the lqs_circuit - table/detail).""" + and the detail line all quote the SAME number.""" sweep = r.get('sweep') or {} lqs_vals = [e['lqs_circuit'] for entries in sweep.get('strata', {}).values() @@ -1403,8 +1394,7 @@ def _open(_b): layout=Layout(align_items='center'))] def _scan_detail_line2(r): - """Second detail line — the per-backend data the removed comparison - table used to carry: stability badge · k-cap phrase · calibration + """Second detail line — per-backend data: stability badge · k-cap phrase · calibration vintage. Segments that don't apply are omitted; '' when none apply. All dynamic values are esc()'d inside the reused helpers / here.""" segs = [] @@ -1523,7 +1513,7 @@ def _notices_html(notices): f"" f"
" + "
".join(parts) + "
" - f"") + "") def _append_notices(notices): # Collapsible loud notices under the scan results. Hidden when empty. @@ -1610,199 +1600,6 @@ def _work(): btn_scan_qpus.on_click(_on_scan_click) - # ── Multi-circuit LUCJ generate ────────────────────────────── - def _on_lucj_multi(b): - if state.active_backend is None: - lbl_lucj_multi.value = ( - "❌ No backend connected.") - return - if hasattr(state.active_backend, 'coords'): - lbl_lucj_multi.value = ( - "❌ Auto-LUCJ " - "requires a connected IBM backend.") - return - - raw = lucj_multi_norbs.value.strip() - if not raw: - lbl_lucj_multi.value = ( - "❌ Enter norb values (e.g. 8, 8)") - return - try: - norb_list = [int(x.strip()) for x in raw.split(',') if x.strip()] - except ValueError: - lbl_lucj_multi.value = ( - "❌ Invalid norb values") - return - if len(norb_list) < 1: - return - - # Per-circuit ancilla counts (parallel to norb). Blank → fall back - # to the single Ancilla dropdown for every circuit (legacy). - anc_raw = lucj_multi_ancillas.value.strip() - ancilla_list = None - if anc_raw: - try: - ancilla_list = [int(x.strip()) for x in anc_raw.split(',') if x.strip()] - except ValueError: - lbl_lucj_multi.value = ( - "❌ Invalid ancilla values " - "(use integers, e.g. 2, 2; -1 = auto)") - return - if len(ancilla_list) != len(norb_list): - lbl_lucj_multi.value = ( - f"❌ " - f"{len(ancilla_list)} ancilla values but " - f"{len(norb_list)} circuits — match them or leave " - f"ancilla blank.") - return - - btn_lucj_multi.disabled = True - btn_lucj_multi.description = '⏳ Generating...' - lbl_lucj_multi.value = "" - - try: - from ..auto_lucj import get_multi_circuit_layouts - - requested_ancillas = lucj_ancilla_dd.value - results = get_multi_circuit_layouts( - norb_list=norb_list, - backend=state.active_backend, - score=lucj_chk_score.value, - buffer_qubits=lucj_buffer_slider.value, - props=_local_scoring_props(), # loaded snapshot, not live - requested_bridges=requested_ancillas, - requested_bridges_list=ancilla_list, - ) - - if not intra_qpu_mode.value and len(norb_list) > 1: - intra_qpu_mode.value = True # OFF→ON reveal: legitimate rebuild - # Same treatment as the sweep path: targeted count refresh, no - # visible Auto-view rebuild (results render in place below). - set_num_circuits(len(norb_list)) - - state.push_undo() - for res in results: - best = res['all_candidates'][0] - _apply_multi_candidate(res['circuit_idx'], best) - - _refresh() - _get_export() - - # Store for re-optimization - _lucj_multi_results.clear() - _lucj_multi_results.extend(results) - _lucj_multi_norbs_list.clear() - _lucj_multi_norbs_list.extend(norb_list) - _lucj_multi_ancillas_list.clear() - _lucj_multi_ancillas_list.extend(ancilla_list if ancilla_list is not None else []) - _lucj_multi_dropdowns.clear() - - # Build per-circuit dropdowns - detail_widgets = [] - for res in results: - cidx = res['circuit_idx'] - cands = res['all_candidates'] - - detail_widgets.append(HTML( - f"
" - f"C{cidx+1} — norb={res['norb']}, " - f"{len(cands)} layouts, ancillas={res['num_bridges']}
")) - - dd_opts = [] - for c in cands: - sc = f"err={c['score']:.4f}" if c['score'] is not None else "?" - dd_opts.append((f"#{c['rank']} ({sc}) α:[{c['alpha'][0]}..{c['alpha'][-1]}]", - c['rank'] - 1)) - - dd_circ = Dropdown(options=dd_opts, value=0, - description=f'C{cidx+1}:', layout=W, - style={'description_width': '35px'}) - lbl_circ = HTML("") - - def _show_detail(entry, lbl): - lbl.value = ( - f"
" - f"α={len(entry['alpha'])} β={len(entry['beta'])}
") - - _show_detail(cands[0], lbl_circ) - - _lucj_multi_dropdowns[cidx] = { - 'dropdown': dd_circ, 'label': lbl_circ, - 'candidates': cands, - } - - def _make_on_change(ci, candidates, label): - def _on_change(change): - idx = change['new'] - if idx is None or idx >= len(candidates): - return - entry = candidates[idx] - state.push_undo() - _apply_multi_candidate(ci, entry) - _refresh() - _get_export() - _show_detail(entry, label) - if ci < len(_lucj_multi_norbs_list) - 1: - _reoptimize_downstream(ci) - return _on_change - - dd_circ.observe(_make_on_change(cidx, cands, lbl_circ), names='value') - detail_widgets.extend([dd_circ, lbl_circ]) - - lucj_multi_detail_box.children = detail_widgets - - summary_lines = [] - for res in results: - cands = res['all_candidates'] - sc = f"err={cands[0]['score']:.4f}" if cands[0]['score'] is not None else "unscored" - summary_lines.append( - f"C{res['circuit_idx']+1} norb={res['norb']}: " - f"{len(cands)} candidates, best {sc}") - - # Per-circuit clamp note: with mixed norb_list each circuit - # may hit its own ceil(norb/4) cap. Same rationale as the - # single-circuit ancilla_note above — auto_lucj's stderr - # warning is invisible in Jupyter. - ancilla_notes = [] - if requested_ancillas is not None and requested_ancillas >= 0: - ancilla_notes = [ - (f"C{res['circuit_idx']+1} (norb={res['norb']}): " - f"requested {requested_ancillas}, got " - f"{res['num_bridges']} (max one bridge every 4 orbitals)") - for res in results - if res['num_bridges'] != requested_ancillas - ] - ancilla_warning = "" - if ancilla_notes: - ancilla_warning = ( - "
⚠️ Ancilla request clamped:
" - + "
".join(f"  • {n}" for n in ancilla_notes) - ) - - lbl_lucj_multi.value = ( - f"
" - f"✅ {len(results)} circuits placed! " - f"(buffer={lucj_buffer_slider.value})
" - f"{'
'.join(summary_lines)}" - f"{ancilla_warning}
" - f"Use dropdowns below to switch layouts per circuit.
") - - # No ctx.update_view(): the count refresh is targeted (above) and - # the detail widgets / summary render into persistent widgets. - - except Exception as e: - lbl_lucj_multi.value = ( - f"
" - f"❌ Error: {esc(str(e))}
") - finally: - btn_lucj_multi.disabled = False - btn_lucj_multi.description = '🤖 Generate Multi-Circuit' - - btn_lucj_multi.on_click(_on_lucj_multi) - # ── Multi-Circuit SWEEP (auto-best per circuit + override) ────── _multi_sweep = {'result': None, 'replan_in_flight': False, 'dropdowns': {}} @@ -2369,92 +2166,3 @@ def _err(exc): btn_scan_batch.on_click(_on_scan_batch) - # ── Re-optimization ───────────────────────────────────── - def _reoptimize_downstream(changed_idx): - try: - from ..auto_lucj import reoptimize_after_change - - locked = {} - for ci in range(changed_idx + 1): - info = _lucj_multi_dropdowns.get(ci) - if info is None: - continue - dd = info['dropdown'] - cands = info['candidates'] - sel_idx = dd.value - if sel_idx is not None and sel_idx < len(cands): - full = cands[sel_idx].get('layout_full', cands[sel_idx]['layout']) - locked[ci] = set(full) - - new_results = reoptimize_after_change( - backend=state.active_backend, - norb_list=_lucj_multi_norbs_list, - locked_qubits=locked, - changed_idx=changed_idx, - buffer_qubits=lucj_buffer_slider.value, - score=lucj_chk_score.value, - props=_local_scoring_props(), # loaded snapshot, not live - requested_bridges=lucj_ancilla_dd.value, - requested_bridges_list=(list(_lucj_multi_ancillas_list) - if _lucj_multi_ancillas_list else None), - ) - - for res in new_results: - cidx = res['circuit_idx'] - cands = res['all_candidates'] - info = _lucj_multi_dropdowns.get(cidx) - if info is None: - continue - - dd = info['dropdown'] - lbl = info['label'] - dd.unobserve_all() - - dd_opts = [] - for c in cands: - sc = f"err={c['score']:.4f}" if c['score'] is not None else "?" - dd_opts.append((f"#{c['rank']} ({sc}) α:[{c['alpha'][0]}..{c['alpha'][-1]}]", - c['rank'] - 1)) - dd.options = dd_opts - dd.value = 0 - info['candidates'] = cands - - _apply_multi_candidate(cidx, cands[0]) - lbl.value = ( - f"
" - f"α: {', '.join(str(q) for q in cands[0]['alpha'])}
" - f"β: {', '.join(str(q) for q in cands[0]['beta'])}
" - f"♻️ re-optimized ({len(cands)} candidates)
") - - def _make_reopt_cb(ci, candidates, label): - def _cb(change): - idx = change['new'] - if idx is None or idx >= len(candidates): - return - entry = candidates[idx] - state.push_undo() - _apply_multi_candidate(ci, entry) - _refresh() - _get_export() - label.value = ( - f"
" - f"α={len(entry['alpha'])} β={len(entry['beta'])}
") - if ci < len(_lucj_multi_norbs_list) - 1: - _reoptimize_downstream(ci) - return _cb - dd.observe(_make_reopt_cb(cidx, cands, lbl), names='value') - - _refresh() - _get_export() - lbl_lucj_multi.value = lbl_lucj_multi.value.replace( - '', - f'
♻️ Re-optimized C{changed_idx+2}+ after C{changed_idx+1} change', - 1, - ) - - except Exception as e: - _log.exception("LUCJ re-optimization failed") - with out: - print(f"⚠️ Re-optimization failed: {e!s}") diff --git a/iqmapper/ui/pretty_json.py b/iqmapper/ui/pretty_json.py index 02a01c0..3bdd49a 100644 --- a/iqmapper/ui/pretty_json.py +++ b/iqmapper/ui/pretty_json.py @@ -229,9 +229,8 @@ def pretty_json_html(data): i += 1 body = ''.join(out) - # Bumped from 12px → 14px on user feedback: at 12px on a 720px sidebar - # the JSON tree was effectively unreadable without zooming in. 14px - # matches the rest of the sidebar body text. + # 14px matches the rest of the sidebar body text; smaller is hard to + # read on a 720px sidebar. result = ( "
str: (defensive — index entries are written by data.py and shouldn't ever be malformed, but we don't want a parse error to hide the option). """ - # Late import keeps this module importable even when tested without - # the data module on the path (see _self_test below). + # Late import keeps this module importable without the data module. try: from ..data import utc_str_to_local_label return utc_str_to_local_label(ts, ref_date=ref_date) @@ -214,36 +182,22 @@ def _format_hm_from_ts(ts: str, ref_date=None) -> str: # ───────────────────────────────────────────────────────────────────── -# Legacy stub — kept as no-op for backward compat -# ───────────────────────────────────────────────────────────────────── -# Time/delta state fields (time_mode, delta_enabled, ref_qubit_props, ...) -# are now declared in SessionState.__init__ (state.py, session version 5+). -# This function remains as a no-op so any external caller that still imports -# install_state_defaults continues to work. The _STATE_DEFAULTS dict has been -# removed since it's no longer the source of truth — see state.py instead. - -def install_state_defaults(state) -> None: - """No-op. Kept for backward compat — fields are now in SessionState.__init__.""" - return None - - -# ───────────────────────────────────────────────────────────────────── -# Cache-loader shim (supports both new SQLite cache and old JSON cache) +# Cache loader # ───────────────────────────────────────────────────────────────────── def _load_calibration_by_timestamp(backend_name: str, last_update: str, data_mod) -> Optional[Tuple[dict, dict]]: """Return (qubit_props, gate_props) for a specific (backend, timestamp) - via the legacy JSON cache in data_mod. + via the JSON cache in data_mod. Returns None if the timestamp is not cached.""" - legacy_loader = getattr(data_mod, '_load_calibration', None) - if legacy_loader is not None: + loader = getattr(data_mod, '_load_calibration', None) + if loader is not None: try: - got = legacy_loader(backend_name, last_update) + got = loader(backend_name, last_update) if got is not None: return got except Exception as exc: - _log.debug("Legacy cache load failed: %s", exc) + _log.debug("Cache load failed: %s", exc) return None @@ -397,7 +351,6 @@ class TimePanelBuilder: def __init__(self, state, data_mod, export_mod, refresh_plot, load_device_graph, spawn_bg=None, on_gif_export=None, on_history_loaded=None): - install_state_defaults(state) self.state = state self.data_mod = data_mod self.export_mod = export_mod @@ -827,7 +780,7 @@ def _on_point_known(self, change): # query the wrong day after the local→UTC conversion at load. if not change['new']: return - # `self.data_mod` can be a stub (see _self_test below) that omits the + # `self.data_mod` can be a stub that omits the # local-time helpers. Treat a missing helper the same as a parse # failure (return None) so the observer no-ops cleanly instead # of raising AttributeError up through the ipywidgets callback. @@ -1195,11 +1148,6 @@ def rebuild(self): b._refresh_delta_visibility() b._refresh_all() - def apply_delta(self): - b = self._b - b._apply_current_delta() - b._refresh_all() - def status_text(self): return describe_current_view(self._b.state) @@ -1245,7 +1193,6 @@ def build_time_panel( api_namespace exposes: .rebuild() — re-render panel (after session load, etc.) - .apply_delta() — re-compute state.delta_* from current config .status_text() — text describing what's currently shown """ return TimePanelBuilder( @@ -1272,132 +1219,3 @@ def _auto_ref_hint(state) -> str: return ("Reference = previous calibration in the sequence " "(step-by-step change) \u00b7 README: Delta references") return "" - - -# ═════════════════════════════════════════════════════════════════════ -# Self-test: run without a real backend to verify widget construction -# ═════════════════════════════════════════════════════════════════════ - -def _self_test(): - """Construct the panel with dummy stubs, verify no exceptions. - Run with: python -m iqmapper.ui.time_panel""" - import types - - class _StubState: - def __init__(self): - self.active_backend = None - self.active_backend_name = 'ibm_stub' - self.qubit_props_data = {} - self.gate_props_data = {} - self.calibration_data_label = None - self.cal_history = {} - self.cal_history_dates = [] - self.delta_mode = False - self.delta_qubit_props = {} - self.delta_gate_props = {} - self.delta_date_a = None - self.delta_date_b = None - # Time-navigation + delta-reference fields. These live on - # SessionState now (see state.py); the stub mirrors them so - # the self-test does not depend on the real SessionState class. - self.time_mode = 'live' - self.delta_enabled = False - self.delta_ref_mode = 'specific' - self.point_timestamp = None - self.intraday_date = None - self.intraday_timestamps = [] - self.intraday_index = 0 - self.range_start = None - self.range_end = None - self.range_index = 0 - self.ref_timestamp = None - self.ref_qubit_props = None - self.ref_gate_props = None - self._live_qubit_props = None - self._live_gate_props = None - self._live_cal_label = None - - data_stub = types.SimpleNamespace( - list_known_calibrations=lambda bn, d: [], - scan_day_calibrations=lambda s, b, d, progress_callback=None: [], - get_props_for_datetime=lambda s, b, t: (None, {}, {}), - fetch_calibration_history=lambda s, a, b, progress_callback=None: 0, - apply_history_snapshot=lambda s, ds: True, - _extract_last_update=lambda p: None, - _load_calibration=lambda bn, lu: None, - ) - export_stub = types.SimpleNamespace( - compute_error_delta=lambda a, b, c, d: ({}, {}), - ) - - state = _StubState() - panel, api = build_time_panel( - state=state, - data_mod=data_stub, - export_mod=export_stub, - refresh_plot=lambda: None, - load_device_graph=lambda: None, - spawn_bg=lambda fn, on_done=None, on_error=None: ( - on_done(fn()) if on_done else fn() - ), - ) - assert panel is not None - assert api.status_text() == 'Live calibration — ibm_stub' - # Exercise each mode - for mode in ('live', 'point', 'intraday', 'range'): - state.time_mode = mode - api.rebuild() - # Exercise delta toggles - state.delta_enabled = True - for ref in ('specific', 'first', 'previous'): - state.delta_ref_mode = ref - api.rebuild() - print("✓ Self-test passed — panel constructs in all 12 non-trivial states.") - - # ── Handler firing ─────────────────────────────────────────────── - # rebuild() above never invokes the button/observer callbacks, so a - # bare-name call inside a handler (e.g. `_scan_day(...)` instead of - # `self._scan_day(...)` after the closure->method refactor) would slip - # through every gate. Build a fresh panel, populate the inputs so the - # scan/fetch/load handlers reach their worker calls, then fire every - # handler and re-raise ONLY NameError (stub-data early-returns and other - # guard exceptions are expected and harmless here). - from datetime import date as _date - tb = TimePanelBuilder( - _StubState(), data_stub, export_stub, - refresh_plot=lambda: None, load_device_graph=lambda: None, - spawn_bg=lambda fn, on_done=None, on_error=None: ( - on_done(fn()) if on_done else fn()), - ) - tb.build() - _past = _date(2020, 1, 1) - for attr, val in (('dp_point', _past), ('tx_point_hour', '12:00'), - ('dp_intra', _past), ('dp_ref', _past), - ('tx_ref_hour', '12:00'), - ('dp_range_from', _past), ('dp_range_to', _date(2020, 1, 2))): - w = getattr(tb, attr, None) - if w is not None: - # Test-harness sweep: some widgets refuse the seed value - # (traitlets TraitError, TypeError, ValueError, …). - # Best-effort — log and keep sweeping the remaining attrs. - try: - w.value = val - except Exception: - _log.debug("test-harness seed failed for %s=%r", attr, val, exc_info=True) - for name in sorted(n for n in dir(tb) if n.startswith('_on_')): - fn = getattr(tb, name) - for arg in (None, {'new': None, 'old': None, 'name': 'value', 'owner': None}): - try: - fn(arg) - break - except NameError: - raise # the bug class this guard exists to catch - except TypeError: - continue # wrong arg shape (observer vs click) -> retry - except Exception: - break # guard/stub-data early-return -> fine - print("✓ Handler self-test passed — all _on_* handlers callable, no bare-name calls.") - - -if __name__ == '__main__': - _self_test() \ No newline at end of file diff --git a/tests/test_ancilla_sweep.py b/tests/test_ancilla_sweep.py index 3583cbe..c7e790d 100644 --- a/tests/test_ancilla_sweep.py +++ b/tests/test_ancilla_sweep.py @@ -171,7 +171,7 @@ def test_kminus1_variant_present(backend, props): "the top layout's own k-1 subtraction variant is absent") -# ── F2c: bridge_slots are the first-k' standard slots — no holes, ever ────── +# ── bridge_slots are the first-k' standard slots — no holes, ever ─────────── def test_bridge_slots_are_prefix(backend, props): """The regression born from the scattered-ancilla bug: EVERY entry in @@ -186,7 +186,7 @@ def test_bridge_slots_are_prefix(backend, props): assert len(e['bridge_slots']) == k_prime == k -# ── F2d: a derived k' entry == its parent embedding's first-k' bridges ────── +# ── a derived k' entry == its parent embedding's first-k' bridges ─────────── def test_prefix_legacy_equivalence(backend, props): """A DERIVED k' candidate must be indistinguishable from the original diff --git a/tests/test_async_util.py b/tests/test_async_util.py index d9951fd..9408842 100644 --- a/tests/test_async_util.py +++ b/tests/test_async_util.py @@ -43,7 +43,7 @@ def _join(thread): assert not thread.is_alive(), "worker thread did not finish" -# ── M3 t1: THE live-shaped regression — worker → captured main loop ───────── +# ── THE live-shaped regression — worker → captured main loop ──────────────── def test_marshal_schedules_onto_captured_loop_from_worker(monkeypatch, _capture_isolation): @@ -95,7 +95,7 @@ def _worker(): loop.close() -# ── M3 t3: caller already on the captured main thread → inline fast path ──── +# ── caller already on the captured main thread → inline fast path ─────────── def test_marshal_inline_on_main_thread(monkeypatch, _capture_isolation): # A captured loop that MUST NOT be used from the main-thread caller. @@ -112,7 +112,7 @@ def call_soon_threadsafe(self, cb): # pragma: no cover assert ran == [threading.current_thread().ident] # inline, on this thread -# ── M3 t2: headless (no captured loop) → inline, zero warnings ────────────── +# ── headless (no captured loop) → inline, zero warnings ───────────────────── def test_init_main_loop_headless_no_loop_no_warning(monkeypatch, _capture_isolation): @@ -173,7 +173,7 @@ async def _main(): assert loop is not None and kind == 'asyncio' -# ── N3: capture sources — the live ipykernel case + tornado last resort ───── +# ── capture sources — the live ipykernel case + tornado last resort ───────── def _policy_set_loop(): import asyncio @@ -186,7 +186,7 @@ def test_capture_via_set_loop_when_not_in_coroutine(monkeypatch, """THE live fix: get_running_loop() fails on the main thread (capture runs in a widget callback — launch_mapper on Connect — not a coroutine), but the thread OWNS a running loop set via set_event_loop. Capture must pick it up - from the policy thread-local (previously it gave up → None → worker inline).""" + from the policy thread-local rather than give up (None → worker inline).""" import asyncio loop = asyncio.new_event_loop() started = threading.Event() @@ -245,7 +245,7 @@ def current(instance=True): asyncio.set_event_loop(prev) -# ── N4: WIRING pin — the real UI build captures, then a worker schedules ──── +# ── WIRING pin — the real UI build captures, then a worker schedules ──────── def _build_ui(monkeypatch): import numpy as np @@ -314,7 +314,7 @@ def _cb(): asyncio.run(_main()) -# ── P3: capture-once + main-only — a worker must NEVER overwrite the capture ─ +# ── capture-once + main-only — a worker must NEVER overwrite the capture ───── def test_worker_capture_does_not_overwrite_good_capture(monkeypatch, _capture_isolation): @@ -400,7 +400,7 @@ def _secondary_worker(): loop.close() -# ── t4: default_spawn_bg deferred-scheduler behaviour (exc binding etc.) ──── +# ── default_spawn_bg deferred-scheduler behaviour (exc binding etc.) ──────── def test_on_error_receives_exception_with_deferred_scheduler(monkeypatch, _capture_isolation): diff --git a/tests/test_audit_section3_fixes.py b/tests/test_audit_section3_fixes.py index 18965b1..e5d5585 100644 --- a/tests/test_audit_section3_fixes.py +++ b/tests/test_audit_section3_fixes.py @@ -1,4 +1,4 @@ -"""Regression tests for the audit §3 fixes: connectivity dedup, 8-char hex, sci format.""" +"""Connectivity dedup, 8-char hex colours, scientific number format.""" from types import SimpleNamespace import numpy as np diff --git a/tests/test_auto_panel_ui_polish.py b/tests/test_auto_panel_ui_polish.py index 2332df2..165adbb 100644 --- a/tests/test_auto_panel_ui_polish.py +++ b/tests/test_auto_panel_ui_polish.py @@ -67,7 +67,7 @@ def _empty_sweep(): 'per_stratum': {}, 'mapping_cap': None} -# ── t1: the expert knobs are collapsed out of the primary flow ────────────── +# ── the expert knobs are collapsed out of the primary flow ────────────────── def test_search_cap_and_deep_search_live_in_advanced_accordion(monkeypatch): b, _ = _build(monkeypatch) @@ -94,7 +94,7 @@ def test_search_cap_and_deep_search_live_in_advanced_accordion(monkeypatch): assert b.chk_deep_search.value is True -# ── t2: diversity ships ON and still reaches the engine both ways ─────────── +# ── diversity ships ON and still reaches the engine both ways ─────────────── def test_diverse_default_on(monkeypatch): b, _ = _build(monkeypatch) @@ -117,7 +117,7 @@ def test_diverse_default_on(monkeypatch): f"unticking diversity did not disable it: {seen.get('diversity_threshold')!r}") -# ── t3: the score checkbox belongs to legacy mode only ────────────────────── +# ── the score checkbox belongs to legacy mode only ────────────────────────── def test_score_checkbox_hidden_in_auto_visible_in_legacy(monkeypatch): b, _ = _build(monkeypatch) @@ -142,7 +142,7 @@ def test_score_checkbox_hidden_in_auto_visible_in_legacy(monkeypatch): "the checkbox must stay in the tree, only hidden") -# ── t4: the hidden checkbox must not drag other widgets down with it ──────── +# ── the hidden checkbox must not drag other widgets down with it ──────────── def test_score_checkbox_owns_its_layout(monkeypatch): """Regression: `W` is ONE shared Layout instance handed to ~86 widgets, so @@ -175,7 +175,7 @@ def test_score_checkbox_owns_its_layout(monkeypatch): (b.chk_lucj_diverse.layout.width, b.chk_lucj_diverse.layout.margin) -# ── t5: benchmark lives in the sidebar, not the Auto tab ─────────────────── +# ── benchmark lives in the sidebar, not the Auto tab ─────────────────────── def _sidebar_accordion(b): """The numbered settings accordion from the assembled sidebar.""" @@ -233,7 +233,7 @@ def test_benchmark_widgets_do_not_share_a_mutated_layout(monkeypatch): assert b.tb_bench_qpu.layout.display == 'none' -# ── t7: the search (engine widgets: see test_search_ui.py) ───────────────── +# ── the search (engine widgets: see test_search_ui.py) ───────────────────── def test_exhaustive_still_routes_to_the_frozen_sweep(monkeypatch): b, _ = _build(monkeypatch) @@ -267,7 +267,7 @@ def test_guided_results_render_through_the_existing_display(monkeypatch): assert best, 'best-per-k line empty for a guided result' -# ── t8: diverse enumeration ──────────────────────────────────────────────── +# ── diverse enumeration ──────────────────────────────────────────────────── def test_diverse_enumeration_checkbox_defaults_on(monkeypatch): b, _ = _build(monkeypatch) @@ -351,7 +351,7 @@ def test_the_cap_notice_goes_to_the_log_not_the_ui(monkeypatch): assert any('hybrid k=1: cap reached' in m for m in collect.messages) -# ── t9: one cap notice per stratum, not two ──────────────────────────────── +# ── one cap notice per stratum, not two ──────────────────────────────────── _CAP_ENTRY = {'layout': [0, 1, 2, 3], 'alpha': [0, 1], 'beta': [2, 3], 'ancillas': [4], 'bridge_slots': (0,), 'product_score': 0.9, diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py index 53ba600..687c504 100644 --- a/tests/test_auto_subpanels.py +++ b/tests/test_auto_subpanels.py @@ -1,7 +1,6 @@ """Auto-tab Single/Multi subpanels, candidate-detail declutter, and the export-is-auto-current pin. """ -from pathlib import Path from types import SimpleNamespace import numpy as np @@ -56,7 +55,7 @@ def _build(monkeypatch): return b, state -# ── t1: subpanels follow the Multi-Programming enable ─────────────────────── +# ── subpanels follow the Multi-Programming enable ─────────────────────────── def test_subpanels_follow_multi_programming(monkeypatch): b, state = _build(monkeypatch) @@ -76,7 +75,7 @@ def test_subpanels_follow_multi_programming(monkeypatch): assert b.btn_lucj_multi_sweep in b._auto_multi_panel.children -# ── R3 t1: exactly TWO buttons in the Multi subpanel — no legacy node ──────── +# ── exactly TWO buttons in the Multi subpanel — no legacy node ─────────────── def test_multi_subpanel_has_two_buttons_no_legacy(monkeypatch): b, state = _build(monkeypatch) @@ -86,7 +85,7 @@ def test_multi_subpanel_has_two_buttons_no_legacy(monkeypatch): buttons = [w for w in b._auto_multi_panel.children if isinstance(w, Button)] assert len(buttons) == 2 # generate + batch assert set(buttons) == {b.btn_lucj_multi_sweep, b.btn_scan_batch} - assert b.btn_lucj_multi not in b._auto_multi_panel.children # legacy gone + assert not hasattr(b, 'btn_lucj_multi') # no second button # The sweep button is the single generate action — no "(sweep)" qualifier. assert b.btn_lucj_multi_sweep.description == '🧺 Generate Multi-Circuit' # The ancilla field speaks one (sweep) language. @@ -94,18 +93,7 @@ def test_multi_subpanel_has_two_buttons_no_legacy(monkeypatch): assert 'Legacy' not in (b.lucj_multi_ancillas.tooltip or '') -# ── R3 t2: the legacy handler + engine stay defined (source pin) ──────────── - -def test_legacy_handler_and_engine_still_defined(): - panel = Path('iqmapper/ui/lucj_panel.py').read_text() - assert 'def _on_lucj_multi(' in panel # handler retained - assert 'get_multi_circuit_layouts' in panel # engine path retained - # And the widget object is still wired (clickable) for the pinned tests. - from iqmapper.ui.builder import MapperUIBuilder - assert hasattr(MapperUIBuilder, '_build_auto_lucj_view') - - -# ── t3: candidate detail shows counts, never qubit index lists ────────────── +# ── candidate detail shows counts, never qubit index lists ────────────────── def test_detail_panel_counts_not_qubit_lists(monkeypatch): b, state = _build(monkeypatch) @@ -121,7 +109,7 @@ def test_detail_panel_counts_not_qubit_lists(monkeypatch): assert '0, 1' not in v and 'ancillas:' not in v # no id lists -# ── t5: an applied batch (C1..Cn) is auto-reflected in the export ────────── +# ── an applied batch (C1..Cn) is auto-reflected in the export ────────────── def test_export_reads_applied_batch(): from iqmapper.export.codegen import get_qiskit_layout_code diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 3d8bd89..e8cd8bd 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -456,7 +456,7 @@ def test_make_runtime_runner_raises_the_documented_install_hint(): bench.make_runtime_runner(object()) -# ── v2: target-selection modes ────────────────────────────────────── +# ── target-selection modes ────────────────────────────────────────── def test_current_layouts_mode_unions_every_circuit_slot(): """Hand-placed or auto-placed, C1..Cn all count — and no duplicate edges.""" @@ -510,7 +510,7 @@ def test_sweep_mode_is_offered_only_once_a_sweep_has_run(): assert bench.TARGET_SWEEP not in bench.available_target_modes(state, []) assert bench.TARGET_SWEEP in bench.available_target_modes( state, [_entry([0, 1], [2], [3])]) - # Order is the one the spec lists. + # Order is the documented one. assert bench.available_target_modes(state, [_entry([0], [1], [])]) == [ bench.TARGET_CURRENT, bench.TARGET_SWEEP, bench.TARGET_WHOLE, bench.TARGET_CUSTOM] @@ -525,7 +525,7 @@ def test_default_mode_prefers_a_placed_layout(): bench.TARGET_SWEEP -# ── v2: Level 1 does not scale with qubit count ───────────────────── +# ── Level 1 does not scale with qubit count ───────────────────────── def test_level1_cost_is_flat_in_qubit_count(): """LocalReadoutError is two circuits whatever the width. @@ -560,7 +560,7 @@ def test_level2_cost_scales_with_layer_count_not_edge_count(): assert few.circuits >= one_edge.circuits -# ── v3 Part A: the plan is composite, and it fits in a job ────────── +# ── the plan is composite, and it fits in a job ──────────────────── def test_level1_is_two_circuits_at_any_width(): """LocalReadoutError prepares all targets at once: 2 circuits, always.""" @@ -590,8 +590,8 @@ def test_level2_is_bounded_by_layers_not_edges(): def test_full_chip_level3_is_about_134_circuits(): """The number that decides whether the job is accepted at all. - The pre-v3 plan emitted one spec per qubit and per edge: ~43,400 circuits - on this device, which IBM rejected outright (error 1520). + One spec per qubit and per edge would be ~43,400 circuits on this device, + which IBM rejects outright (error 1520). """ graph = rustworkx.generators.heavy_hex_graph(9) coupling = [tuple(e) for e in graph.edge_list()] @@ -650,7 +650,7 @@ def test_summary_line_states_circuits_shots_and_jobs(): assert 'estimate' in cost.text -# ── v3 Part C: an empty epoch is a failure ───────────────────────── +# ── an empty epoch is a failure ──────────────────────────────────── def test_epoch_reports_emptiness_partiality_and_completeness(): qp, gp = _reported() @@ -678,7 +678,7 @@ def test_epoch_reports_emptiness_partiality_and_completeness(): assert partial.measured_count == (1, 0) -# ── v3 Part B: a failed job is an error, not an empty parse ──────── +# ── a failed job is an error, not an empty parse ─────────────────── def test_check_chunk_status_raises_on_an_errored_job(): class _Errored: @@ -710,7 +710,7 @@ def errors(self): assert bench._check_chunk_status(_Done(), 0) == ['ok1'] -# ── v3 Part E: the analysis-result shape adapter ─────────────────── +# ── the analysis-result shape adapter ────────────────────────────── def test_result_adapter_handles_the_list_shape(): items = [_Res(name='T1', value=1.0, qubits=[3])] @@ -775,7 +775,7 @@ def test_components_to_qubits_parses_both_forms(): SimpleNamespace(device_components=[]), fallback=(9,)) == [9] -# ── v3 Part D: persistence and diagnosis ─────────────────────────── +# ── persistence and diagnosis ────────────────────────────────────── def test_job_record_is_written_at_submission(tmp_path, monkeypatch): monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) @@ -867,11 +867,11 @@ def test_diagnose_raw_on_a_missing_file(): assert 'Could not read' in bench.diagnose_raw('/nonexistent/path.json') -# ── v3.1: the 20 Sept live-run symptoms, reproduced offline ──────── +# ── live-run result shapes, reproduced offline ───────────────────── # -# Each of these fails against the pre-v3.1 parser with the exact error the -# live run produced. The shapes are taken from the real raw dump -# (measured_20260920T123808_raw.json), not from what we assumed. +# The shapes are taken from a real raw dump of a live run, not from what +# the documentation suggests; each one breaks a parser that assumes +# otherwise. class _Mitigator: """LocalReadoutMitigator: assignment_matrix is a METHOD, not an attribute. @@ -976,7 +976,7 @@ def test_one_qubit_rb_counts_qubits_not_gate_results(): assert note, epoch.notices assert '8 qubit' in note, f'counted gate results, not qubits: {note!r}' assert '24' not in note - # The per-qubit EPGs are kept for the 2Q analysis (Part B). + # The per-qubit EPGs are kept for the 2Q analysis. assert epoch.extra.get('epg_1q'), 'per-qubit 1Q EPGs must be retained' assert set(epoch.extra['epg_1q']) == set(range(8)) @@ -997,7 +997,7 @@ def test_notices_are_summarised_not_a_list_of_indices(): assert len(joined) < 400, f'notice too verbose ({len(joined)} chars)' -# ── v3.1 Part B: 1Q EPG subtraction wiring ───────────────────────── +# ── 1Q EPG subtraction wiring ────────────────────────────────────── def test_level2_now_includes_one_qubit_rb(): """The 2Q analysis cannot subtract what was never measured.""" @@ -1032,12 +1032,10 @@ def set_options(self, **kw): def test_epg_1_qubit_receives_result_objects_not_floats(): - """Live failure: 'float' object has no attribute 'device_components'. - - `rb_analysis._exclude_1q_error` reads `.device_components` off every + """`rb_analysis._exclude_1q_error` reads `.device_components` off every element of `epg_1_qubit`, so the 1Q RB ANALYSIS RESULTS must be forwarded, - not their values. Passing floats made every 2Q callback raise, and phase 2 - of the 20 Sept 13:08 run produced no EPG_cz at all. + not their values. Floats make every 2Q callback raise ('float' object has + no attribute 'device_components'), and phase 2 then yields no EPG_cz. """ analysis = _Analysis() experiment = SimpleNamespace(analysis=analysis) @@ -1098,7 +1096,7 @@ def test_a_rejected_option_is_a_notice_not_a_crash(): assert any('rejected epg_1_qubit' in n for n in notices), notices -# ── v3.1: analysis-callback failures must surface ────────────────── +# ── analysis-callback failures must surface ──────────────────────── def test_analysis_errors_are_collected_from_a_done_experiment(): """A DONE job whose every callback raised must not look successful.""" @@ -1137,7 +1135,7 @@ def test_summarise_analysis_errors_is_empty_when_clean(): assert bench.summarise_analysis_errors([]) is None -# ── v3.1 Part C: consistency and relative mode ───────────────────── +# ── consistency and relative mode ────────────────────────────────── def _epoch_with(measured_gate, reported_gate, mask): qp = {'readout_error': np.full(4, 0.01)} @@ -1212,10 +1210,8 @@ def test_relative_label_says_so(): def test_job_ids_are_recovered_per_phase_from_a_raw_dump(): - """The 20 Sept 13:08 run left no _jobs.json, but the raw dump has the ids. - - `_run_phased` did not call the job-id callback until v3.1, so the record - was never written — the dump is what makes that run recoverable. + """A run that left no _jobs.json is recoverable from its raw dump, which + carries the job ids of each phase. """ dump = {'experiments': [ {'job_ids': ['phase1-job'], 'children': [{'job_ids': ['phase1-job']}]}, @@ -1295,7 +1291,7 @@ def __exit__(self, *a): assert all('j-abc' in r[1] for r in recorded) -# ── v3.1: the reanalysis container must look like run()'s ────────── +# ── the reanalysis container must look like run()'s ──────────────── def test_container_is_built_through_initialize_experiment_data(): """Live failure: 'Unable to extract component child experiment data'. @@ -1424,7 +1420,7 @@ def child_data(self): assert any('private API moved' in n for n in notices), notices -# ── v3.3: the Calibration header must name a measured epoch ──────── +# ── the Calibration header must name a measured epoch ────────────── def test_describe_current_view_names_the_measured_epoch(): """A measured epoch replaces the arrays without changing time_mode, so @@ -1546,7 +1542,7 @@ def test_reanalysis_dumps_do_not_shadow_submissions(tmp_path, monkeypatch): assert record['_stamp'] == '20260920T130000' -# ── v3.5: implausible fits must never reach the 2Q analysis ──────── +# ── implausible fits must never reach the 2Q analysis ────────────── def test_an_implausible_1q_epg_is_not_forwarded_and_is_named(): """Live crash: a failed 1Q fit returned EPG 0.71, which made @@ -1615,7 +1611,7 @@ def test_extra_epg_1q_only_records_plausible_values(): epoch.notices -# ── v3.5: bounds on the other measured kinds ─────────────────────── +# ── bounds on the other measured kinds ───────────────────────────── def test_an_implausible_readout_error_falls_back_with_a_notice(): qp, gp = _reported() diff --git a/tests/test_benchmark_integration.py b/tests/test_benchmark_integration.py index b99eb6b..1d09a40 100644 --- a/tests/test_benchmark_integration.py +++ b/tests/test_benchmark_integration.py @@ -18,7 +18,6 @@ python -m pytest -m integration -q """ -import os import numpy as np import pytest @@ -131,10 +130,8 @@ def _run(circuits, **kwargs): def test_l1_plan_on_fake_backend_yields_measurements(monkeypatch, fake_backend, local_api): - """The check that would have caught the live failure. - - Before v3 this could not even be written: the runner had no seam for a - local sampler, and the plan it built for a real device was unsubmittable. + """The whole run against a local sampler, on a plan built for a real + device. """ targets = bench.Targets([0, 1, 2], []) coupling = _coupling_of(fake_backend) @@ -261,7 +258,7 @@ def test_t1_delays_are_within_the_backend_limits(fake_backend): f'device limit {max_delay}s') -# ── 6. Part F: reanalysis reproduces the direct run ───────────────── +# ── reanalysis reproduces the direct run ──────────────────────────── def _jobs_of(expdata_list): """The job OBJECTS a run produced, for reanalysis to consume.""" @@ -280,14 +277,13 @@ def _jobs_of(expdata_list): def test_reanalysis_from_jobs_reproduces_the_direct_run(monkeypatch, fake_backend, local_api): - """Part F, faithfully: rebuild from the JOBS, not from the run's data. - - The live failure was `AnalysisError: Unable to extract component child - experiment data` — reanalysis built a bare `ExperimentData` and added - jobs to it, so the composite children and component metadata that - `BaseExperiment.run()` allocates before submission were never created. - Reanalysing from the original `expdata` would have hidden that, because - that container already had them. This test therefore goes through + """Rebuild from the JOBS, not from the run's data. + + A bare `ExperimentData` with jobs added to it lacks the composite + children and component metadata that `BaseExperiment.run()` allocates + before submission (`AnalysisError: Unable to extract component child + experiment data`). Reanalysing from the original `expdata` would hide + that, because that container already has them. This test therefore goes through `reanalyze_from_jobs` with job objects and nothing else. Analysis is client-side, so this costs no execution: the same counts are diff --git a/tests/test_benchmark_ui.py b/tests/test_benchmark_ui.py index 735e102..3849bfb 100644 --- a/tests/test_benchmark_ui.py +++ b/tests/test_benchmark_ui.py @@ -447,7 +447,7 @@ def _fake_build(s2, is_secondary=False, return_widgets=False): assert handles_cell[0]().backend_name == 'ibm_k' -# ── v2: the QPU selector ──────────────────────────────────────────── +# ── the QPU selector ──────────────────────────────────────────────── def _qpu2_handles(n_q=6): """A stand-in for ui.inter_qpu's read-only QPU-2 accessor.""" @@ -533,7 +533,7 @@ def test_qpu2_targets_come_from_the_secondary_layout(monkeypatch, tmp_path): assert targets.qubits == [0, 1, 2], 'must read QPU 2 layouts_data' -# ── v2: whole-QPU messaging ───────────────────────────────────────── +# ── whole-QPU messaging ───────────────────────────────────────────── def test_whole_qpu_level1_is_advertised_as_the_cheap_refresh(monkeypatch, tmp_path): @@ -558,7 +558,7 @@ def test_whole_qpu_level3_always_demands_the_acknowledgement(monkeypatch, assert ctx.btn_bench_run.disabled is False -# ── v2.1: the quantum stack is imported on the MAIN thread ────────── +# ── the quantum stack is imported on the MAIN thread ──────────────── def test_runtime_is_preloaded_on_the_main_thread_before_the_worker( monkeypatch, tmp_path): @@ -722,14 +722,15 @@ def run(self, **kw): T1=_Exp, T2Hahn=_Exp) -# ── v3: no false success ──────────────────────────────────────────── +# ── no false success ──────────────────────────────────────────────── def test_empty_epoch_is_not_applied_and_not_called_measured(monkeypatch, tmp_path): - """The exact 18 Sept failure: the run produced nothing and said ✅. + """A run that produced nothing must not say ✅. - IBM rejected the job, the parser found no analysis results, and the panel - applied an epoch identical to the reported one labelled 'measured'. + When IBM rejects the job and the parser finds no analysis results, the + panel must not apply an epoch identical to the reported one labelled + 'measured'. """ monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) _have_qe(monkeypatch) @@ -807,7 +808,7 @@ def test_complete_measurement_reports_real_coverage(monkeypatch, tmp_path): assert '4/4 qubits' in status, status -# ── v3: a failed job says so ──────────────────────────────────────── +# ── a failed job says so ──────────────────────────────────────────── def test_job_failure_surfaces_ibms_message_and_job_ids(monkeypatch, tmp_path): monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) @@ -835,7 +836,7 @@ def _rejecting_runner(_plan): assert ctx.btn_bench_run.disabled is False -# ── v3: submittability gating ─────────────────────────────────────── +# ── submittability gating ─────────────────────────────────────────── def test_run_is_disabled_when_the_plan_cannot_fit_a_job(monkeypatch, tmp_path): @@ -859,7 +860,7 @@ def test_summary_states_circuits_shots_and_jobs(monkeypatch, tmp_path): assert 'circuits' in summary and 'shots' in summary and 'job' in summary -# ── v3.1: consistency check and relative mode in the panel ───────── +# ── consistency check and relative mode in the panel ─────────────── def _offset_runner(factor): """A runner whose readout comes back `factor` times the reported value.""" @@ -879,7 +880,7 @@ def _run(plan): def test_a_systematic_offset_triggers_relative_mode(monkeypatch, tmp_path): - """The 20 Sept signature: everything uniformly worse than reported.""" + """Everything uniformly worse than reported.""" monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) _have_qe(monkeypatch) state = _state() @@ -941,9 +942,9 @@ def test_analysis_callback_failures_are_reported_as_partial(monkeypatch, tmp_path): """A DONE job whose fits all raised must not read as a clean success. - On 20 Sept 13:08 both phases reported DONE, `errors()` was None, and the - panel showed six bland "no results returned" notices with no hint that - every two-qubit callback had thrown. + Both phases report DONE and `errors()` is None; the panel must say that + every two-qubit callback threw, not show bland "no results returned" + notices. """ monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) _have_qe(monkeypatch) @@ -976,7 +977,7 @@ def _runner_with_analysis_failure(plan): assert 'analysis failed' in ctx.lbl_lucj_notices.value -# ── v3.2: reanalysis must replay the ORIGINAL plan ───────────────── +# ── reanalysis must replay the ORIGINAL plan ─────────────────────── def _record_for(plan, when=1_700_000_000.0, jobs=None): """The _jobs.json payload a submission of `plan` would have written.""" @@ -1124,7 +1125,7 @@ def test_plan_from_record_round_trips(): assert a.params.get('pairs') == b.params.get('pairs') -# ── v3.3: the reanalysis must stay phase-aware and self-check ────── +# ── the reanalysis must stay phase-aware and self-check ──────────── def test_reanalysis_passes_job_ids_grouped_by_phase(monkeypatch, tmp_path): """Flattening the phases lost the 1Q subtraction silently. @@ -1205,7 +1206,7 @@ def _fake_reanalyze(plan, job_ids, backend, service=None): assert 'relative' in state.calibration_data_label -# ── v3.4: the UI path must equal the direct path ─────────────────── +# ── the UI path must equal the direct path ───────────────────────── class _SpyAnalysis: """Records what the 2Q analysis was given.""" @@ -1367,7 +1368,7 @@ def _rean(plan, job_ids, backend, service=None): ui_epoch.notices -# ── v3.6: the calibration check, wired ───────────────────────────── +# ── the calibration check, wired ─────────────────────────────────── def _calcheck_state(n_q=16): state = _state(n_q) @@ -1582,7 +1583,7 @@ def _build_real_ui(monkeypatch): return builder, st -# ── v3.7: the result copy a user can actually read ───────────────── +# ── the result copy a user can actually read ─────────────────────── def _run_with_factors(monkeypatch, tmp_path, factors, n_q=8): """Drive a run whose measured/reported ratio is `factors` per property.""" @@ -1618,7 +1619,7 @@ def test_copy_all_in_band(monkeypatch, tmp_path): def test_copy_names_in_band_and_rescaled_properties(): - """The exact parameterised sentence, on the real 20 Sept shape.""" + """The exact parameterised sentence, on a real live-run shape.""" from iqmapper.ui.benchmark_panel import setup_benchmark_panel ctx = _ctx() api = setup_benchmark_panel(ctx) diff --git a/tests/test_calibration_epoch.py b/tests/test_calibration_epoch.py index 360a43b..7dd550d 100644 --- a/tests/test_calibration_epoch.py +++ b/tests/test_calibration_epoch.py @@ -74,7 +74,7 @@ def _build(monkeypatch, *, snapshot, ancilla=0): return b, state, captured -# ── t1: the search receives the snapshot arrays, not the live sentinel ────── +# ── the search receives the snapshot arrays, not the live sentinel ────────── def test_search_uses_snapshot_not_live(monkeypatch): b, state, captured = _build(monkeypatch, snapshot=True) @@ -89,7 +89,7 @@ def test_search_uses_snapshot_not_live(monkeypatch): assert pr.gate_error('cz', (3, 2)) == _SNAP_CZ[2] -# ── t2: search and C1 read the SAME values (epoch consistency) ────────────── +# ── search and C1 read the SAME values (epoch consistency) ────────────────── def test_search_and_c1_share_epoch(monkeypatch): b, state, captured = _build(monkeypatch, snapshot=True) @@ -106,7 +106,7 @@ def test_search_and_c1_share_epoch(monkeypatch): assert pr.t2(2) * 1e6 == pytest.approx(_SNAP_T2[2]) -# ── t3: live mode unchanged — the sentinel flows ──────────────────────────── +# ── live mode unchanged — the sentinel flows ──────────────────────────────── def test_live_mode_passes_initial_props(monkeypatch): b, state, captured = _build(monkeypatch, snapshot=False) # time_mode='live' @@ -116,7 +116,7 @@ def test_live_mode_passes_initial_props(monkeypatch): assert pr.readout_error(3) == 0.99 # the sentinel -# ── t4: the "scored on" note renders only for a non-live snapshot ─────────── +# ── the "scored on" note renders only for a non-live snapshot ─────────────── def test_status_note_only_for_snapshot(monkeypatch): b, state, captured = _build(monkeypatch, snapshot=True) @@ -128,7 +128,7 @@ def test_status_note_only_for_snapshot(monkeypatch): assert 'scored on' not in b2.lbl_lucj_status.value -# ── t5: the Auto sweep path also pre-ranks on the snapshot, not live ───────── +# ── the Auto sweep path also pre-ranks on the snapshot, not live ───────────── def test_sweep_uses_snapshot_not_live(monkeypatch): """Auto (-1) routes to the stratified sweep. It must pre-rank on the loaded diff --git a/tests/test_combined_sweep.py b/tests/test_combined_sweep.py index bcd8ada..a8b81a2 100644 --- a/tests/test_combined_sweep.py +++ b/tests/test_combined_sweep.py @@ -5,7 +5,6 @@ every entry says where it came from, and with the guided half off the result is the exhaustive sweep's own. """ -import numpy as np import pytest import rustworkx diff --git a/tests/test_copy_lengths.py b/tests/test_copy_lengths.py index bebc487..cf9f987 100644 --- a/tests/test_copy_lengths.py +++ b/tests/test_copy_lengths.py @@ -21,7 +21,6 @@ import re import numpy as np -import pytest TAG = re.compile(r'<[^>]+>') diff --git a/tests/test_engine_dedupe_plans.py b/tests/test_engine_dedupe_plans.py index f91989d..53382d7 100644 --- a/tests/test_engine_dedupe_plans.py +++ b/tests/test_engine_dedupe_plans.py @@ -36,7 +36,7 @@ def _duplicates(result): for k, es in result['strata'].items()} -# ── B1: no repeated layout in a stratum ───────────────────────────── +# ── no repeated layout in a stratum ───────────────────────────────── def _fez(): backend = fake_provider.FakeFez() @@ -92,7 +92,7 @@ def test_distinct_layouts_keeps_the_first_copy(): assert gs._distinct_layouts([a, a_again, b]) == [a, b] -# ── B2: the joint planner's complete plans ────────────────────────── +# ── the joint planner's complete plans ────────────────────────────── PLAN_KEYS = {'chosen', 'total', 'circuits', 'total_product', 'total_lqs_circuit', 'placed_qubits', 'buffer_qubits_used', diff --git a/tests/test_error_tab_backend_switch.py b/tests/test_error_tab_backend_switch.py index 51000d0..3f51238 100644 --- a/tests/test_error_tab_backend_switch.py +++ b/tests/test_error_tab_backend_switch.py @@ -2,14 +2,13 @@ The header text comes from time_panel.describe_current_view(state) but only re-renders when the panel's own observers fire — a backend switch never touches -them. The builder now KEEPS the time-panel API handle and the switch wiring +them. The builder keeps the time-panel API handle and the switch wiring calls api.rebuild() (best-effort, never breaking a switch) so the header re-renders for the new backend. """ import types from types import SimpleNamespace -import pytest # ── stubs shared by the switch-wiring tests ───────────────────────────────── diff --git a/tests/test_export_layout_io.py b/tests/test_export_layout_io.py index 28e67c1..964eedd 100644 --- a/tests/test_export_layout_io.py +++ b/tests/test_export_layout_io.py @@ -65,8 +65,8 @@ def test_import_json_size_cap(make_state, make_slot, monkeypatch): # malformed shape falls back to the documented midpoint behaviour. def test_partition_negative_lengths_summing_correctly_falls_back(make_state, make_slot): - # a=-1, b=4, o=0 sums to 3 == len(q_list): the old code accepted it - # and produced a negative-slice split with no error. Must midpoint. + # a=-1, b=4, o=0 sums to 3 == len(q_list) but is not a valid split + # (a negative slice). Must midpoint. st = _slots(make_state, make_slot) apply_layout_to_circuit(st, 0, [0, 1, 2], "lucj", partition={"alpha_len": -1, "beta_len": 4, "other_len": 0}) diff --git a/tests/test_failures_logged.py b/tests/test_failures_logged.py new file mode 100644 index 0000000..d200df9 --- /dev/null +++ b/tests/test_failures_logged.py @@ -0,0 +1,61 @@ +"""Failures that do not stop the action still leave a log line. + +A QPU-1 label hook that raises during a backend switch is logged at debug +with its traceback. A scan backend whose properties cannot be loaded for the +circuit-level scores is named in a warning, which the scan shows as a notice. +""" +import logging + +from test_error_tab_backend_switch import _fresh_state, _switch_ctx +from test_scan_ui import _build, _labels, _StubProps, _sweep, _walk + + +def test_a_failing_qpu1_label_hook_is_logged_and_the_switch_completes( + monkeypatch, caplog): + from iqmapper.ui.backend_switch import setup_backend_switch + monkeypatch.setattr("iqmapper.connection._check_properties", + lambda b, n: (object(), None)) + monkeypatch.setattr("iqmapper.constants.resolve_coords", + lambda b: ([], 'Heron r1')) + + def _boom(): + raise RuntimeError('label boom') + state = _fresh_state() + ctx = _switch_ctx(state, load_device_graph=lambda force=False: None, + refresh_time_panel=None) + ctx.refresh_qpu1_label = [_boom] + with caplog.at_level(logging.DEBUG, logger='iqmapper.ui.backend_switch'): + setup_backend_switch(ctx)({'new': 'ibm_new'}) + + assert state.active_backend_name == 'ibm_new' + failed = [r for r in caplog.records + if r.getMessage() == 'QPU-1 toggle label refresh failed'] + assert failed and failed[0].exc_info[1].args == ('label boom',) + + +def test_a_scan_backend_without_properties_for_scoring_is_named(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}, + {'name': 'ibm_b', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _sweep(0.6, 0.5)) + calls = {'ibm_a': 0} + + def get_props(state): + def gp(backend): + if backend.name == 'ibm_a': + calls['ibm_a'] += 1 + if calls['ibm_a'] > 1: # the search got them; scoring not + raise RuntimeError('props gone') + return _StubProps(0.6, 'live · 09:30') + return gp + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", get_props) + + b.btn_scan_qpus.click() + + assert 'ibm_a' in ' '.join(_labels(b)) # still listed + notices = ' '.join(getattr(w, 'value', '') or '' + for w in _walk(b.scan_results_box)) + assert 'circuit scores unavailable for ibm_a' in notices + assert 'props gone' in notices diff --git a/tests/test_floor_batch_ui.py b/tests/test_floor_batch_ui.py index a30cfd8..f63ff5b 100644 --- a/tests/test_floor_batch_ui.py +++ b/tests/test_floor_batch_ui.py @@ -150,31 +150,19 @@ def test_scan_floor_per_backend(monkeypatch): assert not (seen['ibm_b'].get('exclude_qubits') or set()) -# ── legacy single/multi buttons untouched by the floor ─────────────── +# ── the single-count search is untouched by the floor ──────────────── -def test_legacy_paths_untouched(monkeypatch): +def test_single_count_search_untouched(monkeypatch): b, state = _build(monkeypatch) single = [] monkeypatch.setattr("iqmapper.auto_lucj.get_all_zigzag_layouts", lambda **k: single.append(k) or ([{'rank': 1, 'score': 0.1, 'alpha': [0, 1], 'beta': [2, 3]}], 1)) - multi = [] - monkeypatch.setattr("iqmapper.auto_lucj.get_multi_circuit_layouts", - lambda **k: multi.append(k) or [ - {'circuit_idx': 0, 'norb': 8, 'num_bridges': 2, - 'all_candidates': [{'layout': [0, 1, 2, 3], - 'alpha': [0, 1], 'beta': [2, 3], - 'score': 0.03, 'rank': 1, - 'layout_full': [0, 1, 2, 3, 4]}]}]) - b.lucj_ancilla_dd.value = 2 # legacy single (not sweep) + b.lucj_ancilla_dd.value = 2 # exact count (not sweep) b.btn_lucj_run.click() - b.lucj_multi_norbs.value = '8' - b.btn_lucj_multi.click() # legacy multi - assert len(single) == 1 # legacy engines called… - assert len(multi) == 1 - # …and neither legacy engine accepts/forwards a floor exclude set. + assert len(single) == 1 + # The single-count engine takes no floor exclude set. assert 'exclude_qubits' not in single[0] - assert 'exclude_qubits' not in multi[0] # ── batch scan ────────────────────────────────────────────────────────── @@ -269,7 +257,7 @@ def test_batch_selector_handoff_payload(monkeypatch): b.lucj_multi_norbs.value = '8, 8' b.btn_scan_batch.click() - from ipywidgets import Dropdown, HBox + from ipywidgets import HBox kids = list(b.scan_batch_box.children) btn = next(c for w in kids for c in (w.children if isinstance(w, HBox) else [w]) if isinstance(c, Button)) diff --git a/tests/test_html_safe.py b/tests/test_html_safe.py index d50878c..5094978 100644 --- a/tests/test_html_safe.py +++ b/tests/test_html_safe.py @@ -1,9 +1,8 @@ """ tests/test_html_safe.py — Unit tests for iqmapper.html_safe.esc(). -Closes the audit gap (AUDIT_REPORT § html_safe.py): the escape helper -was previously untested even though it's the single defence against -XSS via user-influenced strings in ipywidgets.HTML widgets (loaded +The escape helper is the single defence against XSS via +user-influenced strings in ipywidgets.HTML widgets (loaded session JSON, calibration label strings, exception messages, ...). """ @@ -14,7 +13,7 @@ class TestEscBasic: """Core escape behaviour: every HTML-significant character is replaced.""" def test_script_tag(self): - # The headline case the audit report calls out explicitly. + # The headline case. assert esc("