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 32d5f99..4bd20ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,126 @@ 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] + +## [0.1.0] - 2026-11-23 + +### Added +- Opt-in real-time benchmarking (`iqmapper.benchmark`, extra + `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 + 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. The experiment plan is composite + (one `ParallelExperiment` per kind, edge-coloured layers for two-qubit RB), + 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 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 (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: 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. 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`). 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. +- 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. 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 + 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 (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`, + 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 + 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 on the reference page + (`docs/reference.md`). + +### Changed +- Documentation reorganised: short README, tutorial, and a reference page + under docs/. +- 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 + 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. +- 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 First public-ready release. diff --git a/CITATION.cff b/CITATION.cff index 1ca6ced..47f7858 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -1,11 +1,17 @@ cff-version: 1.2.0 -message: "If you use I-QMapper in your research, please cite the I-QMapper paper (see preferred-citation)." +message: "If you use I-QMapper, please cite the paper below (preferred-citation)." title: "I-QMapper" +abstract: >- + Interactive, calibration-aware visualization and layout selection for + quantum-circuit ansaetze (LUCJ and general) on superconducting quantum + processors, driven by the device's reported calibration data. authors: - family-names: "Bazayeva" given-names: "Milana" -version: 0.0.5 +version: 0.1.0 +date-released: 2026-11-23 license: Apache-2.0 +repository-code: "https://github.com/MIQuLab/i-qmapper" preferred-citation: type: article title: "I-QMapper: Error-Aware Layout Optimization and Device Diagnostics for NISQ Hardware" @@ -13,92 +19,8 @@ preferred-citation: - family-names: "Bazayeva" given-names: "Milana" - family-names: "Merz" - given-names: "Kenneth" + given-names: "Kenneth M." + name-suffix: "Jr." year: 2026 doi: "10.48550/arXiv.2606.27508" url: "https://arxiv.org/abs/2606.27508" -abstract: >- - Interactive, noise-aware visualization and layout selection for - quantum-circuit ansaetze (LUCJ and general) on superconducting QPU - topologies, driven by real device calibration data. -references: - - type: article - title: >- - Bridging physical intuition and hardware efficiency for correlated - electronic states: the local unitary cluster Jastrow ansatz for - electronic structure - authors: - - family-names: "Motta" - given-names: "Mario" - - family-names: "Sung" - given-names: "Kevin J." - - family-names: "Whaley" - given-names: "K. Birgitta" - - family-names: "Head-Gordon" - given-names: "Martin" - - family-names: "Shee" - given-names: "James" - journal: "Chemical Science" - volume: 14 - start: 11213 - end: 11227 - year: 2023 - doi: "10.1039/D3SC02516K" - - type: article - title: "Suppressing quantum circuit errors due to system variability" - authors: - - family-names: "Nation" - given-names: "Paul D." - - family-names: "Treinish" - given-names: "Matthew" - journal: "PRX Quantum" - volume: 4 - start: 010327 - year: 2023 - doi: "10.1103/PRXQuantum.4.010327" - - type: article - title: "ffsim: Faster simulation of fermionic quantum circuits" - authors: - - family-names: "Sung" - given-names: "Kevin J." - - family-names: "Choi" - given-names: "Inho" - - family-names: "Amico" - given-names: "Mirko" - - family-names: "Andrews" - given-names: "Bartholomew" - - family-names: "Ayantuna" - given-names: "Esra" - - family-names: "Kawashima" - given-names: "Yukio" - - family-names: "Lin" - given-names: "Wan-Hsuan" - - family-names: "Omanovic" - given-names: "David" - - family-names: "Piccinelli" - given-names: "Samuele" - - family-names: "Robledo Moreno" - given-names: "Javier" - - family-names: "Ash Saki" - given-names: "Abdullah" - - family-names: "Shee" - given-names: "James" - - family-names: "Shin" - given-names: "Soyoung" - - family-names: "Tran" - given-names: "Minh C." - - family-names: "Ueda" - given-names: "Kento" - - family-names: "Zhang" - given-names: "Haimeng" - - family-names: "Motta" - given-names: "Mario" - year: 2026 - doi: "10.48550/arXiv.2605.03123" - url: "https://arxiv.org/abs/2605.03123" - - type: software - title: "ffsim" - repository-code: "https://github.com/qiskit-community/ffsim" - - type: software - title: "mapomatic" - repository-code: "https://github.com/qiskit-community/mapomatic" diff --git a/CODE_OVERVIEW.md b/CODE_OVERVIEW.md index 2909b3a..77bbf8c 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,15 +43,38 @@ 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. | | `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. | +## 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` | 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. | +| `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`). | + ## `export/` — analysis & I/O | Module | Role | @@ -60,6 +85,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 +95,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 (`_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`). | | `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/` — 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 d4bf104..3da3931 100644 --- a/README.md +++ b/README.md @@ -1,256 +1,127 @@ # I-QMapper -**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.** +Interactive, calibration-aware qubit layout selection for IBM Quantum processors. -[![tests](https://github.com/mbazayeva/i-qmapper/actions/workflows/tests.yml/badge.svg)](https://github.com/mbazayeva/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) +[![tests](https://github.com/MIQuLab/i-qmapper/actions/workflows/tests.yml/badge.svg)](https://github.com/MIQuLab/i-qmapper/actions/workflows/tests.yml) +[![PyPI](https://img.shields.io/pypi/v/i-qmapper.svg)](https://pypi.org/project/i-qmapper/) [![arXiv](https://img.shields.io/badge/arXiv-2606.27508-b31b1b.svg)](https://arxiv.org/abs/2606.27508) -I-QMapper is presented in the paper *I-QMapper: Error-Aware Layout Optimization and -Device Diagnostics for NISQ Hardware* (Bazayeva & Merz, -[arXiv:2606.27508](https://arxiv.org/abs/2606.27508)). - -![I-QMapper — auto-placed LUCJ layout with role legend on an IBM Heron device](docs/img/hero.png) - -**Contents:** -[Why](#why) · -[Features](#features) · -[Requirements](#requirements) · -[Installation](#installation) · -[Set up your IBM Quantum account](#set-up-your-ibm-quantum-account) · -[Quickstart](#quickstart) · -[Tutorial](TUTORIAL.md) · -[How it works](#how-it-works) · -[Extending to other vendors](#extending-to-other-vendors) · -[Project layout](#project-layout) · -[Limitations](#limitations--caveats) · -[License & Citing](#license-credits--citing) - ---- - -## Why - -On NISQ hardware, *where* you place a circuit matters as much as *what* you run: -gate errors, readout errors, and coherence times vary across the chip and **drift -over time**. Today you either eyeball calibration tables by hand or trust an -automated layout pipeline you can't see into. I-QMapper closes that gap: an -interactive Jupyter tool where the device, its calibration data, its history, and -your layout live in one view — so every placement decision is **visible, -inspectable, and reproducible**. - -## Features - -- 🗺️ **Live error heatmaps** on the real device topology — readout, CZ error, - coherence, and more, straight from current calibration data. -- 🕰️ **Time travel** — intraday snapshots, multi-day history, and **delta views** - that show what drifted since yesterday (or since any reference you pick). -- 📈 **Stability Check** — don't just pick the best qubits *today*; see which - 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. -- 🏆 **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 - publication-ready PNGs, time-lapse GIF/MP4 of calibration - history, full session save/restore, and generated Qiskit code for your chosen - layout. -- 🔒 **Local-first** — your IBM Quantum credentials never leave your machine; the - tool talks to IBM through your own locally saved `QiskitRuntimeService` account. - -## Requirements - -- Python **3.10+** -- 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)) -- JupyterLab or Jupyter Notebook +I-QMapper is a Jupyter application that displays a quantum processor's calibration +data on its physical topology, tracks how that data changes over time, and places +circuits — in particular the LUCJ ansatz used in quantum chemistry — on the qubits +where they are expected to run best. Every placement decision is visible and +reproducible: the device, its calibration history and the candidate layouts are +shown in one view, and each candidate is ranked by an explicit quality score. ## Installation -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]" ``` -### From source (development) +| Extra | Adds | Install | +|---|---|---| +| `png` | PNG export of the map (kaleido) | `pip install "i-qmapper[png]"` | +| `timelapse` | GIF/MP4 export of calibration history | `pip install "i-qmapper[timelapse]"` | +| `benchmark` | On-device benchmarking (qiskit-experiments) | `pip install "i-qmapper[benchmark]"` | -```bash -git clone https://github.com/MIQuLab/i-qmapper -cd i-qmapper -pip install -e ".[dev]" -pytest -q -``` +Extras can be combined, e.g. `"i-qmapper[png,benchmark]"`. -## Set up your IBM Quantum account - -I-QMapper uses the credentials you save locally with `qiskit-ibm-runtime` — -it never asks for, stores, or transmits your token itself. One-time setup: +Requirements: Python 3.10 or later, JupyterLab or Jupyter Notebook, and an +[IBM Quantum](https://quantum.ibm.com) account whose credential is saved locally +with `qiskit-ibm-runtime`: ```python from qiskit_ibm_runtime import QiskitRuntimeService - -QiskitRuntimeService.save_account( - channel='ibm_quantum_platform', - token='YOUR_TOKEN', - instance='YOUR_CRN', - set_as_default=True, # make this your default credential - overwrite=True, -) +QiskitRuntimeService.save_account(channel="ibm_quantum_platform", + token="YOUR_TOKEN", instance="YOUR_CRN", + set_as_default=True, overwrite=True) ``` -Find your token and instance CRN on the -[IBM Quantum Platform](https://quantum.ibm.com) dashboard. +I-QMapper reads this credential through `qiskit-ibm-runtime`; it does not store or +transmit the token itself. Several credentials can be saved under different +`name=` values and selected from the application. -**Multiple accounts / instances.** You can save one credential as your -**default** and give the others a `name=` — for example a premium instance as -the default, and another instance (e.g. a local QPU) you switch to on demand: - -```python -# premium instance — saved as the default (used when no name is selected) -QiskitRuntimeService.save_account( - channel='ibm_quantum_platform', - token='YOUR_TOKEN', - instance='PREMIUM_CRN', - set_as_default=True, - overwrite=True, -) - -# another instance (e.g. a local QPU) — saved under a name, picked explicitly -QiskitRuntimeService.save_account( - channel='ibm_quantum_platform', - token='YOUR_TOKEN', - instance='OTHER_CRN', - name='my_backend', - overwrite=True, -) -``` - -In I-QMapper's **account selector**, the default credential is used unless -you pick a named one — switch between them anytime without re-entering -anything. - -## Quickstart - -In a notebook cell: +## Quick start ```python from iqmapper import run run() ``` -This opens the sidebar UI. Pick **IBM Quantum**, choose your saved account, pick -a backend, select the ansatz mode, and click **Connect & Launch**. From there -you can place qubits by hand, auto-place a LUCJ layout, compare candidates by -score, inspect calibration history, and export everything you see. - -**New here? Follow the step-by-step [Tutorial](TUTORIAL.md).** - -| ![Live error heatmap](docs/img/heatmap.png) | ![Delta view — calibration drift](docs/img/delta-view.png) | -|:--:|:--:| -| *Live error heatmap* | *Delta view: what drifted since the reference* | -| ![Stability check](docs/img/stability-report.png) | ![The app](docs/img/app-view.png) | -| *Stability check over a 14-day window* | *The full editor: layout, scoring, controls* | +1. In the connection panel, **Load Account** (leave the account name blank for + the default credential), select the backend, then **Connect & Launch**. +2. The map shows the processor with the selected calibration property as a + colour scale; hover a qubit or coupler for its values. +3. Choose the LUCJ mode and the number of spatial orbitals, then **Generate LUCJ + Layout**. The candidates are listed with their quality score (LQS) and drawn + on the map; the Estimated Layout-Quality panel gives the score of the + current layout. +4. Use the calibration section to view earlier calibrations and the change + since a chosen reference, and the stability check to see which qubits have + remained reliable over the last 7, 14 or 30 days. +5. Export the layout as JSON, Qiskit code, PNG, or save the whole session. -## How it works +A step-by-step walkthrough is in the [tutorial](https://github.com/MIQuLab/i-qmapper/blob/main/TUTORIAL.md). -
-Architecture in one paragraph — click to expand -
+## Capabilities -The Python kernel is the auth and data layer: calibration data is fetched through -your locally saved IBM account, cached per-user on disk, and rendered with Plotly -inside ipywidgets panels. Every analysis (scoring, stability, delta) runs on the -cached snapshots — so browsing history and comparing layouts costs no QPU time -and no extra API calls. For a module-by-module tour, see -[CODE_OVERVIEW.md](CODE_OVERVIEW.md). - -**Where your data lives:** - -| What | Where | +| | | |---|---| -| Calibration cache | macOS `~/Library/Caches/iqmapper` · Linux `~/.cache/iqmapper` (or `$XDG_CACHE_HOME/iqmapper`) · Windows `%LOCALAPPDATA%\iqmapper\Cache` | -| Cache override | Set the `IQMAPPER_CACHE_DIR` environment variable to relocate it | -| Sessions & style presets | `.iqmapper_sessions/` inside the directory your notebook runs from | - -The cache is safe to delete at any time — the tool recreates it and refetches -on demand. Your IBM credentials are **not** stored by I-QMapper at all; they -live in your own `qiskit-ibm-runtime` account store. - -
- -## Extending to other vendors - -
-How the vendor dispatch works — click to expand -
- -Backend loading goes through an explicit dispatch table -(`_VENDOR_LOADERS` in `iqmapper/connection.py`). Adding a provider means -implementing one loader with the same signature and registering it — the UI, -scoring, and visualization layers are vendor-agnostic. IBM Quantum is the -provider shipped today. - -
- -## Project layout +| **Calibration map** | Readout error, two-qubit gate error, T1, T2 and the other reported properties on the device topology, for the current calibration or any cached earlier one. | +| **History and drift** | Intraday snapshots, multi-day history, and difference views against a chosen reference calibration. | +| **Stability check** | Per-qubit reliability across a 7-, 14- or 30-day window, used to exclude qubits that score well today but drift. | +| **Layout quality score (LQS)** | A product-form estimate built from readout and two-qubit gate errors of the qubits and couplers a circuit uses. Used to rank candidates before any QPU time is spent. | +| **Automatic LUCJ placement** | An exhaustive subgraph search and a calibration-guided search run together; for every ancilla count the best candidates of both are kept. | +| **Several circuits on one processor** | Joint placement of multiple circuits with a configurable buffer between them; complete plans are ranked by their combined score. | +| **Several processors** | The same search on every accessible backend, ranked, with a one-step transfer of a layout to a second processor. | +| **On-device benchmarking** (optional) | Re-measurement of readout, gate errors and coherence on the chosen qubits, fed back into the map and the ranking as a separate calibration epoch. Never automatic; cost shown before the run. | +| **Import and export** | Layouts from JSON, `.npy` or QPY; export to PNG, GIF/MP4, JSON, Qiskit code and full session files. | + +## Repository layout + +| Path | Contents | +|---|---| +| `iqmapper/` | The application: connection and calibration cache, device map, layout search engines, scoring, benchmarking, session state | +| `iqmapper/ui/` | The Jupyter interface (ipywidgets panels) | +| `iqmapper/export/` | Layout quality score, layout import/export, code generation, PNG export | +| `tests/` | Offline test suite; no IBM account required | +| `docs/` | Reference page and images | +| `TUTORIAL.md` | Step-by-step walkthrough | +| `CHANGELOG.md` | Release history | -
-Repository structure — click to expand -
+A module-by-module description is in [CODE_OVERVIEW.md](https://github.com/MIQuLab/i-qmapper/blob/main/CODE_OVERVIEW.md). -``` -iqmapper/ -├── connection.py # account loading, vendor dispatch, backend selection -├── data.py # calibration fetch + per-user cache -├── plot.py # device graph & heatmap rendering -├── auto_lucj.py # LUCJ auto-placement + layout error scoring -├── 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 -``` +## Supported processors -For a guided tour of the modules and data flow, see -[CODE_OVERVIEW.md](CODE_OVERVIEW.md). +The device map covers the 156-qubit IBM Heron (r2, r3) and the 120-qubit IBM +Nighthawk processors. Other backends are listed in the multi-processor scans as +not supported and are not searched. -
+## Documentation -## Limitations & caveats +- [Tutorial](https://github.com/MIQuLab/i-qmapper/blob/main/TUTORIAL.md) — from launch to an exported layout. +- [Reference](https://github.com/MIQuLab/i-qmapper/blob/main/docs/reference.md) — settings, search options, messages, the quality score, and on-device benchmarking. +- [Code overview](https://github.com/MIQuLab/i-qmapper/blob/main/CODE_OVERVIEW.md) — architecture and modules. +- [Changelog](https://github.com/MIQuLab/i-qmapper/blob/main/CHANGELOG.md) -
-What this tool is not — click to expand -
+## Citing -- Calibration data is as fresh as IBM's calibration cycle; the tool shows you - *reported* device quality, which is a strong prior — not a guarantee — of run - 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. +If you use I-QMapper in your research, please cite: -
+> M. Bazayeva, K. M. Merz Jr., *I-QMapper: Error-Aware Layout Optimization and +> Device Diagnostics for NISQ Hardware*, arXiv:2606.27508 (2026). +> https://arxiv.org/abs/2606.27508 -## License, Credits & Citing +### Works used -I-QMapper is released under the [Apache License 2.0](LICENSE) (see also -[NOTICE](NOTICE)). +1. M. Motta, K. J. Sung, K. B. Whaley, M. Head-Gordon, J. Shee, *Chem. Sci.* + **14**, 11213 (2023). The LUCJ ansatz. +2. P. D. Nation, M. Treinish, *PRX Quantum* **4**, 010327 (2023). Cost function + followed by the layout quality score (mapomatic). +3. K. J. Sung *et al.*, arXiv:2605.03123 (2026). The LUCJ layout scorer was + adapted from code now part of [ffsim](https://github.com/qiskit-community/ffsim). -Parts of this project build on IBM open-source work: the auto-LUCJ layout scorer -was adapted from IBM code now incorporated in -[ffsim](https://github.com/qiskit-community/ffsim) (Sung *et al.*, -[arXiv:2605.03123](https://arxiv.org/abs/2605.03123)), and the layout-quality -estimator implements a cost function in the style of -[mapomatic](https://github.com/qiskit-community/mapomatic) -(Nation & Treinish, *PRX Quantum* **4**, 010327, 2023). The LUCJ ansatz is due to -Motta *et al.*, *Chem. Sci.* **14**, 11213–11227 (2023), -[doi:10.1039/D3SC02516K](https://doi.org/10.1039/D3SC02516K). +## License -If you use I-QMapper in your research, please cite the I-QMapper paper -([arXiv:2606.27508](https://arxiv.org/abs/2606.27508)) — see -[CITATION.cff](CITATION.cff). +Apache License 2.0; see [LICENSE](https://github.com/MIQuLab/i-qmapper/blob/main/LICENSE) and [NOTICE](https://github.com/MIQuLab/i-qmapper/blob/main/NOTICE). diff --git a/TUTORIAL.md b/TUTORIAL.md index 8fa9f27..fb4fcfb 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -1,23 +1,22 @@ -# I-QMapper — Tutorial +# Tutorial -A step-by-step walkthrough from zero to an exported, error-aware layout. -Prerequisites: [Installation](README.md#installation) and -[account setup](README.md#set-up-your-ibm-quantum-account) from the README. +A walkthrough from launch to an exported, calibration-aware layout. It assumes +the package is installed and an IBM Quantum credential is saved locally (see +[Installation](README.md#installation)). -**Steps:** -[1. Launch & connect](#1-launch--connect) · +Contents: +[1. Launch and connect](#1-launch-and-connect) · [2. Read the map](#2-read-the-map) · [3. Place a layout](#3-place-a-layout) · -[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) +[4. Score and compare](#4-score-and-compare) · +[5. Calibration history](#5-calibration-history) · +[6. Stability check](#6-stability-check) · +[7. Intra- and inter-QPU parallelisation](#7-intra--and-inter-qpu-parallelisation) · +[8. Benchmark the device](#8-benchmark-the-device) · +[9. Import, export and sessions](#9-import-export-and-sessions) · +[10. Where your data lives](#10-where-your-data-lives) ---- - -## 1. Launch & connect +## 1. Launch and connect In a notebook cell: @@ -26,132 +25,178 @@ from iqmapper import run run() ``` -The sidebar opens. In order: +The connection panel opens: -1. **Vendor** — pick *IBM Quantum* (the provider shipped today). -2. **Account** — the dropdown lists every credential you saved with - `QiskitRuntimeService.save_account(..., name=...)`. This is how you switch - between, say, a premium instance and an open one without re-entering - anything. -3. **Load account** — the tool connects through your local credential and - lists the backends your instance can access. -4. **Backend** — pick a device, choose the **ansatz mode** (general-purpose - or LUCJ), and click **Connect & Launch**. +1. **Vendor** — IBM Quantum (the provider shipped today). +2. **Account name** — blank uses the default credential; a name selects a + credential saved with `QiskitRuntimeService.save_account(name=...)`. +3. **Load Account** — connects through the credential and lists the backends + the instance can access. It runs once by itself with the default + credential when the panel opens. +4. **Backend** — select a device and the **Ansatz** (LUCJ / Chemistry or + General Ansatz), then **Connect & Launch**. -The device map appears, and a 14-day calibration history starts loading in the -background — you'll see a ⏳ note in the Stability section until it finishes -(everything else is usable immediately). +The device map and the sidebar appear; section **1. Hardware** switches to +another backend later. A 14-day calibration history loads in the background; +the Stability section shows a note until it is complete, and everything else is +available immediately. -![Connect: vendor, account, backend, ansatz](docs/img/sidebar-connect.png) +

Hardware section: vendor, account, backend and ansatz mode

## 2. Read the map -The main view is the device topology with a live error heatmap: +The main view is the device topology coloured by a calibration property. -- **Property selector** — switch what the colors mean: readout error, CZ/two- - qubit gate error, T1/T2, gate length, and more. Qubit colors and edge colors - are set independently. -- **Hover** any qubit or coupling to see its exact calibrated values. -- **Colorbars** at the bottom show the scale, with the device **median** - marked — an instant sense of "is this qubit better or worse than typical". -- Light = good, dark = high error (with the default palette; you can restyle - everything from the color picker). +- **Property selectors** — one for qubits, one for couplers: readout error, + two-qubit gate error, T1, T2, gate length and the other properties the + backend reports. Only properties with values on the connected device are + listed. +- **Hover** a qubit or coupler for its calibrated values. A missing value reads + "no data". +- **Colour bars** show the scale with the device median marked. +- With the default palette, deep blue means low error and near-white means + high error; the palette can be changed in **3. Colors**. -![Hover a qubit to see its calibrated values](docs/img/heatmap-hover.png) +

Calibration map with a qubit's values shown on hover

## 3. Place a layout -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. +- **By hand** — click qubits on the map to add them to, or remove them from, + the current circuit. In LUCJ mode each qubit takes a role (α chain, β chain + or ancilla bridge), shown in a distinct colour. +- **Automatically (LUCJ mode)** — set the number of spatial orbitals and + select **Generate LUCJ Layout**. The search tries every ancilla count, + scores each candidate on the current calibration, places the best one and + lists the others in the **Layout** dropdown, ranked by LQS. Each entry ends + with its origin: `E` (exhaustive search), `G` (guided search) or `E+G` (both). -Multiple circuits can coexist, each with its own color; undo/redo covers every -placement action. +Several circuits can be placed at once, each in its own colour; undo and redo +cover every placement action. -![Auto-placed LUCJ layout with α/β/ancilla roles](docs/img/hero.png) +

LUCJ layout placed automatically, with chain and ancilla roles

-## 4. Score & compare +## 4. Score and compare -Open the **Analysis** panel: +- **Estimated Layout-Quality** (sidebar) gives the layout quality score (LQS) of + each placed circuit: a product of readout and two-qubit gate fidelities over + exactly the qubits and couplers the circuit uses, with the qubit and coupler + counts beside it. The definition is in the + [reference](docs/reference.md#lqs). +- **Rankings** (Error tab, Analysis) order qubits and couplers by error. -- **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. +The score is intended for comparing layouts on the same processor; differences +between layouts are meaningful, the absolute value is not a fidelity +prediction. -The score is a first-order, *relative* heuristic — treat differences between -layouts as meaningful, not the absolute number. +

Layout editor with the Estimated Layout-Quality panel

-![Layout editor with LQS score](docs/img/app-view.png) +## 5. Calibration history -## 5. Travel in time - -The **Time** panel changes *which calibration snapshot* the whole map shows: +The **Calibration** section selects which calibration the map shows: - **Live** — the current calibration (default). -- **Point** — 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. - -Turn on **delta mode** to color the map by *change* relative to a reference -(e.g. "previous snapshot"): blue improved, red degraded. This is the fastest -way to see what drifted overnight — and whether yesterday's chosen qubits are -still the right ones today. - -![Delta view: blue improved, red degraded](docs/img/delta-view.png) - -## 6. Check stability - -In the **Analysis** panel, 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 -qubit tomorrow. If you selected 30 days but only 14 are fetched, the header -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 - -From the **Export** tab: - -- **Layout JSON** — export your layouts (including LUCJ role partitions) and - re-import them later or on another backend. -- **Import** — accepts layout `.json`, `.npy` (a plain array of qubit - indices), and QPY circuits. -- **PNG** — publication-ready snapshot of the current view, with legend and - colorbars (requires the `[png]` extra). -- **Time-lapse** — after fetching history (intraday or multi-day), export an - animated GIF/MP4 of the calibration evolving (requires the `[timelapse]` +- **Snapshot** — a chosen past date and time. +- **Intraday** — one day, with a slider over its calibration updates. +- **Multi-day** — a date range, with a slider over the days. + +**Delta** colours the map by the change relative to a reference calibration +(the first of the sequence, or the previous one): blue improved, red degraded. +It shows at a glance what has drifted since the layout was chosen. + +

Delta view: blue improved, red degraded

+ +## 6. Stability check + +In the **Stability check** card, enable the check and select a window of 7, 14 +or 30 days. For the qubits and couplers of the placed layout, the cached +history is analysed and the unstable qubits and gates are listed, each with +its maximum, median and minimum over the window and its worst day. If the +selected window is longer than the fetched history, the header says so; more +days can be fetched from the Multi-day mode of the Calibration section. + +The stability filter, in the Auto-LUCJ options, excludes volatile qubits from +the automatic search. + +

Stability report over a 14-day window

+ +## 7. Intra- and inter-QPU parallelisation + +Several circuits can share one processor (intra-QPU), and the same circuit or +set of circuits can be compared across processors (inter-QPU). + +**Intra-QPU.** With **4. Multi-Programming** enabled, the Auto-LUCJ panel gains +a **Multi** tab. Enter the orbital counts of the circuits, e.g. `8, 8, 6`, and +**Buffer qubits**, the number of idle qubits to keep between them, then +**Generate Multi-Circuit**. The circuits are planned together; the **Plans** +dropdown lists the best complete plans and places all circuits of the selected +one. + +**Inter-QPU.** **Scan all QPUs** (Single tab) and **Scan batch on all QPUs** +(Multi tab) run the same search on every accessible backend, each scored with +its own calibration, and rank the results. **Open on QPU 2** connects the +selected backend as a second processor and places the chosen layout or plan on +it, so the two devices can be compared side by side. +Details of the planner and the scans are in the +[reference](docs/reference.md#multi-circuit-planner). + +## 8. Benchmark the device + +The sections above rank layouts on the calibration the provider reports, +which can be up to a day old. Section **5. Benchmark** measures the hardware +now. It requires the `benchmark` extra (`pip install "i-qmapper[benchmark]"`); +without it the section shows the install hint and stays disabled. + +1. **Targets** — the current layouts (every circuit slot), the last search's + best candidates, the whole QPU, or a typed list of qubits. +2. **Level** — 1 measures readout only (seconds; its cost does not grow with + the number of qubits), 2 adds two-qubit randomized benchmarking on the + target couplers, 3 measures the whole processor including coherence times + (about four minutes). +3. The summary line states how many qubits and couplers will be measured, the + estimated QPU time and the detected plan. On the Open plan, Level 2 warns + and Level 3 requires an explicit acknowledgement. +4. **Run benchmark**. + +When the run completes, the calibration label changes to the measured epoch, +e.g. `measured 14:32 (L2, 38q/44e)`, and the map, the LQS and the candidate +list use the measured values for the elements that were measured; all other +elements keep their reported values. A consistency line compares the +measurement with the reported calibration; a systematic offset is handled in +relative mode, and **Calibration check** distinguishes an estimator offset from +crosstalk. See [Benchmarking](docs/reference.md#benchmarking) in the reference. + +Nothing runs automatically: no benchmark starts on connect, on a timer or +during a scan. + +## 9. Import, export and sessions + +From the **I/O** section: + +- **Layout JSON** — export the placed layouts, including LUCJ roles, and + re-import them later or on another backend. Import also accepts `.npy` + arrays of qubit indices and QPY circuits. +- **PNG** — the current view with legend and colour bars (requires the `png` extra). -- **Qiskit code** — generate ready-to-run code that applies your chosen - layout, so the decision you made here travels into your actual workflow. +- **Time-lapse** — after fetching intraday or multi-day history, an animated + GIF or MP4 of the calibration over time (requires the `timelapse` extra). +- **Qiskit code** — code that applies the chosen layout in a Qiskit workflow. +- **Export Session / Load Session** — the whole state (layouts, colours, zoom, + backend context) in one file, to resume later or to share. Style presets can + be saved and reused independently of sessions. -![Publication-ready PNG export with legend](docs/img/hero.png) +Messages in the interface that end with `· Reference: ` refer to the entry +of that name in the [reference](docs/reference.md). -## 8. Save your session +## 10. Where your data lives -**Session save/restore** captures everything — layouts, colors, zoom, the -backend context — into a single file, so you can close the notebook and pick -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 - -| What | Where | +| Data | Location | |---|---| | Calibration cache | macOS `~/Library/Caches/iqmapper` · Linux `~/.cache/iqmapper` (or `$XDG_CACHE_HOME/iqmapper`) · Windows `%LOCALAPPDATA%\iqmapper\Cache` | -| Cache override | Set `IQMAPPER_CACHE_DIR` before launching to relocate it | -| Sessions & style presets | `.iqmapper_sessions/` inside the directory your notebook runs from | -| IBM credentials | **Not stored by I-QMapper.** They live in your own `qiskit-ibm-runtime` account store (`~/.qiskit/qiskit-ibm.json`) | - -The cache exists so that time travel, delta views, and stability analysis cost -no repeated API calls. It is safe to delete at any time — the tool recreates -it and refetches on demand. +| Cache override | environment variable `IQMAPPER_CACHE_DIR`, set before launching | +| Log file | `iqmapper.log` in the user log directory (e.g. `~/Library/Logs/iqmapper` on macOS) | +| Sessions and style presets | `.iqmapper_sessions/` in the directory the notebook runs from | +| IBM credentials | Not stored by I-QMapper; they live in the `qiskit-ibm-runtime` account store (`~/.qiskit/qiskit-ibm.json`) | + +The cache is what makes history, delta views and the stability check free of +repeated API calls. It can be deleted at any time; the tool recreates it on +demand. diff --git a/docs/img/app-view.png b/docs/img/app-view.png index 214ec58..15eb33b 100644 Binary files a/docs/img/app-view.png and b/docs/img/app-view.png differ diff --git a/docs/img/hero.png b/docs/img/hero.png index 8b953e3..6e53066 100644 Binary files a/docs/img/hero.png and b/docs/img/hero.png differ diff --git a/docs/img/stability-report.png b/docs/img/stability-report.png index c3b753a..a18bc08 100644 Binary files a/docs/img/stability-report.png and b/docs/img/stability-report.png differ diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..b36e456 --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,286 @@ +# Reference + +Explanations of the settings and messages of the I-QMapper interface. A tooltip +that ends with `· Reference: ` refers to the entry of that name on this +page. For a first walkthrough see the [tutorial](../TUTORIAL.md); for the code, +[CODE_OVERVIEW.md](../CODE_OVERVIEW.md). + +Contents: +[LQS](#lqs) · +[Automatic LUCJ placement](#automatic-lucj-placement) · +[Multi-circuit planner](#multi-circuit-planner) · +[Scanning other processors](#scanning-other-processors) · +[Calibration history](#calibration-history) · +[Offline mode](#offline-mode) · +[Log file](#log-file) · +[Benchmarking](#benchmarking) + +## LQS + +The layout quality score estimates how well a circuit would run on a given set of +qubits: + +LQS = ∏ (1 − readout error) over the qubits the circuit uses + × ∏ (1 − two-qubit gate error) over every coupler joining two of those qubits. + +Each coupler is counted once, whichever directions the backend lists it in. The +Estimated Layout-Quality panel shows the same number for each circuit, together +with the qubit and coupler counts, e.g. `C1: 77.2% (18q × 18g · …)`. + +Layouts produced by the LUCJ search contain only the couplers the ansatz uses, +so for them the coupler count equals the number of two-qubit gates: +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 estimate was used. + +The score assumes independent errors and ignores crosstalk, circuit depth and +coherence; it is intended for comparing layouts on the same processor, not as an +absolute fidelity prediction. + +## Automatic LUCJ placement + +The LUCJ ansatz maps to a fixed template: an α chain and a β chain of `norb` +qubits each, joined by ancilla bridges. The search looks for the placement of +this template with the highest LQS on the processor. + +### Search engine + +Two engines run on every search: + +- The **exhaustive** engine enumerates the placements that fit the template and + scores them afterwards. At low ancilla counts on a large processor the number + of placements exceeds the search cap, and only a sample is ranked. +- The **guided** engine grows each layout along the best-calibrated qubits and + refines the finalists with local moves. It is not capped, but as a heuristic it + can miss placements the exhaustive engine would find. + +For every ancilla count the two shortlists are merged, duplicates are removed, +and the final list is ranked by LQS with the region-diversity rule below. The +best layout is therefore never worse than either engine alone. Each entry in +the layout list ends with its origin: `· E` exhaustive, `· G` guided, `· E+G` +both. + +**Guided search** (Advanced, on by default) enables the guided engine. With it +off, the search uses the exhaustive engine alone, as in the previous release; +**Beam width** and **Refine top** tune the guided engine and are shown only +while it is on. The multi-processor scan and the stability filter use the exhaustive engine +only. + +### Search results + +A search ends with one line, e.g. `12 layouts found · scored on live · 20:41`: +the number of layouts in the list and the calibration that scored them. Each +entry carries its ancilla count, rank, LQS and origin. + +### Search cap + +The exhaustive engine stops after this many candidate placements. On a large +processor the cap is normally reached at low ancilla counts. When it is, the log +file records it; with diverse enumeration off, a warning notes that the ranking +may be non-exhaustive. Raising the cap gives a more thorough but slower search. + +### Diverse enumeration + +With this option on, the cap counts distinct candidates: a placement that +overlaps one already kept by more than 80 % of its qubits, and does not score +better, is discarded without using a slot, and one that scores better replaces +it. Without it, the cap fills with near-copies of the first region found, and +much of a large processor is never examined. The option only has an effect +where the cap is reached. It is on by default on heavy-hex processors and off on +square-lattice processors (Nighthawk), where the number of placements is far +larger and the option costs minutes for a gain of about 1 % in LQS. + +### Prefer diverse regions + +The first half of each candidate list is always the best-scoring layouts. The +second half may prefer layouts on other parts of the processor, so that the +list offers alternatives rather than variations of one position. A better +layout is never demoted. + +### Quality floor + +Qubits whose readout error lies more than the given number of standard +deviations above the device mean are excluded before the search starts. Set to 0 +to disable. The purpose is to exclude clearly defective qubits, not to tune the +search. + +## Multi-circuit planner + +Several circuits are placed together on one processor. Placing them one at a +time, each on the best remaining region, can leave a later circuit a poor region +or none at all. The planner therefore keeps several partial plans: after each +circuit it tries **Candidates per circuit** layouts (default 3) on every plan it +holds and keeps the best **Plans kept** (default 3). It also builds the +one-at-a-time plan and returns whichever is better, so the result is never +worse than sequential placement. + +The status line `2 circuits placed · +X% vs one-by-one` compares the two plans' +totals (the product of the circuits' LQS); the gain is omitted when there is +none. If the joint plan fits more circuits than sequential placement could, the +line reads `places 3 vs 2 one-by-one` instead. + +**Plans** lists the best complete plans, e.g. +`Plan 1 · total 48.2% · C1 79.2% + C2 61.0%`; selecting one places all its +circuits. Below it, each circuit's alternatives include only layouts after +which every later circuit still fits; the others are counted in one line. + +**Buffer qubits** is the number of idle qubits kept between circuits. With a +buffer of 1 or more, circuits never share a coupler. At 0 they may sit side by +side; couplers joining two circuits are listed as `shared couplers: 47–48` and +each one multiplies the plan score by `1 − Boundary penalty`, so a non-zero +penalty makes the planner prefer plans without them when such plans exist. + +**Fast: one circuit at a time** (Advanced, off by default) skips joint planning +and places the circuits sequentially with the exhaustive engine, as in the +previous release. + +## Scanning other processors + +**Scan all QPUs** runs the current single-circuit search on every accessible +backend, scored with that backend's own calibration, and ranks the results. +**Scan batch on all QPUs** does the same for the current set of circuits, +placing them one at a time on each backend. Backends that fit all circuits +rank first by combined score; a backend that fits only some of them reads +`ibm_x — 1 of 2 circuits fit`, carries no total, and cannot be opened. +Backends whose topology the application cannot display are listed as +not supported. The processor currently connected is never searched again; its +local result appears as a reference row. + +**Open on QPU 2** connects the selected backend as a second processor and +places the chosen layout or batch on it. The outcome is reported next to the +button. + +## Calibration history + +Calibrations are cached locally as they are fetched, so browsing earlier +calibrations, difference views and the stability check cost no QPU time. + +### Delta references + +In the difference view each calibration is compared against a reference. +**First** uses the first calibration in the sequence, showing cumulative drift +from a starting point. **Previous** uses the preceding calibration, showing the +step-by-step change as the slider moves; the first position has no comparison. + +### Stability check + +For each qubit, the readout and gate errors are evaluated over the selected +window (7, 14 or 30 days). Qubits whose values vary strongly across the window +are flagged, and the stability filter can exclude them from the automatic +search. For each unstable qubit or coupler the report shows the maximum, median +and minimum over the window and the worst day. + +## Offline mode + +A session restored without a backend connection. Layout editing, scoring +against the saved calibration and export all work. Anything that needs live +data — the difference view, calibration history, refreshing the map — becomes +available once a backend is connected from the Hardware section. + +Sessions and style presets are saved under `.iqmapper_sessions/` in the +directory the notebook runs from; **Export Session** writes a session file to a +path of your choice. + +## Log file + +Technical messages (fallbacks, cap statistics, missing calibration values) are +written to `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. They never appear under the +notebook cell. + +# Benchmarking + +I-QMapper normally ranks layouts on the calibration the provider reports, which +is refreshed about once a day. Qubits drift within that window. The Benchmark +section (sidebar, **5. Benchmark**) re-measures the hardware and feeds the +result back as a *measured* calibration epoch; the map, the LQS, the candidate +ranking and the exports read it exactly as they read the reported one. + +Requires the optional dependency: + +```bash +pip install "i-qmapper[benchmark]" +``` + +Benchmarking is never automatic: nothing runs on connect, on a timer or inside +the multi-processor scan. A run starts only from **Run benchmark**, and its +estimated QPU cost is shown before the button is enabled. + +## Levels + +| Level | Measures | Scope | Approximate QPU time | +|---|---|---|---| +| 1 | Readout assignment error | Target qubits | Seconds | +| 2 | Level 1 + single- and two-qubit randomized benchmarking | Target qubits and couplers | Tens of seconds | +| 3 | T1, T2 (Hahn echo), readout, single- and two-qubit RB | Whole processor | About four minutes | + +Level 1 uses two circuits regardless of the number of qubits, so its cost does +not grow with the target; Level 1 on the whole processor is the inexpensive way +to refresh the readout map. Levels 2 and 3 scale with the number of couplers. +Level 3 reproduces the full-chip suite of IBM's "Real-time benchmarking for +qubit selection" tutorial, with the experiments grouped so that the whole +processor is covered by about 134 circuits. + +## Targets + +What a run measures: the layouts currently placed (every circuit slot), the +last search's best candidates, the whole processor, or an explicit list of +qubits. In inter-QPU mode a **QPU 1 | QPU 2** selector applies the targets, the +run and the resulting epoch to the selected processor. + +## Cost + +Cost estimates are wall-clock QPU seconds. The plan of the account is detected +where possible and assumed to be the Open plan otherwise; on that assumption +Level 2 warns and Level 3 requires an explicit acknowledgement, since a Level 3 +run can consume a large part of a monthly allowance. The estimate is calibrated +from a single published figure and should be read as an order of magnitude. + +Jobs that would exceed the provider's per-job shot limit are split +automatically. A rejected or failed job reports the provider's own error text +and the job identifiers. A completed run can be re-analysed later from its job +identifiers at no QPU cost. + +## Relative mode + +Randomized benchmarking and the provider's calibration are different estimators +of the same quantities, and they do not always agree on the absolute scale. A +two-qubit Clifford contains on average about 1.5 two-qubit gates and 8 to 10 +single-qubit gates; the two-qubit RB analysis is therefore given the measured +single-qubit error rates and subtracts them. + +After every run the measured values are compared with the reported ones, +property by property, and the result is stated: values in line with the +reported calibration, or values that differ by a constant factor and are shown +on the reported scale. The figures are in the **Details** table. If a property's +median is more than twice, or less than half, the reported one, the difference +is treated as a difference of method rather than a change in the device, and the +epoch is applied in relative mode: each value is rescaled so that the median +matches the reported one, which removes the offset while preserving every ratio +between elements. A coupler that has degraded still appears several times worse +than its neighbours. **Apply absolute values** uses the raw measurements +instead. + +## Calibration check + +Measures a small set of couplers twice in one session — with all pairs driven +in parallel, then one pair at a time — and compares both against the reported +values: + +- both arms offset in the same way: estimator bias (single-qubit error + attributed to the two-qubit gate); +- only the parallel arm offset: crosstalk between simultaneously driven pairs; +- both close to the reported values: the measurements agree. + +The check does not change the calibration in use. + +## What is applied + +Measured values replace reported ones only for the elements actually measured; +all other elements keep their reported values, and the calibration label names +the epoch in use. A run reports what it measured (`measured 156/156 qubits`, +or `partial` when some elements failed), and a run that measured nothing is +reported as a failure and leaves the reported calibration in place. An +experiment or fit that fails falls back to the reported value for that element +with a notice. diff --git a/iqmapper/__init__.py b/iqmapper/__init__.py index 337e4a3..cd4c511 100644 --- a/iqmapper/__init__.py +++ b/iqmapper/__init__.py @@ -10,12 +10,25 @@ 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(): """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 + # 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() + install_file_log() + def _on_connect(vendor, backend_name, backend, chip, props, props_warning, ansatz, service, available_backends): diff --git a/iqmapper/ancilla_sweep.py b/iqmapper/ancilla_sweep.py new file mode 100644 index 0000000..81dd525 --- /dev/null +++ b/iqmapper/ancilla_sweep.py @@ -0,0 +1,710 @@ +""" +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 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 +----------------------------- +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 hashlib +import logging +import random + +import numpy as np +import rustworkx + +from .auto_lucj import ( + _collect_vf2_mappings, + _get_two_q_gate_name, + _make_backend_cmap_pygraph, + _MAX_RAW_VF2_MAPPINGS, + _remove_nodes_from_graph, + 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 + +# 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 the per-stratum shuffled-search-graph construction below. +_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 _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: + 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, exclude_qubits=None, + circuit_score_fn=None, hybrid=True, + shuffle_seed=_AUTO_SHUFFLE, + diversity_threshold=None, + diverse_cap=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. + + 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. + 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. + 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. + 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. + diversity_threshold: when a float in (0, 1), rebalance each stratum's + 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 ∪ + 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 + 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 + '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) + 'excluded_qubits': [...], # sorted list actually pruned (empty + # when exclude_qubits is None) + 'per_stratum': {k: {'n_direct', 'n_derived', 'truncated', 'shuffled'}}, + # per-k provenance; vf2_truncated is + # any(per-stratum truncated); + # 'shuffled' = search order permuted + } + 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 ---------------- + # `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 + + # ---- 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 + # 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, + backend_coupling_graph=search_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})." + ) + + # ---- 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.") + + # 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) + 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 full_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)) + + # ---- 3. Collect VF2 embeddings, detect truncation --------------------- + cap = mapping_cap if mapping_cap is not None else _MAX_RAW_VF2_MAPPINGS + + reservoir_stats = {} + + def _make_reservoir(k, key_to_phys): + """A DiverseReservoir scoring with the sweep's own product formula. + + The score closes over the `readout` / `_edge_e` hoisted just above, + so enumeration and `_add_variant` cannot drift apart. Returns None + when diverse_cap is off, which restores the historical path exactly. + """ + if not diverse_cap: + return None + from .reservoir import DiverseReservoir + size = 2 * norb + k + + def _to_layout(mapping): + layout = [None] * size + for key, value in mapping.items(): + if value < size: + layout[value] = key_to_phys(key) + return layout + + def _score(layout): + alpha = layout[:norb] + beta = layout[norb:2 * norb] + product = 1.0 + for q in layout[:2 * norb]: + product *= max(0.0, 1.0 - float(readout[q])) + for j in range(norb - 1): + product *= max(0.0, 1.0 - _edge_e(alpha[j], alpha[j + 1])) + product *= max(0.0, 1.0 - _edge_e(beta[j], beta[j + 1])) + for i in range(k): + bphys = layout[2 * norb + i] + product *= (max(0.0, 1.0 - float(readout[bphys])) + * max(0.0, 1.0 - _edge_e(alpha[4 * i], bphys)) + * max(0.0, 1.0 - _edge_e(bphys, beta[4 * i]))) + return product + + return DiverseReservoir(cap, _score, _to_layout) + + kmax_graph, kmax_key_to_phys, kmax_shuffled = _search_for(k_max_effective) + _kmax_res = _make_reservoir(k_max_effective, kmax_key_to_phys) + mappings = _collect_vf2_mappings(kmax_graph, template, cap=cap, + reservoir=_kmax_res) + if _kmax_res is not None: + reservoir_stats[k_max_effective] = _kmax_res.stats + # 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] = kmax_key_to_phys(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." + ) + + # ---- 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)} + 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 + + 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_qubits = np.array(chain, dtype=int) + 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) + bridges = [] + 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]) + bridges.append({ + '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) + 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 + 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): + n_candidates_scored += 1 + 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 + k_graph, k_key_to_phys, k_shuffled = _search_for(k) + per_stratum[k]['shuffled'] = k_shuffled + _res_k = _make_reservoir(nb_k, k_key_to_phys) + maps_k = _collect_vf2_mappings(k_graph, tmpl_k, cap=cap, + reservoir=_res_k) + if _res_k is not None: + reservoir_stats[k] = _res_k.stats + 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] = k_key_to_phys(key) + if any(v is None for v in lay): + continue + edata = _embedding_data(lay, nb_k) + # 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()) + + # ---- 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 — + # 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 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. + higher_winners = [] + 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'], reverse=True) + + if circuit_score_fn is None: + # 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: + 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) + # 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) + # 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 + 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)) + + # One notice per stratum whose cap was actually reached. The reservoir + # only engages on the hybrid path (at k_max the enumeration is far below + # the cap), so the notice names the hybrid pass explicitly. + reservoir_notices = [] + if reservoir_stats: + from .reservoir import summarise as _summarise_reservoir + for k in sorted(reservoir_stats, reverse=True): + stats_k = reservoir_stats[k] + if stats_k.get('kept', 0) >= cap: + note = _summarise_reservoir( + stats_k, k, hybrid=(k != k_max_effective)) + if note: + reservoir_notices.append(note) + + return { + 'strata': strata, + 'reservoir': reservoir_stats, + 'reservoir_notices': reservoir_notices, + '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, + 'excluded_qubits': excluded_sorted, + 'per_stratum': per_stratum, + # 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/iqmapper/async_util.py b/iqmapper/async_util.py index 1ab63e9..356bd86 100644 --- a/iqmapper/async_util.py +++ b/iqmapper/async_util.py @@ -4,73 +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. tornado IOLoop (classic notebook + most JupyterLab kernels) - 2. asyncio event loop (asyncio-native kernels) - 3. inline fallback (run on the worker thread, original behaviour) +# 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. """ + # 1. running loop try: - from tornado.ioloop import IOLoop - loop = IOLoop.current() - return lambda cb: loop.add_callback(cb) + return asyncio.get_running_loop(), 'asyncio' + except RuntimeError: + 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("tornado IOLoop unavailable", exc_info=True) + _log.debug("asyncio set-loop probe failed", exc_info=True) + # 3. tornado IOLoop (optional dependency); probed WITHOUT creating one. try: - import asyncio - try: - aloop = asyncio.get_running_loop() - except RuntimeError: - aloop = None - if aloop is not None: - return lambda cb: aloop.call_soon_threadsafe(cb) + 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("asyncio event loop unavailable", exc_info=True) - # No event loop available — run inline on the worker thread. - return lambda cb: cb() + _log.debug("tornado IOLoop probe failed", exc_info=True) + return None, None -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. +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) - 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 +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): + """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): + + 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. + """ + 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 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) @@ -83,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/iqmapper/auto_lucj.py b/iqmapper/auto_lucj.py index 568b1a1..4a373b0 100644 --- a/iqmapper/auto_lucj.py +++ b/iqmapper/auto_lucj.py @@ -336,13 +336,36 @@ def _make_backend_cmap_pygraph(backend) -> PyGraph: _MAX_RAW_VF2_MAPPINGS = 2000 -def _collect_vf2_mappings(graph, subgraph, cap=_MAX_RAW_VF2_MAPPINGS): +def _collect_vf2_mappings(graph, subgraph, cap=_MAX_RAW_VF2_MAPPINGS, *, + reservoir=None): """Collect at most `cap` isomorphic mappings from rustworkx.vf2_mapping. Returns the materialized list. Logs a warning when the cap was hit so we can tell the user (or future maintainers) that scoring may have missed better-ranked layouts beyond the cap. + + With `reservoir` (an `iqmapper.reservoir.DiverseReservoir`) the cap + counts DISTINCT candidates instead of raw mappings: near-duplicates are + offered, rejected and do not consume a slot. VF2 yields in graph + traversal order, so a plain cap keeps one clustered corner of the chip; + see reservoir.py for the measurement. `reservoir=None` is the historical + path, byte-for-byte unchanged. """ + if reservoir is not None: + for m in rustworkx.vf2_mapping(graph, subgraph, subgraph=True): + reservoir.offer(m) + # Stop on the OFFER budget, not on being full: the reservoir + # fills before it sieves, so halting at `len >= cap` would make + # it see nothing past the first `cap` mappings and behave + # exactly like the plain cap it replaces. + if reservoir.exhausted: + _log.debug( + "VF2 cap reached: kept %d diverse mappings, skipped %d " + "near-duplicates", len(reservoir), + reservoir.stats['skipped_similar']) + break + return reservoir.mappings + mappings = [] truncated = False for m in rustworkx.vf2_mapping(graph, subgraph, subgraph=True): @@ -777,7 +800,7 @@ def get_multi_circuit_layouts( # ═══════════════════════════════════════════════════════════════════════ -# JOINT RE-OPTIMIZATION (F3) +# JOINT RE-OPTIMIZATION # ═══════════════════════════════════════════════════════════════════════ def reoptimize_after_change( diff --git a/iqmapper/benchmark.py b/iqmapper/benchmark.py new file mode 100644 index 0000000..21ff458 --- /dev/null +++ b/iqmapper/benchmark.py @@ -0,0 +1,3174 @@ +""" +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 +import warnings +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 + +#: Plausibility bounds. A failed fit does not return an error — it returns a +#: NUMBER, and an absurd one poisons whatever consumes it. A 1Q EPG of 0.71 +#: forwarded into `rb_analysis._exclude_1q_error` made it evaluate +#: `(1 - 2*epg) ** n_gate` on a negative base and raise +#: "The uncertainties module does not handle complex results", killing every +#: two-qubit callback of the calibration check. IBM single-qubit gate errors +#: run about 1e-4 to 1e-3, so anything at or above 5e-2 is a failed fit, not +#: a bad qubit. +_EPG_1Q_MAX = 0.05 + +#: Readout assignment error is a probability; 0.5 is chance, and a symmetric +#: matrix worse than that means the fit, not the qubit, is broken. +_READOUT_MAX = 0.5 + +#: T1/T2 in microseconds. Superconducting coherence times are hundreds of +#: microseconds at best; 10 ms is a fit that ran away. +_COHERENCE_MAX_US = 10_000.0 + +#: 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 = 1.20 +_SEC_PER_CIRCUIT_2Q = 1.90 +_SEC_PER_T1T2 = 1.20 +_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', + 'planned_count', 'extra', 'consistency', 'relative') + + def __init__(self, qubit_props, gate_props, measured_qubit_mask, + measured_edge_mask, level, when, notices=None, + planned_count=None, extra=None, consistency=None, + relative=False): + 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 []) + # (n_qubits, n_edges) the plan INTENDED to measure. Compared against + # measured_count so the UI can tell "complete", "partial" and "nothing + # came back" apart — the last of which must never read as success. + self.planned_count = tuple(planned_count or (0, 0)) + # Side data the arrays have no column for: per-qubit 1Q EPGs (used to + # subtract single-qubit error from the 2Q Clifford decay), and + # anything else diagnostic. + self.extra = dict(extra or {}) + # Filled by `consistency_stats` after folding: how the measured values + # compare with the reported ones, per property. + self.consistency = dict(consistency or {}) + # True when the values were rescaled to the reported medians because a + # systematic offset was detected (see `apply_relative_mode`). + self.relative = bool(relative) + + # ── 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()) + + @property + def measured_count(self): + return (self.n_measured_qubits, self.n_measured_edges) + + @property + def is_empty(self): + """Nothing was measured. A FAILURE, not a successful no-op.""" + return self.measured_count == (0, 0) + + @property + def is_complete(self): + return (self.planned_count != (0, 0) + and self.measured_count == self.planned_count) + + def coverage_text(self): + """'120/156 qubits, 210/240 edges' for the status line.""" + pq, pe = self.planned_count + return (f'{self.n_measured_qubits}/{pq} qubits, ' + f'{self.n_measured_edges}/{pe} edges') + + 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. + + 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 [])] + + 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 and qubits: + 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)) + + # 1Q RB runs at L2 as well as L3, and BEFORE the two-qubit layers: its + # per-qubit EPGs are what lets the 2Q analysis subtract single-qubit error + # from the Clifford decay. Without that subtraction a 2Q Clifford's ~8-10 + # single-qubit gates are all attributed to the two-qubit gate, which on + # 20 Sept inflated every measured cz_error by roughly 2-3x uniformly. + if level in (LEVEL_TARGETED, 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: + # 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)): + 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) + + +# ── 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): + """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 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_planned_count(plan): + """(n_qubits, n_edges) this plan actually intends to MEASURE. + + Not the target counts: a Level 1 plan targets qubits and edges but only + ever measures readout, so counting its target edges as "planned" would + make a perfect L1 run look permanently partial. Planned means "a spec in + this plan writes to that element". + """ + # Pairs are counted AS GIVEN, not sorted into undirected pairs: a + # device's gate arrays are indexed by its directed edge list, so + # (a, b) and (b, a) are two array slots and the measured mask counts + # both. Deduplicating here made a complete run read "348/176 edges". + qubits, edges = set(), set() + for spec in plan.specs: + if spec.kind in ('readout', 't1', 't2hahn'): + qubits.update(int(q) for q in spec.qubits) + elif spec.kind == 'rb2q_layer': + for pair in (spec.params.get('pairs') or []): + edges.add(tuple(int(q) for q in pair)) + elif spec.kind == 'rb2q': + edges.add(tuple(int(q) for q in spec.qubits)) + return (len(qubits), len(edges)) + + +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: + _log.warning( + 'one experiment needs %s circuit-shots, over IBM\'s %s ' + 'per-job limit, and cannot be split further', + f'{chunk.shots:,}', f'{_MAX_CIRCUIT_SHOTS_PER_JOB:,}') + return False, ( + "One experiment exceeds IBM's per-job limit \u2014 reduce " + "the targets or the level") + return True, None + + +def estimate_cost(plan, shots=DEFAULT_SHOTS): + """Wall-clock QPU seconds a plan is expected to consume. + + Now that every spec is a ParallelExperiment, the driver is the CIRCUIT + COUNT, not the qubit count: widening a spec puts more qubits into the same + circuits rather than adding circuits. So the model is flat per circuit, + with a higher rate for two-qubit RB because those circuits are deeper. + + An ESTIMATE, and a coarse one: back-solved from the tutorial's single + published figure (~4 min for the full suite) and blind to queueing and + device load. `circuits` and `shots` on the returned estimate are exact; + only `qpu_seconds` is a guess. + """ + circuits = plan_circuit_count(plan) + seconds = 0.0 + for spec in plan.specs: + n = _spec_circuits(spec) + if spec.kind in ('rb2q_layer', 'rb2q'): + seconds += n * _SEC_PER_CIRCUIT_2Q + elif spec.kind in ('t1', 't2hahn'): + seconds += n * _SEC_PER_T1T2 + else: + seconds += n * _SEC_PER_CIRCUIT_1Q + + seconds *= (shots / float(DEFAULT_SHOTS)) if DEFAULT_SHOTS else 1.0 + seconds += _SESSION_OVERHEAD_S if plan.specs else 0.0 + + n_jobs = len(split_for_submission(plan, shots)) if plan.specs else 0 + total_shots = circuits * int(shots) + return CostEstimate(circuits, seconds, + _format_cost(circuits, total_shots, n_jobs, seconds)) + + +def _format_shots(total): + if total >= 1_000_000: + return f'{total / 1_000_000:.1f}M shots' + if total >= 1_000: + return f'{total / 1_000:.0f}k shots' + return f'{total} shots' + + +def _format_cost(circuits, total_shots, n_jobs, seconds): + """The one line that has to tell the truth before the click. + + Circuits, shots and job count are exact; the seconds are the estimate. + Showing the job count matters because a run that needs more than one job + is the situation that used to fail at submission. + """ + if circuits == 0: + return 'nothing to measure' + job_txt = '1 job' if n_jobs <= 1 else f'{n_jobs} jobs' + if seconds < 90: + time_txt = f'~{seconds:.0f} s QPU (estimate)' + else: + time_txt = f'~{seconds / 60.0:.1f} min QPU (estimate)' + return (f'~{circuits} circuits · {_format_shots(total_shots)} · ' + f'{job_txt} · {time_txt}') + + +# ── 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 uses ~4 min of QPU \u2014 a large share of an ' + 'Open-plan monthly allowance') + 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 + + +class BenchmarkRunError(RuntimeError): + """A job was rejected, errored or cancelled by the provider. + + Carries the provider's own message and the job ids, because "no results + returned" told the user nothing on the run that motivated this class: IBM + had rejected the submission outright (error 1520, shot limit) and the + panel still reported success. + """ + + def __init__(self, message, job_ids=None, chunk=None, expdata=None): + super().__init__(message) + self.job_ids = list(job_ids or []) + self.chunk = chunk + # Carried so the panel can still write a raw dump on the failure path, + # which is exactly when the diagnostic artefact matters most. + self.expdata = list(expdata or []) + + +#: Analysis-result names the tutorial's experiments produce. Kept in one place +#: because they are the contract between qiskit-experiments and our parser, and +#: a rename there silently emptied every epoch before the integration tests. +RESULT_T1 = 'T1' +RESULT_T2 = 'T2' +RESULT_READOUT_MITIGATOR = 'Local Readout Mitigator' +RESULT_EPG_PREFIXES = ('EPG', 'EPC') + + +def _build_experiment(spec, api, context=None): + """One `ExperimentSpec` → ONE composite qiskit-experiments object. + + Every branch returns a single experiment covering all of the spec's qubits + or pairs at once. `flatten_results=True` is passed explicitly rather than + left to the installed version's default, so the analysis results land at a + predictable depth whatever version is installed. + """ + physical = list(spec.qubits) + if spec.kind == 't1': + return api.ParallelExperiment( + [api.T1((q,), delays=spec.params['delays']) for q in physical], + flatten_results=True) + if spec.kind == 't2hahn': + return api.ParallelExperiment( + [api.T2Hahn((q,), delays=spec.params['delays']) for q in physical], + flatten_results=True) + 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], + flatten_results=True) + if spec.kind == 'rb2q_layer': + pairs = [tuple(p) for p in spec.params['pairs']] + epg_results = (context or {}).get('epg_results') or {} + notices = (context or {}).setdefault('notices', []) \ + if context is not None else [] + inner = [] + applied, skipped = 0, [] + for pair in pairs: + rb = api.StandardRB(pair, lengths=spec.params['lengths'], + num_samples=spec.params['num_samples']) + if apply_epg_1q_options(rb, pair, epg_results, notices): + applied += 1 + else: + skipped.append(tuple(pair)) + inner.append(rb) + # MANDATORY: whether the subtraction happened is the difference + # between a measured cz_error of 2.9e-3 and 4.0e-3, so it is never + # left to be inferred from the absence of a message. + if context is not None: + tally = context.setdefault('_epg_tally', {'applied': 0, + 'skipped': []}) + tally['applied'] += applied + tally['skipped'].extend(skipped) + return api.ParallelExperiment(inner, flatten_results=True) + if spec.kind == 'rb2q': # legacy single-pair spec + return api.StandardRB(tuple(physical), + lengths=spec.params['lengths'], + num_samples=spec.params['num_samples']) + raise ValueError(f'unknown experiment kind: {spec.kind}') + + +EpgHarvest = namedtuple('EpgHarvest', 'results rejected') + + +def _plausible_epg(value): + return (value is not None and np.isfinite(value) + and 0.0 <= value < _EPG_1Q_MAX) + + +def harvest_epg_results(entry): + """Per-qubit lists of the ACTUAL 1Q EPG analysis-result objects. + + Not floats. `rb_analysis._exclude_1q_error` iterates whatever is handed to + `epg_1_qubit` and reads `.device_components` off each element, so passing + plain numbers raised + + AttributeError: 'float' object has no attribute 'device_components' + + in every two-qubit callback of the 20 Sept 13:08 run — phase 1 succeeded, + phase 2 produced no EPG_cz at all, and because the JOBS were DONE nothing + upstream noticed. The tutorial passes the 1Q RB analysis results + themselves, so that is what we keep and forward. + + Results whose value is implausible (see `_EPG_1Q_MAX`) are withheld: a + failed fit returns a number, and forwarding one crashed the whole 2Q + analysis. Returns `EpgHarvest(results, rejected)`; a rejected qubit is + treated as having no 1Q EPG at all, so its pairs are simply not + subtracted — and the tally says which. + """ + out, values = {}, {} + items = entry if isinstance(entry, (list, tuple)) else [entry] + for item in items: + name = str(getattr(item, 'name', '') or '') + if not name.upper().startswith('EPG'): + continue + qubits = _components_to_qubits(item) + if len(qubits) != 1: + continue + qubit = int(qubits[0]) + try: + value = _result_value(item) + except Exception: + value = None + out.setdefault(qubit, []).append(item) + # Track the worst value seen for the qubit: one broken basis-gate fit + # is enough to poison the subtraction for every pair it touches. + if value is not None and np.isfinite(value): + values[qubit] = max(values.get(qubit, value), float(value)) + else: + values[qubit] = float('nan') + + rejected = {q: v for q, v in values.items() if not _plausible_epg(v)} + for qubit in rejected: + out.pop(qubit, None) + return EpgHarvest(out, rejected) + + +def apply_epg_1q_options(experiment, pair, epg_results, notices=None): + """Hand a two-qubit RB analysis the 1Q EPG RESULTS for its two qubits. + + `epg_results` maps qubit -> list of analysis-result objects harvested from + the phase-1 1Q RB run (see `harvest_epg_results`). + + When a result is missing for either qubit the subtraction is SKIPPED for + that pair, with a notice, rather than substituted with a fabricated + stand-in. That is a deliberate choice: the failure mode is deferred to + analysis time — a wrong shape does not raise when the option is set, it + raises inside the fit callback after the QPU time has already been spent, + and `set_options` cannot validate it. A synthetic object that merely looks + right would risk repeating exactly the failure this function exists to + fix, so an un-subtracted pair plus a visible notice is the safer trade. + + Returns True when the option was set. + """ + notices = notices if notices is not None else [] + pair = tuple(pair) + results = [] + missing = [] + for q in pair: + got = (epg_results or {}).get(int(q)) + if got: + results.extend(got) + else: + missing.append(int(q)) + + if missing: + return False + + analysis = getattr(experiment, 'analysis', None) + if analysis is None or not hasattr(analysis, 'set_options'): + return False + try: + analysis.set_options(epg_1_qubit=results) + return True + except Exception as exc: # noqa: BLE001 - reported + notices.append(f'{list(pair)}: the installed qiskit-experiments ' + f'rejected epg_1_qubit ({exc}); not 1Q-subtracted') + return False + + +def epg_tally_notice(context): + """The one line that says whether 1Q subtraction actually happened. + + Absence of a message is not evidence of success: a reanalysis replayed + from a SINGLE-phase record has no 1Q EPGs to hand the 2Q analyses, and + produced an un-subtracted cz_error (x2.85 rather than x2.11) with nothing + on screen to say so. This notice is emitted on every run that contains + two-qubit RB, whatever the outcome. + """ + tally = (context or {}).get('_epg_tally') + if not tally: + return None + applied = int(tally.get('applied') or 0) + skipped = list(tally.get('skipped') or []) + rejected = dict((context or {}).get('_epg_rejected') or {}) + if not applied and not skipped: + return None + text = f'1Q EPG subtraction: applied to {applied} pairs' + if skipped: + qubits = sorted({q for pair in skipped for q in pair}) + # Name the implausible fits with their value: "q17: 1Q EPG 0.71 + # implausible" tells the user which qubit to look at, where a bare + # count does not. + blamed = [f'q{q}: 1Q EPG {rejected[q]:.2g} implausible' + for q in qubits if q in rejected and + np.isfinite(rejected[q])] + blamed += [f'q{q}: 1Q EPG fit failed' + for q in qubits if q in rejected and + not np.isfinite(rejected[q])] + if not blamed: + shown = ', '.join(str(q) for q in qubits[:12]) + more = '' if len(qubits) <= 12 else f', +{len(qubits) - 12} more' + blamed = [f'qubits {shown}{more}'] + detail = '; '.join(blamed[:6]) + if len(blamed) > 6: + detail += f'; +{len(blamed) - 6} more' + text += (f', skipped {len(skipped)} ({detail}) — ' + f'those edges read high versus reported') + return text + + +def collect_analysis_errors(expdata, depth=0): + """Client-side analysis failures, which `status()` does NOT report. + + A job can be DONE while every fit callback raised: on 20 Sept 13:08 both + phases reported DONE=12 and `errors()` was None at the top level, yet + phase 2 produced zero results because each callback had thrown. Silence + there is what turned a total analysis failure into six bland "no results + returned" notices. Walks the tree because composite experiments record + failures on the child that raised. + """ + found = [] + if expdata is None or depth > 6: + return found + for attr in ('analysis_errors', 'errors'): + getter = getattr(expdata, attr, None) + if getter is None: + continue + try: + value = getter() if callable(getter) else getter + except Exception: + continue + if value: + text = str(value).strip() + if text and text.lower() not in ('none', '[]', '{}'): + found.append(text) + try: + for child in list(expdata.child_data()): + found.extend(collect_analysis_errors(child, depth + 1)) + except Exception: + pass + return found + + +def summarise_analysis_errors(errors, limit=3): + """Collapse repeated callback failures into one readable notice.""" + if not errors: + return None + counts = {} + for text in errors: + head = text.splitlines()[-1][:200] if text else text + counts[head] = counts.get(head, 0) + 1 + ordered = sorted(counts.items(), key=lambda kv: -kv[1]) + parts = [f'{n}x {head}' if n > 1 else head for head, n in ordered[:limit]] + extra = ('' if len(ordered) <= limit + else f' (+{len(ordered) - limit} other error(s))') + return f'analysis failed: {"; ".join(parts)}{extra}' + + +def _job_ids_of(expdata): + try: + return [str(j) for j in (expdata.job_ids or [])] + except Exception: + return [] + + +def _status_name(obj): + try: + status = obj.status() + except Exception: + return '' + return getattr(status, 'name', None) or str(status) + + +def _check_chunk_status(expdata, chunk_index): + """Raise `BenchmarkRunError` when the provider failed this chunk. + + This is the gap that produced the false success: a rejected submission + left an errored `ExperimentData` whose `analysis_results()` was simply + empty, and an empty parse looked exactly like a successful run that + measured nothing. + """ + job_ids = _job_ids_of(expdata) + status = _status_name(expdata).upper() + if status in ('ERROR', 'CANCELLED'): + detail = '' + try: + errors = expdata.errors() + if errors: + detail = str(errors).strip() + except Exception: + pass + raise BenchmarkRunError( + f'chunk {chunk_index + 1}: job {status.lower()}' + + (f' — {detail}' if detail else ''), + job_ids, chunk_index) + return job_ids + + +def make_runtime_runner(backend, on_jobs=None, sampler_factory=None): + """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. The call shape + is pinned by tests/test_benchmark_runtime_contract.py. + + The plan is split into chunks that each fit IBM's per-job circuit-shot + limit and submitted sequentially INSIDE ONE SESSION, so the whole run + still costs one reservation. Each chunk's status is checked before its + results are parsed; a failed chunk raises rather than yielding an empty + parse that would look like a successful measurement of nothing. + + Args: + on_jobs: optional ``callable(chunk_index, job_ids, status)`` invoked as + soon as ids are known, so the panel can persist them for later + reanalysis even if the process dies mid-run. + sampler_factory: optional ``callable(session) -> sampler``, for the + integration tests to substitute a local simulator without touching + any other part of the path. + """ + api = preload_runtime() + + def _runner(plan): + # Two phases inside ONE session: everything that is not two-qubit RB + # first, then the 2Q layers built with the 1Q EPGs the first phase + # produced. The ordering is what makes the subtraction possible — + # a StandardRB analysis cannot be told the single-qubit error after + # it has been constructed and run. + has_2q = any(sp.kind in ('rb2q_layer', 'rb2q') for sp in plan.specs) + if has_2q: + phase1 = [sp for sp in plan.specs + if sp.kind not in ('rb2q_layer', 'rb2q')] + phase2 = [sp for sp in plan.specs + if sp.kind in ('rb2q_layer', 'rb2q')] + if phase1: + return _run_phased(plan, phase1, phase2) + chunks = split_for_submission(plan, plan.shots) + merged = {} + notices = [] + collected = [] + spec_offset = 0 + + with api.Session(backend=backend) as session: + sampler = (sampler_factory(session) if sampler_factory is not None + else api.SamplerV2(mode=session)) + for chunk in chunks: + experiments = [(spec, _build_experiment(spec, api)) + for spec in chunk.specs] + batch = api.BatchExperiment( + [exp for _s, exp in experiments], flatten_results=False) + with warnings.catch_warnings(): + # qiskit-experiments' RB analysis divides by a per-Clifford + # gate count that is zero for any basis gate the sequences + # never use, emitting one RuntimeWarning per such gate. + # It is library-side and harmless, but it floods the + # notebook. Scoped to that module only: our own warnings, + # and every other library's, still surface. + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, + module=r'.*qiskit_experiments.*rb_analysis.*') + data = batch.run(sampler=sampler, shots=plan.shots) + job_ids = _job_ids_of(data) + if on_jobs is not None: + try: + on_jobs(chunk.index, job_ids, 'submitted') + except Exception: + _log.debug('job-id callback failed', exc_info=True) + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, + module=r'.*qiskit_experiments.*rb_analysis.*') + data.block_for_results() + + try: + job_ids = _check_chunk_status(data, chunk.index) + except BenchmarkRunError as exc: + if len(chunks) == 1: + exc.expdata = collected + [data] + raise + # Partial failure: keep what the other chunks produced and + # surface this one loudly rather than losing the whole run. + notices.append( + f'chunk {chunk.index + 1}/{len(chunks)} failed: {exc}') + spec_offset += len(chunk.specs) + continue + if on_jobs is not None: + try: + on_jobs(chunk.index, job_ids, _status_name(data)) + except Exception: + _log.debug('job-id callback failed', exc_info=True) + + for local_idx, (spec, _exp) in enumerate(experiments): + idx = spec_offset + local_idx + try: + merged[idx] = list(_iter_analysis_results( + data.child_data(local_idx))) + except Exception as exc: # noqa: BLE001 - per-experiment + _log.warning('benchmark: no results for %s %s: %s', + spec.kind, spec.qubits, exc) + merged[idx] = None + collected.append(data) + spec_offset += len(chunk.specs) + + if notices: + merged['_notices'] = notices + # The ExperimentData objects live on the runner, not in the result + # mapping: `results_to_epoch` iterates that mapping by spec index, and + # a stray key there would look like an extra experiment. + _runner.last_expdata = collected + return merged + + def _run_phased(plan, phase1, phase2, session=None, sampler=None): + """Phase 1 (readout/T1/T2/1Q RB) then phase 2 (2Q RB), one session. + + Phase 1's per-qubit EPGs are handed to phase 2's analyses so the + two-qubit numbers are 1Q-subtracted. If phase 1 yields no EPGs the run + still proceeds — the values are then comparable only in relative + terms, which `consistency_stats` detects and flags. + """ + merged = {} + collected = [] + context = {'epg_results': {}, 'epg_1q': {}, 'notices': []} + index_of = {id(sp): i for i, sp in enumerate(plan.specs)} + phase_no = [0] + + def _submit(specs, session, sampler): + experiments = [(sp, _build_experiment(sp, api, context)) + for sp in specs] + batch = api.BatchExperiment([e for _s, e in experiments], + flatten_results=False) + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, + module=r'.*qiskit_experiments.*rb_analysis.*') + data = batch.run(sampler=sampler, shots=plan.shots) + job_ids = _job_ids_of(data) + if on_jobs is not None: + try: + on_jobs(phase_no[0], job_ids, 'submitted') + except Exception: + _log.debug('job-id callback failed', exc_info=True) + data.block_for_results() + _check_chunk_status(data, phase_no[0]) + if on_jobs is not None: + try: + on_jobs(phase_no[0], _job_ids_of(data), + _status_name(data)) + except Exception: + _log.debug('job-id callback failed', exc_info=True) + + # A DONE job can still have had every analysis callback raise. + # Surfacing that is the difference between "the fits failed, here + # is why" and six bland "no results returned" notices. + failures = collect_analysis_errors(data) + summary = summarise_analysis_errors(failures) + if summary: + context['notices'].append(f'phase {phase_no[0] + 1}: {summary}') + phase_no[0] += 1 + collected.append(data) + for local_idx, (sp, _exp) in enumerate(experiments): + try: + merged[index_of[id(sp)]] = list( + _iter_analysis_results(data.child_data(local_idx))) + except Exception as exc: # noqa: BLE001 - per-experiment + _log.warning('benchmark: no results for %s: %s', + sp.kind, exc) + merged[index_of[id(sp)]] = None + return data + + import contextlib as _ctxlib + # An already-open session is reused (the calibration check drives two + # arms through ONE session so the whole check costs one reservation); + # otherwise this opens its own. + own_session = session is None + ctx_mgr = (api.Session(backend=backend) if own_session + else _ctxlib.nullcontext(session)) + with ctx_mgr as session: + if sampler is None: + sampler = (sampler_factory(session) + if sampler_factory is not None + else api.SamplerV2(mode=session)) + _submit(phase1, session, sampler) + + # Harvest the 1Q EPG RESULT OBJECTS before building the + # two-qubit experiments: the analysis needs the results, not + # their values (see harvest_epg_results). + for sp in phase1: + if sp.kind != 'rb1q': + continue + entry = merged.get(index_of[id(sp)]) or [] + harvest = harvest_epg_results(entry) + context['epg_results'].update(harvest.results) + context.setdefault('_epg_rejected', {}).update( + harvest.rejected) + harvested = {} + _collect_rb1q(entry, sp, [], harvested) + context['epg_1q'].update(harvested.get('epg_1q', {})) + + if not context['epg_results']: + context['notices'].append( + 'No 1Q results \u2014 two-qubit errors are not ' + '1Q-subtracted and read high') + if phase2: + _submit(phase2, session, sampler) + + tally = epg_tally_notice(context) + if tally: + context['notices'].append(tally) + if context['notices']: + merged['_notices'] = list(context['notices']) + _runner.last_expdata = collected + return merged + + def _run_in_session(plan, session, sampler): + """Run one plan inside a caller-owned session. Both arms of the + calibration check go through here, so each gets its own phase-1 1Q RB + and therefore its own subtraction, while sharing one reservation.""" + phase1 = [sp for sp in plan.specs + if sp.kind not in ('rb2q_layer', 'rb2q')] + phase2 = [sp for sp in plan.specs + if sp.kind in ('rb2q_layer', 'rb2q')] + return _run_phased(plan, phase1, phase2, session, sampler) + + _runner.run_in_session = _run_in_session + _runner.api = api + _runner.last_expdata = [] + return _runner + + +def make_calibration_check_runner(backend, on_jobs=None, + sampler_factory=None): + """Run both calibration-check arms in ONE session. + + Returns `runner(plans) -> [raw_parallel, raw_sequential]`. Each arm is a + full plan with its own phase-1 1Q RB, so the subtraction applies to both + and the two numbers are directly comparable — which is the entire point: + an estimator bias moves both arms, crosstalk moves only the parallel one. + """ + inner = make_runtime_runner(backend, on_jobs, sampler_factory) + api = inner.api + + def _run(plans): + out = [] + collected = [] + with api.Session(backend=backend) as session: + sampler = (sampler_factory(session) if sampler_factory is not None + else api.SamplerV2(mode=session)) + for plan in plans: + out.append(inner.run_in_session(plan, session, sampler)) + collected.extend(getattr(inner, 'last_expdata', []) or []) + _run.last_expdata = collected + return out + + _run.last_expdata = [] + return _run + + +def _safe_analysis_results(expdata): + """`analysis_results()` without tripping the deprecation. + + Leaving `dataframe` unset is deprecated as of qiskit-experiments 0.9, and + under `-W error` that DeprecationWarning is RAISED. Both the parser and + the raw dump guard their calls with `except Exception`, so the warning + was being swallowed and reported as "no results returned" for every + experiment — a healthy run looking exactly like the failed one. Ask for + the DataFrame explicitly; older versions have no such keyword, hence the + TypeError fallback. + """ + if expdata is None: + return None + for attempt in ({'dataframe': True}, {}): + try: + return expdata.analysis_results(**attempt) + except TypeError: + continue + except Exception: + return None + return None + + +def _iter_analysis_results(expdata): + """Yield analysis results from either shape qiskit-experiments returns. + + `ExperimentData.analysis_results()` returns a list of `AnalysisResult` + objects in older versions and a pandas DataFrame in newer ones (with + `dataframe=True` becoming the default). Normalising here means the parser + below never has to know which is installed — and a version bump cannot + silently empty every epoch again. + + Recurses into `child_data` so a composite experiment's results are found + whether they were flattened to the top or left nested. + """ + if expdata is None: + return + + # Ask for the DataFrame explicitly. Leaving `dataframe` unset is + # deprecated as of qiskit-experiments 0.9, and under `-W error` that + # DeprecationWarning is raised as an exception inside the per-experiment + # guard below — which then reported a perfectly good run as "no results + # returned" for every experiment. Older versions have no such keyword, + # hence the TypeError fallback. + results = _safe_analysis_results(expdata) + + for item in _normalise_results(results): + yield item + + # Nested composites: look one level down too. + try: + children = list(expdata.child_data()) + except Exception: + children = [] + for child in children: + for item in _iter_analysis_results(child): + yield item + + +def _normalise_results(results): + """List / DataFrame / None → a flat list of result-like objects.""" + if results is None: + return [] + # DataFrame: has .itertuples and .columns + if hasattr(results, 'itertuples') and hasattr(results, 'columns'): + out = [] + for row in results.itertuples(index=False): + # The column is `components` in qiskit-experiments 0.10 and + # `device_components` in the legacy object form. Reading only the + # latter yielded None for every row, so nothing could be matched + # to a qubit and every epoch came back empty. + components = getattr(row, 'components', None) + if components is None: + components = getattr(row, 'device_components', None) + out.append(SimpleNamespace( + name=getattr(row, 'name', None), + value=getattr(row, 'value', None), + device_components=list(components or []), + quality=getattr(row, 'quality', None))) + return out + if isinstance(results, (list, tuple)): + return list(results) + return [results] + + +def _components_to_qubits(item, fallback=()): + """Physical qubit ids an analysis result refers to. + + `device_components` entries are `Qubit(3)`-style objects or their string + form; both are handled, because which one appears depends on the version + and on whether the results came back as a DataFrame. + """ + raw = getattr(item, 'device_components', None) + if not raw: + raw = getattr(item, 'qubits', None) + out = [] + for component in (raw or []): + if isinstance(component, (int, np.integer)): + out.append(int(component)) + continue + # `Qubit(3)` exposes .index as an int. Careful: str also has an + # `.index` ATTRIBUTE — the method — so the type check matters. + index = getattr(component, 'index', None) + if isinstance(index, (int, np.integer)): + out.append(int(index)) + continue + text = str(component) + digits = ''.join(ch for ch in text if ch.isdigit()) + if digits: + out.append(int(digits)) + return out or list(fallback) + + +# ── Results → epoch ───────────────────────────────────────────────── + +def _summarise_failures(notices, label, failures, total): + """One line per failure KIND, never a list of every index. + + The 20 Sept run emitted a notice naming all 156 qubit indices verbatim, + which is unreadable and hides the one thing that matters — the error. Up + to five failures are still named individually, because at that size the + indices are the useful part. + """ + if not failures: + return + if len(failures) <= 5: + for element, reason in failures: + notices.append(f'{label} q{element}: {reason}; kept reported value') + return + reasons = {} + for _element, reason in failures: + reasons[reason] = reasons.get(reason, 0) + 1 + common = max(reasons.items(), key=lambda kv: kv[1])[0] + notices.append(f'{label}: {len(failures)}/{total} failed — {common}' + + ('' if len(reasons) == 1 + else f' (+{len(reasons) - 1} other error(s))') + + '; kept reported values') + + +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 = [] + extra = {} + + 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}: no results returned for ' + f'{len(spec.qubits)} qubit(s), 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_layer': + _apply_rb2q_layer(entry, spec, gate_props, e_mask, edge_index, + two_q_key, notices) + elif spec.kind == 'rb2q': # legacy single-pair spec + _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': + _collect_rb1q(entry, spec, notices, extra) + 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') + + run_notices = (raw.get('_notices') if isinstance(raw, dict) else None) or [] + for note in run_notices: + notices.append(str(note)) + + planned = plan_planned_count(plan) + _assert_attribution(raw, plan, q_mask, e_mask, notices) + return MeasuredEpoch(qubit_props, gate_props, q_mask, e_mask, + plan.level, when, notices, planned_count=planned, + extra=extra) + + +def _assert_attribution(raw, plan, q_mask, e_mask, notices): + """Never return "nothing measured" when results were in fact present. + + The failure this guards against: the analysis produced 348 EPG_cz plus + T1/T2/readout for 156 qubits, and the epoch still came back (0, 0) with + an EMPTY notice list — so the UI reported "no usable measurements" with + nothing to explain it, while the raw dump held everything. Silence there + is worse than a wrong number, because it looks like an answer. + + If any analysis result was seen but none was attributed to a target, say + how many and name the most likely reason. + """ + found = 0 + for key, entry in (raw or {}).items(): + if not isinstance(key, int): + continue + if isinstance(entry, (list, tuple)): + found += len(entry) + elif entry is not None: + found += 1 + if not found: + return + if q_mask.any() or e_mask.any(): + return + + if not plan.specs: + reason = 'the plan being folded has no experiments' + elif not plan.targets.qubits and not plan.targets.edges: + reason = 'the plan has no targets to attribute results to' + else: + _log.warning( + 'attribution failed: no result qubit/edge matched the plan ' + 'targets. Check the edge orientation against state.edges_list ' + 'and that the plan matches the run that produced these results.') + reason = 'plan/run mismatch' + notices.append(f'Results found but none matched the targets — ' + f'{reason}') + + +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: no assignment matrix for ' + f'{len(spec.qubits)} qubit(s), kept reported values') + return + failures = [] + for qubit, matrix in matrices.items(): + if not (0 <= qubit < n_q): + continue + try: + value = _readout_error_from_matrix(matrix) + if not np.isfinite(value) or not (0.0 <= value <= _READOUT_MAX): + raise ValueError( + f'implausible readout error {value:.3g} ' + f'(expected 0-{_READOUT_MAX:g})') + arr[qubit] = value + q_mask[qubit] = True + except Exception as exc: # noqa: BLE001 - per element + failures.append((qubit, str(exc))) + _summarise_failures(notices, 'readout', failures, len(matrices)) + + +def _readout_matrices(entry, spec): + """Map physical qubit → 2x2 assignment matrix from a readout result. + + `LocalReadoutError` returns ONE analysis result for the whole target set, + whose value is a `LocalReadoutMitigator`. Its `assignment_matrix` is a + METHOD taking the qubits to report on — reading it as an attribute yields + the bound method itself, and `float()` on that raised + + float() argument must be a string or a real number, not 'method' + + for all 156 qubits on the 20 Sept run. The same class of bug as reading + `str.index` as an integer. Attributes are tried too, since older versions + and some stand-ins expose a plain array. + """ + out = {} + items = entry if isinstance(entry, (list, tuple)) else [entry] + for item in items: + value = getattr(item, 'value', item) + qubits = _components_to_qubits(item, fallback=spec.qubits) + accessor = getattr(value, 'assignment_matrix', None) + if accessor is None and isinstance(value, dict): + accessor = value.get('assignment_matrix') + + if callable(accessor): + # The live shape: one mitigator, queried per qubit. + for q in qubits: + try: + matrix = np.asarray(accessor([int(q)]), dtype=float) + except Exception: + try: + matrix = np.asarray(accessor(int(q)), dtype=float) + except Exception: + continue + if matrix.shape == (2, 2): + out[int(q)] = matrix + continue + + if accessor is None: + continue + matrix = np.asarray(accessor, 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()}: no results for {len(spec.qubits)} ' + f'qubit(s), kept reported values') + return + failures = [] + for item in items: + # Identify the qubit from device_components. Falling back to + # spec.qubits[0] wrote all 156 of the 20 Sept T1 results onto qubit 0, + # which is why that run reported "measured qubits: 1". + qubits = _components_to_qubits(item) + if not qubits: + continue + qubit = int(qubits[0]) + if not (0 <= qubit < n_q): + continue + try: + seconds = _result_value(item) + micros = seconds * 1e6 # data.py stores µs + if not np.isfinite(micros) or not (0 < micros < _COHERENCE_MAX_US): + raise ValueError( + f'implausible {key} {micros:.3g} us ' + f'(expected 0-{_COHERENCE_MAX_US:g})') + arr[qubit] = micros + q_mask[qubit] = True + except Exception as exc: # noqa: BLE001 - per element + failures.append((qubit, str(exc))) + _summarise_failures(notices, key.upper(), failures, len(items)) + + +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 _apply_rb2q_layer(entry, spec, gate_props, e_mask, edge_index, two_q_key, + notices): + """Fold ONE layer's parallel 2Q RB: many pairs, one experiment. + + Each analysis result names its own qubits through `device_components`, so + results are matched to edges by those components rather than by position — + a ParallelExperiment gives no ordering guarantee worth relying on. + """ + pairs = [tuple(p) for p in (spec.params.get('pairs') or [])] + if two_q_key is None: + notices.append(f'{spec.kind}: no two-qubit error array to update') + return + arr = gate_props.get(two_q_key) + if arr is None: + return + + items = entry if isinstance(entry, (list, tuple)) else [entry] + by_pair = {} + for item in items: + name = str(getattr(item, 'name', '') or '') + if not name.upper().startswith(RESULT_EPG_PREFIXES): + continue + qubits = tuple(sorted(_components_to_qubits(item))) + if len(qubits) != 2: + continue + by_pair.setdefault(qubits, item) + + for pair in pairs: + item = by_pair.get(tuple(sorted(pair))) + # `a or b` is wrong here: edge index 0 is falsy, so the first edge + # of every device silently fell through to the reversed lookup and + # was reported "not in the device map". Test the sentinel explicitly. + idx = edge_index.get(pair) + if idx is None: + idx = edge_index.get((pair[1], pair[0])) + if idx is None or not (0 <= idx < len(arr)): + notices.append(f'{list(pair)}: edge not in the device map, skipped') + continue + if item is None: + notices.append(f'{list(pair)}: no RB result in the layer, ' + f'kept reported value') + continue + try: + epg = _result_value(item) + 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 _collect_rb1q(entry, spec, notices, extra): + """Per-qubit 1Q EPGs, and a notice that counts QUBITS. + + `StandardRB` reports one result per (qubit, basis gate) — rz, sx, x — so + the 20 Sept run saw 468 results for 156 qubits and announced "median EPG + over 624 qubit(s)". The per-gate values are averaged per qubit here and + kept in `epoch.extra['epg_1q']`, which is what the 2Q RB analysis needs to + subtract single-qubit error from the Clifford decay (see Part B). + + These are NOT counted as measured qubit properties: the reported arrays + carry per-gate errors separately, and overwriting one of them with an RB + average would mix two estimators in the same column. + """ + items = entry if isinstance(entry, (list, tuple)) else [entry] + per_qubit = {} + for item in items: + name = str(getattr(item, 'name', '') or '') + if not name.upper().startswith('EPG'): + continue + qubits = _components_to_qubits(item) + if len(qubits) != 1: + continue + try: + value = _result_value(item) + except Exception: + continue + if np.isfinite(value) and value >= 0: + per_qubit.setdefault(int(qubits[0]), []).append(float(value)) + + if not per_qubit: + notices.append(f'1Q RB: no usable results for {len(spec.qubits)} ' + f'qubit(s)') + return + + averaged = {q: float(np.mean(v)) for q, v in per_qubit.items()} + # Same bound as the forwarding path: an implausible EPG must not be + # recorded as if it were a measurement. + implausible = {q: v for q, v in averaged.items() if not _plausible_epg(v)} + averaged = {q: v for q, v in averaged.items() if _plausible_epg(v)} + if implausible: + notices.append( + f'1Q RB: {len(implausible)} qubit(s) returned an implausible EPG ' + f'(>= {_EPG_1Q_MAX:g}) and were dropped: ' + + ', '.join(f'q{q}={v:.2g}' for q, v in + sorted(implausible.items())[:6])) + if not averaged: + notices.append(f'1Q RB: no plausible results for {len(spec.qubits)} ' + f'qubit(s)') + return + extra.setdefault('epg_1q', {}).update(averaged) + notices.append( + f'1Q RB: median EPG {np.median(list(averaged.values())):.2e} over ' + f'{len(averaged)} qubit(s)') + + +# ── Consistency against the reported calibration ─────────────────── +# +# The 20 Sept run measured 351 edges at a median 4.03e-3 against a reported +# median 1.43e-3: 2.8x worse across the board, 238 edges more than 2x worse, +# only 4 better. Real drift does not move an entire chip uniformly in one +# direction — that signature is an ESTIMATOR MISMATCH. Believing those +# absolute numbers would have made every layout look bad by the same factor, +# which changes no ranking but corrupts every fidelity estimate shown. +# +# So a measured epoch is now checked against the reported one before it is +# trusted, and when the medians disagree badly the values are rescaled to the +# reported median. Rescaling preserves every per-element RATIO, which is where +# the real signal lives: on 20 Sept the outliers (edge 190: 6.6e-2 -> 0.75, a +# collapsed coupler) were genuine and are exactly what the feature is for. + +#: Median ratio outside this band means "do not trust the absolute values". +CONSISTENCY_BAND = (0.5, 2.0) + + +def _median_ratio_stats(measured, reported, mask): + measured = np.asarray(measured, dtype=float) + reported = np.asarray(reported, dtype=float) + mask = np.asarray(mask, dtype=bool) + n = min(len(measured), len(reported), len(mask)) + sel = (mask[:n] & np.isfinite(measured[:n]) & np.isfinite(reported[:n]) + & (reported[:n] > 0)) + if not sel.any(): + return None + m, r = measured[:n][sel], reported[:n][sel] + # Nothing was actually written to this property: the mask marks elements + # measured for SOME property, and a device carrying both cz_error and + # rzz_error will have one of them untouched and identical to reported. + # Reporting a x1.00 ratio for it is noise that hides the real offender. + if np.allclose(m, r, rtol=0, atol=0): + return None + ratios = m / r + idx = np.where(sel)[0] + worst = idx[np.argsort(-ratios)][:5] + return { + 'n': int(sel.sum()), + 'median_reported': float(np.median(r)), + 'median_measured': float(np.median(m)), + # Two different statistics, and they differ on skewed data (20 Sept: + # 2.82 vs 2.43). `ratio_of_medians` is what rescaling corrects, so it + # is the one the policy uses; `median_ratio` describes the typical + # element. Both are reported because quoting one as "the" ratio has + # already caused confusion. + 'ratio_of_medians': float(np.median(m) / np.median(r)), + 'median_ratio': float(np.median(ratios)), + 'frac_worse_2x': float((ratios > 2).mean()), + 'frac_better_2x': float((ratios < 0.5).mean()), + 'n_worse_2x': int((ratios > 2).sum()), + 'n_better_2x': int((ratios < 0.5).sum()), + 'top_degradations': [ + {'index': int(i), 'reported': float(reported[i]), + 'measured': float(measured[i]), + 'ratio': float(measured[i] / reported[i])} + for i in worst], + } + + +def consistency_stats(epoch, reported_qubit_props, reported_gate_props): + """Compare a measured epoch with the reported calibration, per property. + + Only measured elements are compared — an unmeasured one still holds the + reported value, so including it would dilute the ratio towards 1 and hide + exactly the offset this is looking for. + """ + out = {} + for key in ('readout_error', 't1', 't2'): + if key in epoch.qubit_props and key in (reported_qubit_props or {}): + stats = _median_ratio_stats(epoch.qubit_props[key], + reported_qubit_props[key], + epoch.measured_qubit_mask) + if stats: + out[key] = stats + for key in ('cz_error', 'rzz_error'): + if key in epoch.gate_props and key in (reported_gate_props or {}): + stats = _median_ratio_stats(epoch.gate_props[key], + reported_gate_props[key], + epoch.measured_edge_mask) + if stats: + out[key] = stats + return out + + +def consistency_offenders(stats, band=CONSISTENCY_BAND): + """Properties whose ratio-of-medians falls outside the trust band.""" + low, high = band + return {k: v for k, v in (stats or {}).items() + if not (low <= v['ratio_of_medians'] <= high)} + + +def consistency_summary(stats, band=CONSISTENCY_BAND): + """One line per property, for the panel.""" + parts = [] + for key, v in (stats or {}).items(): + flag = '' if (band[0] <= v['ratio_of_medians'] <= band[1]) else ' \u26a0' + parts.append(f"{key}: x{v['ratio_of_medians']:.2f} median vs reported " + f"· {v['n_worse_2x']} of {v['n']} >2x worse{flag}") + return ' · '.join(parts) + + +def apply_relative_mode(epoch, reported_qubit_props, reported_gate_props, + stats=None, band=CONSISTENCY_BAND): + """Rescale offending properties so their median matches the reported one. + + Each measured value is multiplied by (reported median / measured median) + for its property. That leaves every per-element ratio untouched — the + collapsed coupler stays 11x worse than its neighbours — while removing the + uniform offset that makes the absolute numbers unusable. Returns the + number of properties rescaled; mutates `epoch` in place and sets + `epoch.relative`. + """ + stats = stats or consistency_stats(epoch, reported_qubit_props, + reported_gate_props) + offenders = consistency_offenders(stats, band) + if not offenders: + return 0 + + rescaled = 0 + for key, v in offenders.items(): + factor = v['median_reported'] / v['median_measured'] \ + if v['median_measured'] else None + if not factor or not np.isfinite(factor): + continue + if key in epoch.qubit_props: + arr = epoch.qubit_props[key] + mask = epoch.measured_qubit_mask[:len(arr)] + elif key in epoch.gate_props: + arr = epoch.gate_props[key] + mask = epoch.measured_edge_mask[:len(arr)] + else: + continue + arr[:len(mask)][mask] = arr[:len(mask)][mask] * factor + rescaled += 1 + epoch.notices.append( + f'{key}: rescaled by x{factor:.3f} to the reported median ' + f'(relative mode; per-element ratios preserved)') + if rescaled: + epoch.relative = True + return rescaled + + +# ── Calibration check: estimator bias vs crosstalk ───────────────── + +def build_calibration_check_plans(targets, n_qubits, coupling_edges, + n_edges=6): + """Two plans over the same few edges: one parallel, one sequential. + + The 20 Sept offset has two plausible causes that a single run cannot + distinguish. An estimator mismatch (the 1Q EPGs not being subtracted from + the Clifford decay) inflates every edge whether or not its neighbours are + being driven. Crosstalk from running many pairs simultaneously only + inflates the parallel case. Measuring the same edges both ways separates + them: if both come back high, it is the estimator; if only the parallel + run is high, it is crosstalk. + + Returns (parallel_plan, sequential_plan), each ~30 circuits plus the 1Q RB + they share. + """ + edges = [tuple(e) for e in (targets.edges or [])][:max(1, int(n_edges))] + qubits = sorted({q for e in edges for q in e}) + subset = Targets(qubits, edges) + + parallel = build_plan(LEVEL_TARGETED, subset, n_qubits, coupling_edges) + + # Sequential: one pair per layer, so nothing runs alongside anything else. + seq_specs = [] + for spec in parallel.specs: + if spec.kind != 'rb2q_layer': + seq_specs.append(spec) + continue + for i, pair in enumerate(spec.params['pairs']): + params = dict(spec.params) + params['pairs'] = [tuple(pair)] + seq_specs.append(ExperimentSpec('rb2q_layer', tuple(pair), params, + len(seq_specs) + i)) + sequential = parallel._replace(specs=seq_specs) + return parallel, sequential + + +#: Marks a submission record as a calibration check rather than a benchmark. +RECORD_KIND_BENCHMARK = 'benchmark' +RECORD_KIND_CALIBRATION_CHECK = 'calibration_check' + +#: A calibration check needs enough edges for the parallel arm to mean +#: something; below this the two arms are nearly the same experiment. +CALIBRATION_CHECK_EDGES = 6 + + +def calibration_check_table_html(table, esc=str): + """The verdict table, as the panel renders it under the status.""" + if not table or not table.get('rows'): + return ("
" + "Calibration check produced no comparable edges.
") + + def _ratio(value): + return '—' if value is None else f'×{value:.2f}' + + rows = ''.join( + f"{r['edge'][0]}–{r['edge'][1]}" + f"{r['reported']:.3e}" + f"{r['parallel']:.3e}" + f"" + f"{r['sequential']:.3e}" + for r in table['rows']) + return ( + "
" + "🔬 Calibration check
" + "" + "" + "" + "" + "" + f"{rows}
edgereportedparallelsequential
" + f"median vs reported — parallel {_ratio(table['ratio_parallel'])}, " + f"sequential {_ratio(table['ratio_sequential'])}
" + f"{esc(table['verdict'])}
") + + +def calibration_check_table(edges, reported, parallel_epoch, + sequential_epoch, gate_key='cz_error'): + """Rows of (edge, reported, parallel, sequential) plus the two ratios.""" + rows = [] + par = parallel_epoch.gate_props.get(gate_key) + seq = sequential_epoch.gate_props.get(gate_key) + rep = np.asarray(reported, dtype=float) + index = {tuple(sorted(e)): i for i, e in enumerate(edges)} + # ONLY the edges this check actually measured. An unmeasured edge still + # holds its reported value, so including the rest of the device dragged + # both medians back to the reported one and every check read "x1.00, + # consistent" however biased the measured edges were. + par_mask = np.asarray(parallel_epoch.measured_edge_mask, dtype=bool) + seq_mask = np.asarray(sequential_epoch.measured_edge_mask, dtype=bool) + par_vals, seq_vals, rep_vals = [], [], [] + for edge, i in sorted(index.items(), key=lambda kv: kv[1]): + if par is None or seq is None or i >= len(rep): + continue + if i >= len(par_mask) or i >= len(seq_mask): + continue + if not (par_mask[i] and seq_mask[i]): + continue + rows.append({'edge': edge, 'reported': float(rep[i]), + 'parallel': float(par[i]), 'sequential': float(seq[i])}) + rep_vals.append(rep[i]) + par_vals.append(par[i]) + seq_vals.append(seq[i]) + + def _ratio(values): + if not values or not rep_vals or np.median(rep_vals) == 0: + return None + return float(np.median(values) / np.median(rep_vals)) + + return { + 'rows': rows, + 'ratio_parallel': _ratio(par_vals), + 'ratio_sequential': _ratio(seq_vals), + 'verdict': _check_verdict(_ratio(par_vals), _ratio(seq_vals)), + } + + +def _check_verdict(ratio_parallel, ratio_sequential): + """Read the two ratios into a one-line conclusion.""" + if ratio_parallel is None or ratio_sequential is None: + return 'inconclusive (a run produced no usable values)' + low, high = CONSISTENCY_BAND + par_off = not (low <= ratio_parallel <= high) + seq_off = not (low <= ratio_sequential <= high) + if par_off and seq_off: + return ('Estimator bias: both arms offset \u2014 single-qubit ' + 'error is being counted as two-qubit error') + if par_off and not seq_off: + return ('crosstalk: only the parallel run is offset, so driving ' + 'neighbouring pairs together is inflating the error') + if seq_off and not par_off: + return 'unexpected: the sequential run is offset but the parallel one is not' + return 'consistent: both runs agree with the reported calibration' + + +# ── 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 + mode = ', relative' if getattr(epoch, 'relative', False) else '' + state.calibration_data_label = ( + f'{state.active_backend_name} — measured {epoch.time_label()} ' + f'(L{epoch.level}{mode}, {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 _jsonable_consistency(stats): + out = {} + for key, value in (stats or {}).items(): + out[key] = {k: (list(v) if isinstance(v, (list, tuple)) else v) + for k, v in (value or {}).items()} + return out + + +def _jsonable_extra(extra): + out = {} + for key, value in (extra or {}).items(): + if isinstance(value, dict): + out[key] = {str(k): (float(v) if isinstance(v, (int, float)) + else v) + for k, v in value.items()} + else: + out[key] = value + return out + + +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), + # Persisted so a saved epoch can be read back for what it IS: + # without these, a rescaled epoch reloaded as `relative=None` + # and looked like raw measured values. + 'relative': bool(getattr(epoch, 'relative', False)), + 'planned_count': list(getattr(epoch, 'planned_count', (0, 0))), + 'consistency': _jsonable_consistency( + getattr(epoch, 'consistency', None)), + 'extra': _jsonable_extra(getattr(epoch, 'extra', None)), + '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'), + planned_count=tuple(data.get('planned_count') or (0, 0)), + extra={k: {int(q): float(x) for q, x in v.items()} + if k == 'epg_1q' and isinstance(v, dict) else v + for k, v in (data.get('extra') or {}).items()}, + consistency=data.get('consistency'), + relative=bool(data.get('relative', False))) + 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 _stamp_for(when): + return time.strftime('%Y%m%dT%H%M%S', time.localtime(when)) + + +def jobs_path(backend_name, when): + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{_stamp_for(when)}_jobs.json') + + +def raw_path(backend_name, when): + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{_stamp_for(when)}_raw.json') + + +def _write_json(path, payload): + try: + dirn = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(dir=dirn, suffix='.tmp') + try: + with os.fdopen(fd, 'w', encoding='utf-8') as fh: + _json.dump(payload, fh, default=str) + os.replace(tmp, path) + except Exception: + try: + os.remove(tmp) + except OSError: + pass + raise + return path + except Exception as exc: # noqa: BLE001 - diagnostic only + _log.warning('Failed to write %s: %s', path, exc) + return None + + +def save_job_record(backend_name, when, plan, shots=None, session_id=None, + chunks=None, jobs=None, statuses=None, + kind=RECORD_KIND_BENCHMARK, arms=None): + """Persist what was submitted, as soon as it is known. + + Written at submission rather than at completion, because the run that + motivated this file never completed: the job was rejected and there was no + record of what had been sent. With this, a failed or interrupted run can + still be diagnosed — and, via `reanalyze_from_jobs`, recovered without + spending QPU time again. + """ + shots = shots or plan.shots + payload = { + 'when': when, + # 'benchmark' or 'calibration_check'. The latter measures the + # INSTRUMENT, not the device, so it never yields an epoch — and + # Reanalyze needs to know which it is replaying. + 'kind': kind, + 'arms': arms or [], + 'level': plan.level, + 'shots': shots, + 'circuits': plan_circuit_count(plan), + 'total_shots': plan_shots(plan, shots), + 'session_id': session_id, + 'targets': {'qubits': list(plan.targets.qubits), + 'edges': [list(e) for e in plan.targets.edges]}, + 'specs': [{'kind': s.kind, 'qubits': list(s.qubits), + 'layer': s.layer, 'params': _jsonable(s.params)} + for s in plan.specs], + 'chunks': [{'index': c.index, 'circuits': c.circuits, + 'shots': c.shots, + 'kinds': [s.kind for s in c.specs]} + for c in (chunks or split_for_submission(plan, shots))], + 'jobs': dict(jobs or {}), + 'statuses': dict(statuses or {}), + } + return _write_json(jobs_path(backend_name, when), payload) + + +def _jsonable(params): + out = {} + for key, value in (params or {}).items(): + if isinstance(value, (list, tuple)): + out[key] = [list(v) if isinstance(v, tuple) else v for v in value] + else: + out[key] = value + return out + + +def latest_job_record(backend_name): + """The most recent replayable run for a backend, or None. + + Deliberately NOT "the newest _jobs.json". Records were only written from + v3.1 onward, and only the non-phased runner wrote them before that — so + the newest record on disk could be an OLD run while a newer one had left + only a raw dump. That is what happened on 20 Sept: the panel kept + replaying the 12:38 single-batch run (one job, no 1Q phase, hence no + subtraction and a cz_error of x2.85) while the 13:08 two-phase run sat + beside it, reachable only through its raw dump. + + So: consider every run that has EITHER a job record or a raw dump, take + the newest by timestamp, and recover the per-phase job ids from the dump + when the record is absent or single-phase. + """ + try: + dirn = _measured_dir(backend_name) + names = os.listdir(dirn) + except Exception: + _log.debug('no cache dir for %s', backend_name, exc_info=True) + return None + + runs = {} + for name in names: + if not name.startswith(_MEASURED_PREFIX): + continue + if name.endswith('_jobs.json'): + stamp = name[len(_MEASURED_PREFIX):-len('_jobs.json')] + runs.setdefault(stamp, {})['jobs_file'] = name + elif name.endswith('_rean.json'): + continue # a replay, not a submission + elif name.endswith('_raw.json'): + stamp = name[len(_MEASURED_PREFIX):-len('_raw.json')] + runs.setdefault(stamp, {})['raw_file'] = name + if not runs: + return None + + loaded = [] + for stamp in sorted(runs, reverse=True): + record = _load_run(dirn, stamp, runs[stamp]) + if record: + loaded.append((stamp, record)) + + # Drop replays. A reanalysis dumped before this version was written as a + # plain `_raw.json`, so it looks like the newest run — but it executed + # nothing and its job ids belong to an OLDER submission. Any run whose + # ids are all claimed by something earlier is therefore a replay of it, + # and replaying the replay would keep resurrecting the wrong run. + def _ids_of(rec): + return {j for ids in (rec.get('jobs') or {}).values() for j in ids} + + for index, (stamp, record) in enumerate(loaded): + ids = _ids_of(record) + if not ids: + continue + older = set() + for _s, other in loaded[index + 1:]: + older |= _ids_of(other) + if ids <= older and older: + record['_is_replay'] = True + continue + return record + + return loaded[0][1] if loaded else None + + +def _load_run(dirn, stamp, files): + """One run's record, with phase-grouped job ids where recoverable.""" + record = None + jobs_file = files.get('jobs_file') + if jobs_file: + try: + with open(os.path.join(dirn, jobs_file), 'r', + encoding='utf-8') as fh: + record = _json.load(fh) + record['_path'] = os.path.join(dirn, jobs_file) + except Exception: + record = None + + raw_file = files.get('raw_file') + raw_path_full = os.path.join(dirn, raw_file) if raw_file else None + phases = [] + if raw_path_full: + try: + phases = [p for p in job_ids_from_raw(raw_path_full) if p] + except Exception: + phases = [] + + if record is None: + # Raw-only run: no spec list, so the caller cannot rebuild the plan. + # Still worth returning, so the UI can say WHICH run it cannot + # replay rather than silently reaching for an older one. + if not phases: + return None + return {'_path': raw_path_full, '_stamp': stamp, 'specs': [], + 'jobs': {str(i): ids for i, ids in enumerate(phases)}, + '_raw_path': raw_path_full} + + record['_stamp'] = stamp + record['_raw_path'] = raw_path_full + # A record written before the phased runner recorded only one group; the + # raw dump knows better, so prefer its phase split when it has more. + recorded = [v for v in (record.get('jobs') or {}).values() if v] + if len(phases) > len(recorded): + record['jobs'] = {str(i): ids for i, ids in enumerate(phases)} + record['_phases_from_raw'] = True + return record + + +_MAX_DUMP_ITEMS = 1000 + + +def notices_path(backend_name, when): + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{_stamp_for(when)}_notices.json') + + +def calibration_check_path(backend_name, when): + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{_stamp_for(when)}_calcheck.json') + + +def save_calibration_check(backend_name, when, table): + """Persist the verdict table beside the run's other artifacts.""" + return _write_json(calibration_check_path(backend_name, when), + {'when': when, + 'rows': [{**r, 'edge': list(r['edge'])} + for r in (table or {}).get('rows', [])], + 'ratio_parallel': (table or {}).get('ratio_parallel'), + 'ratio_sequential': (table or {}).get( + 'ratio_sequential'), + 'verdict': (table or {}).get('verdict')}) + + +def save_attempt_notices(backend_name, when, notices): + """Persist an attempt's notices, whatever the outcome. + + Separate from the epoch file because the attempts that most need + explaining are the ones that produce no epoch to attach notices to. + """ + return _write_json(notices_path(backend_name, when), + {'when': when, 'notices': [str(n) for n in + (notices or [])]}) + + +def dump_raw_results(expdata_list): + """Everything an ExperimentData tree holds, as plain JSON-able data. + + Deliberately exhaustive and shape-agnostic: the bug this exists to catch + was a parser looking in the wrong place, so a dump that only recorded what + the parser already understood would have been useless. Values longer than + 1000 entries are truncated. + """ + return {'experiments': [_dump_one(d) for d in (expdata_list or [])]} + + +def _dump_one(expdata, depth=0): + if expdata is None or depth > 6: + return {} + node = { + 'type': type(expdata).__name__, + 'experiment_type': getattr(expdata, 'experiment_type', None), + 'status': _status_name(expdata), + 'job_ids': _job_ids_of(expdata), + 'results': [], + 'errors': None, + 'children': [], + } + try: + errors = expdata.errors() + node['errors'] = str(errors) if errors else None + except Exception: + pass + raw = _safe_analysis_results(expdata) + for item in _normalise_results(raw): + node['results'].append({ + 'name': str(getattr(item, 'name', '') or ''), + 'device_components': [str(c) for c in + (getattr(item, 'device_components', None) + or [])], + 'value': _dump_value(getattr(item, 'value', None)), + }) + try: + for child in list(expdata.child_data()): + node['children'].append(_dump_one(child, depth + 1)) + except Exception: + pass + return node + + +def _dump_value(value): + try: + if hasattr(value, 'nominal_value'): + return float(value.nominal_value) + if isinstance(value, (int, float, str, bool)) or value is None: + return value + if hasattr(value, 'tolist'): + listed = value.tolist() + if isinstance(listed, list) and len(listed) > _MAX_DUMP_ITEMS: + return listed[:_MAX_DUMP_ITEMS] + ['...truncated'] + return listed + if isinstance(value, (list, tuple)): + listed = list(value) + if len(listed) > _MAX_DUMP_ITEMS: + return listed[:_MAX_DUMP_ITEMS] + ['...truncated'] + return listed + return str(value)[:500] + except Exception: + return '' + + +def reanalysis_raw_path(backend_name, when): + return os.path.join(_measured_dir(backend_name), + f'{_MEASURED_PREFIX}{_stamp_for(when)}_rean.json') + + +def save_reanalysis_raw(backend_name, when, expdata_list): + """Dump a REANALYSIS separately from a submission. + + A reanalysis executes nothing; its dump describes jobs that some earlier + run submitted. Writing it as `_raw.json` made it look like the newest + run, so the replay target became an artefact of the previous replay. + """ + return _write_json(reanalysis_raw_path(backend_name, when), + dump_raw_results(expdata_list)) + + +def save_raw_results(backend_name, when, expdata_list): + return _write_json(raw_path(backend_name, when), + dump_raw_results(expdata_list)) + + +def diagnose_raw(path_or_dump): + """Human summary of a raw dump: where the results were, and what failed.""" + dump = path_or_dump + if isinstance(path_or_dump, str): + try: + with open(path_or_dump, 'r', encoding='utf-8') as fh: + dump = _json.load(fh) + except Exception as exc: + return f'Could not read {path_or_dump}: {exc}' + + lines = [] + experiments = (dump or {}).get('experiments') or [] + if not experiments: + return 'Empty dump: no ExperimentData recorded.' + + from collections import Counter + names = Counter() + depth_hits = Counter() + statuses = Counter() + errors = [] + + def _walk(node, depth): + statuses[node.get('status') or '?'] += 1 + if node.get('errors'): + errors.append((depth, node['errors'])) + for result in node.get('results') or []: + names[result.get('name') or '?'] += 1 + depth_hits[depth] += 1 + for child in node.get('children') or []: + _walk(child, depth + 1) + + for exp in experiments: + _walk(exp, 0) + + lines.append(f'{len(experiments)} top-level experiment(s).') + lines.append('Job statuses: ' + ', '.join( + f'{k}={v}' for k, v in statuses.most_common()) or 'none') + if depth_hits: + lines.append('Analysis results by nesting depth: ' + ', '.join( + f'depth {d}: {n}' for d, n in sorted(depth_hits.items()))) + else: + lines.append('NO analysis results at any depth — ' + 'the run produced nothing to parse.') + if names: + lines.append('Result names: ' + ', '.join( + f'{k} x{v}' for k, v in names.most_common(12))) + if errors: + lines.append(f'{len(errors)} node(s) reported errors:') + for depth, text in errors[:5]: + lines.append(f' depth {depth}: {str(text)[:300]}') + return '\n'.join(lines) + + +# ── Reanalysis from job ids (zero QPU) ────────────────────────────── + +def job_ids_from_raw(path_or_dump): + """Job ids per phase, recovered from a raw dump. + + Needed because `_run_phased` did not call the job-id callback until this + version, so the 20 Sept 13:08 run left no `_jobs.json` — but the raw dump + records `job_ids` on every node, so the run is still recoverable. + Returns a list of lists, one per top-level experiment (phase). + """ + dump = path_or_dump + if isinstance(path_or_dump, str): + with open(path_or_dump, 'r', encoding='utf-8') as fh: + dump = _json.load(fh) + + def _ids(node): + out = list(node.get('job_ids') or []) + for child in node.get('children') or []: + out.extend(_ids(child)) + return out + + phases = [] + for experiment in (dump or {}).get('experiments') or []: + seen, ordered = set(), [] + for jid in _ids(experiment): + if jid not in seen: + seen.add(jid) + ordered.append(jid) + phases.append(ordered) + return phases + + +def _initialize_container(experiment, backend, notices=None): + """Build the ExperimentData the way `BaseExperiment.run()` does. + + A composite experiment's results do not live in one flat container: the + analysis calls `CompositeAnalysis._component_experiment_data`, which walks + per-component CHILD containers and the composite metadata that names them. + `run()` creates all of that up front via + `BaseExperiment._initialize_experiment_data()`, before a single circuit is + submitted. + + Reanalysis used to skip that and construct a bare + `ExperimentData(experiment=batch)`, which allocates no children and no + component metadata — so the analysis raised + + AnalysisError: Unable to extract component child experiment data + + `_initialize_experiment_data` is private but has been the stable entry + point for this across versions; the public constructor is kept as a + fallback, and a notice records when the composite metadata still looks + absent so the next failure is legible rather than cryptic. + """ + notices = notices if notices is not None else [] + try: + experiment.backend = backend + except Exception: + pass + + expdata = None + initializer = getattr(experiment, '_initialize_experiment_data', None) + if callable(initializer): + try: + expdata = initializer() + except Exception as exc: # noqa: BLE001 - fall back + notices.append(f'_initialize_experiment_data failed ({exc}); ' + f'falling back to a bare container') + if expdata is None: + from qiskit_experiments.framework import ExperimentData + expdata = ExperimentData(experiment=experiment, backend=backend) + + missing = _missing_composite_metadata(expdata, experiment) + if missing: + _log.warning( + 'reanalysis container is missing composite metadata (%s); ' + 'component results may not be extractable in this ' + 'qiskit-experiments version', ', '.join(missing)) + notices.append('Reanalysis container incomplete \u2014 results may ' + 'be partial') + return expdata + + +#: Keys `CompositeAnalysis` uses to locate a component's child container. The +#: name has moved between versions, so presence of ANY of them is enough. +_COMPOSITE_METADATA_KEYS = ('component_child_index', 'component_types', + 'component_metadata') + + +def _missing_composite_metadata(expdata, experiment): + """Diagnostic: what a composite container should carry but does not. + + Not a hard check — the exact keys differ by version, and this module is + written against several. It exists so that if the container is wrong + again the notice says which piece was absent instead of surfacing a bare + AnalysisError from deep inside the library. + """ + if not getattr(experiment, '_experiments', None): + return [] # not composite; nothing to carry + try: + metadata = dict(expdata.metadata or {}) + except Exception: + return ['metadata unreadable'] + # Only the METADATA is required at initialisation. qiskit-experiments + # 0.10 allocates the child containers later, during add_jobs/analysis, so + # demanding them here produced a false alarm on runs that then worked. + if any(key in metadata for key in _COMPOSITE_METADATA_KEYS): + return [] + return ['/'.join(_COMPOSITE_METADATA_KEYS)] + + +def plan_for_replay(record, backend_name=None, n_qubits=None, + coupling_edges=None): + """The plan to replay, and how it was obtained. + + Returns `(plan, how)` where `how` is 'record' (exact, from the saved spec + list) or 'reconstructed' (a whole-chip Level 3 plan rebuilt from the + device, which is fully determined and so safe to recreate). Runs from + before the spec list was recorded are otherwise unreplayable, and a + Level 1 or 2 run cannot be reconstructed at all because its targets are + not recoverable from the dump. + """ + plan = plan_from_record(record) + if plan is not None: + return plan, 'record' + + level = None + if record: + level = record.get('level') + if level is None and backend_name and record and record.get('_stamp'): + epoch_file = os.path.join(_measured_dir(backend_name), + f"{_MEASURED_PREFIX}{record['_stamp']}.json") + try: + with open(epoch_file, 'r', encoding='utf-8') as fh: + level = _json.load(fh).get('level') + except Exception: + level = None + + if int(level or 0) == LEVEL_FULL and n_qubits and coupling_edges: + return (build_plan(LEVEL_FULL, Targets([], []), n_qubits, + coupling_edges), 'reconstructed') + return None, None + + +def plan_from_record(record): + """Rebuild the exact `BenchmarkPlan` a saved submission used. + + Reanalysis must replay the plan that PRODUCED the jobs, not whatever the + UI's target selector happens to point at now. Using the live selector + meant that reanalysing with the selector on "Current layout(s)" and + nothing placed built a plan with ZERO specs: no experiment to rebuild, no + result to attribute, no notice to emit — a silent (0, 0) that looked like + "the jobs contained nothing" when the jobs in fact contained everything. + """ + if not record: + return None + specs = [] + for raw_spec in record.get('specs') or []: + params = dict(raw_spec.get('params') or {}) + if 'pairs' in params: + params['pairs'] = [tuple(p) for p in params['pairs']] + specs.append(ExperimentSpec(raw_spec['kind'], + tuple(raw_spec.get('qubits') or []), + params, int(raw_spec.get('layer') or 0))) + if not specs: + return None + targets_raw = record.get('targets') or {} + targets = Targets(list(targets_raw.get('qubits') or []), + [tuple(e) for e in (targets_raw.get('edges') or [])]) + return BenchmarkPlan(int(record.get('level') or LEVEL_FULL), specs, + targets, int(record.get('shots') or DEFAULT_SHOTS)) + + +def reanalyze_from_jobs(plan, job_ids, backend, service=None): + """Rebuild the analysis from already-executed jobs. Costs no QPU time. + + qiskit-experiments runs its fits CLIENT-SIDE: the jobs hold the raw + counts, and analysis is pure post-processing. So a run whose fits crashed + — as the 20 Sept two-qubit callbacks did — can be recovered from its job + ids alone, with the corrected options, without re-executing anything. + + `job_ids` may be a flat list (single-phase) or a list of per-phase lists + (as `job_ids_from_raw` returns). The phased form matters: the plan is + submitted as non-2Q first then 2Q, so the 1Q EPG results must be + harvested from phase 1 and handed to phase 2's analyses exactly as the + live runner does — reanalysing both phases as one batch would reproduce + the un-subtracted numbers. + """ + if not plan.specs: + raise BenchmarkRunError( + "Nothing to reanalyse: this run's plan was not recorded") + api = preload_runtime() + phases_ids = (list(job_ids) if job_ids and isinstance(job_ids[0], (list, tuple)) + else [list(job_ids or [])]) + + has_2q = any(sp.kind in ('rb2q_layer', 'rb2q') for sp in plan.specs) + if has_2q and len(phases_ids) > 1: + groups = [[sp for sp in plan.specs + if sp.kind not in ('rb2q_layer', 'rb2q')], + [sp for sp in plan.specs + if sp.kind in ('rb2q_layer', 'rb2q')]] + else: + groups = [list(plan.specs)] + phases_ids = [[j for ids in phases_ids for j in ids]] + + index_of = {id(sp): i for i, sp in enumerate(plan.specs)} + context = {'epg_results': {}, 'epg_1q': {}, 'notices': []} + merged = {} + collected = [] + + for phase, (specs, ids) in enumerate(zip(groups, phases_ids)): + if not specs: + continue + experiments = [(sp, _build_experiment(sp, api, context)) + for sp in specs] + batch = api.BatchExperiment([e for _s, e in experiments], + flatten_results=False) + jobs = [] + for job_id in ids: + if service is None: + jobs.append(job_id) + continue + try: + jobs.append(service.job(job_id)) + except Exception as exc: # noqa: BLE001 - reported + raise BenchmarkRunError( + f'could not retrieve job {job_id}: {exc}', ids) from exc + + expdata = _initialize_container(batch, backend, context['notices']) + expdata.add_jobs(jobs) + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, + module=r'.*qiskit_experiments.*rb_analysis.*') + batch.analysis.run(expdata, replace_results=True) + expdata.block_for_results() + + failures = summarise_analysis_errors(collect_analysis_errors(expdata)) + if failures: + context['notices'].append(f'phase {phase + 1}: {failures}') + collected.append(expdata) + + for local_idx, (sp, _exp) in enumerate(experiments): + try: + merged[index_of[id(sp)]] = list( + _iter_analysis_results(expdata.child_data(local_idx))) + except Exception: + merged[index_of[id(sp)]] = None + + if phase == 0 and len(groups) > 1: + for sp in specs: + if sp.kind != 'rb1q': + continue + entry = merged.get(index_of[id(sp)]) or [] + harvest = harvest_epg_results(entry) + context['epg_results'].update(harvest.results) + context.setdefault('_epg_rejected', {}).update( + harvest.rejected) + harvested = {} + _collect_rb1q(entry, sp, [], harvested) + context['epg_1q'].update(harvested.get('epg_1q', {})) + + tally = epg_tally_notice(context) + if tally: + context['notices'].append(tally) + elif any(sp.kind in ('rb2q_layer', 'rb2q') for sp in plan.specs): + context['notices'].append( + '1Q EPG subtraction: applied to 0 pairs (single-phase run) ' + '\u2014 two-qubit errors read high') + if context['notices']: + merged['_notices'] = list(context['notices']) + return merged, collected + + +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/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/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 713635b..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 @@ -999,8 +1062,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. """ - # 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/iqmapper/engine_select.py b/iqmapper/engine_select.py new file mode 100644 index 0000000..ff412d3 --- /dev/null +++ b/iqmapper/engine_select.py @@ -0,0 +1,296 @@ +""" +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 +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: + + 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 . 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 + + +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, + } + + +# ── 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/evaluation.py b/iqmapper/evaluation.py new file mode 100644 index 0000000..a1dbaec --- /dev/null +++ b/iqmapper/evaluation.py @@ -0,0 +1,712 @@ +""" +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. +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 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 scorer, +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. 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. + +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()`, +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 --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`; +`--session PATH` names the saved session to take the coupling map from. +""" +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 .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'} + +#: Extension "Export Session" gives a saved session. +SESSION_SUFFIX = '.qpusession.json' + + +# ── 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 + + +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: + """One (date, norb, k) comparison.""" + + __slots__ = ('date', 'norb', 'k', 'vf2_lqs', 'guided_lqs', 'vf2_time', + 'guided_time', 'vf2_scaffolds', 'guided_scaffolds', + '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, hybrid_lqs=None): + 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 + # {guided_max_k: best LQS at this k}, one entry per hybrid threshold. + self.hybrid_lqs = dict(hybrid_lqs or {}) + + @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, 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): + 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}', '', + 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 |' + + 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} |' + 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): + """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, 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 + 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: '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. + 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 " + 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 + 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. + 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(_no_session_message(backend_name, session_dir)) + return Report(backend_name, [], errors, metric, hybrid_ks) + + 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) + 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, + 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 + + +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_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_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 '') + + +def _read_session(path): + """A saved session as a dict. Raises ValueError saying what is wrong.""" + from .export import MAX_IMPORT_BYTES + try: + 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 + 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: + payload = _read_session(path) + except ValueError: + continue + if _session_backend(payload) != str(backend_name): + continue + 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.""" + 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 [] + + 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')) + 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, + {t: _best_lqs(res, k) for t, res in hybrid.items()})) + 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)') + 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') + 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, + scorer=args.scorer, + 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) + + 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/export/autodetect.py b/iqmapper/export/autodetect.py index bef5727..5718d82 100644 --- a/iqmapper/export/autodetect.py +++ b/iqmapper/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 (planned), -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/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/export/scoring.py b/iqmapper/export/scoring.py index 47a3e94..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,119 @@ 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` + 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. + 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. + + 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. @@ -65,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. @@ -113,66 +234,26 @@ 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 - - # 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]))) + if i < len(cz_arr): + gate_edges.append((u_id, v_id, cz_arr[i])) - 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, + unique_couplers(gate_edges), + all_readout=re_arr) 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/guided_search.py b/iqmapper/guided_search.py new file mode 100644 index 0000000..5ab49bc --- /dev/null +++ b/iqmapper/guided_search.py @@ -0,0 +1,813 @@ +""" +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 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. + +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, 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 + `(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 large 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 induced embedding of the (norb, k) template. + + 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. + """ + 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 + 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 + + +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)) + + 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. + + 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. The + two chain heads are never coupled to each other. + """ + 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:]: + 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)) + + _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:]: + 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) + 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`. + + 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) + out = [] + 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)) + + _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 + 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))) + 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. 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; + 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 + + +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, + 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) + # 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] + 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/joint_plan.py b/iqmapper/joint_plan.py new file mode 100644 index 0000000..bfb524d --- /dev/null +++ b/iqmapper/joint_plan.py @@ -0,0 +1,394 @@ +""" +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, 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'] + 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, beam + + +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 _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: + 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), + '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': fields['boundary_couplers'], + 'greedy_total': greedy_plan.score(penalty), + 'greedy_placed': len(greedy_plan.records), + '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, 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, + _complete_plans(ctx, list(joint_beam) + list(greedy_beam))) + + +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'), `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 " + 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/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/multi_sweep.py b/iqmapper/multi_sweep.py new file mode 100644 index 0000000..923d1b1 --- /dev/null +++ b/iqmapper/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/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/plot.py b/iqmapper/plot.py index d4b7d29..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) @@ -543,13 +545,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) @@ -1004,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/iqmapper/props_shim.py b/iqmapper/props_shim.py new file mode 100644 index 0000000..43bc35b --- /dev/null +++ b/iqmapper/props_shim.py @@ -0,0 +1,258 @@ +""" +props_shim.py — Cache-aware props adapter for the multi-QPU scan. + +The ancilla sweep (``ancilla_sweep.sweep_ancilla_layouts``) scores layouts +through a ``BackendProperties``-like object, calling EXACTLY two methods: + +* ``readout_error(qubit)`` -> float +* ``gate_error(gate_name, (u, v))`` -> float (the caller tries both edge + orders, so this need not be direction-aware — but we make it so anyway) + +The app's disk cache (``data.py``) does not store ``BackendProperties`` +objects; it stores extracted numeric dicts: + +* ``qubit_props`` — ``{'readout_error': array[q], 't1': ..., ...}`` + (per-qubit arrays, indexed by physical qubit id) +* ``gate_props`` — ``{'cz_error': array[i], ...}`` (per-EDGE arrays, + positionally parallel to an edge list) + +:class:`CachedPropsShim` adapts those dicts to the two-method surface the +sweep needs. The edge list required to map ``(u, v) -> array index`` is +derived deterministically from the backend coupling map the same way +``data._generate_ibm`` builds ``state.edges_list`` +(``[e for e in coupling_map.get_edges() if e[0] < n and e[1] < n]``), so a +snapshot cached by the normal connect flow reconstructs correctly here. + +:func:`make_scan_get_props` is the ``get_props`` factory the scan injects: +cache-first per backend name, live-fetch-and-cache on a miss. It is NOT the +state-bound ``data.get_props_for_datetime`` (which is pinned to the *current* +backend's name/qubits/edges and would mis-shape a remote backend) — it uses +the per-backend cache primitives instead, which are keyed correctly. +""" + +import logging + +_log = logging.getLogger(__name__) + +# 2Q gate error keys the disk cache actually carries (see +# constants.GATE_PROP_OPTIONS). IBM Heron/Nighthawk use 'cz'. +_DEFAULT_GATE_KEY = 'cz_error' + + +class CachedPropsShim: + """Adapt cached ``(qubit_props, gate_props)`` dicts + an edge list to the + ``readout_error`` / ``gate_error`` surface the sweep consumes. + + Args: + qubit_props: ``{'readout_error': sequence indexed by qubit id, ...}``. + gate_props: ``{'_error': sequence parallel to `edges`, ...}``. + edges: list of ``(u, v)`` pairs, positionally parallel to the + ``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). + + 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, 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] + # 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 + # product_score uses (one value per undirected edge). Lengths are + # guaranteed equal above — no silent truncation. + self._gate = {} + for i, (u, v) in enumerate(self._edges): + self._gate[frozenset((u, v))] = gate_arr[i] + + def readout_error(self, qubit): + try: + return float(self._readout[qubit]) + except (IndexError, KeyError, TypeError) as exc: + raise KeyError( + f"no readout_error for qubit {qubit!r}") from exc + + def gate_error(self, gate_name, pair): + u, v = pair + key = frozenset((int(u), int(v))) + try: + return float(self._gate[key]) + except KeyError as exc: + 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`` — the SAME edge surface as + 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, unique_couplers + 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 + # 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) + + +def _backend_edges(backend): + """Deterministic edge list for a backend, matching data._generate_ibm.""" + raw = list(backend.coupling_map.get_edges()) + n = int(getattr(backend, 'num_qubits', 0) or 0) + if n <= 0 and raw: + n = max(max(e) for e in raw) + 1 + return [(u, v) for (u, v) in raw if u < n and v < n] + + +def make_scan_get_props(state, *, now=None): + """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 (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 + from .auto_lucj import _get_two_q_gate_name + + def _gate_key_for(backend): + name = _get_two_q_gate_name(backend) + return f"{name}_error" if name else _DEFAULT_GATE_KEY + + def _live_stamp(): + dt = now or _dt.now() + return dt.strftime('%H:%M') if hasattr(dt, 'strftime') else str(dt) + + def _from_state(): + """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 + 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) + + # 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) + + # 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( + f"backend.properties() returned None for {backend_name}") + gate_name = _get_two_q_gate_name(backend) or 'cz' + n = int(getattr(backend, 'num_qubits', 0) or 0) + qubit_props = {'readout_error': [props.readout_error(q) for q in range(n)]} + gate_arr = [] + for (u, v) in edges: + try: + gate_arr.append(props.gate_error(gate_name, (u, v))) + except Exception: + try: + gate_arr.append(props.gate_error(gate_name, (v, u))) + except Exception: + gate_arr.append(float('nan')) + gate_props = {f"{gate_name}_error": gate_arr} + # 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: + data._save_calibration(backend_name, lu, qubit_props, gate_props) + 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", + vintage=f"live · {_live_stamp()}", + n_qubits=n or None) + + return get_props diff --git a/iqmapper/qpu_scan.py b/iqmapper/qpu_scan.py new file mode 100644 index 0000000..8a0f09e --- /dev/null +++ b/iqmapper/qpu_scan.py @@ -0,0 +1,281 @@ +""" +qpu_scan.py — Multi-QPU scan engine (pure, synchronous, testable). + +Two concerns, no threads (all async/threading belongs to the 3b UI layer): + +1. :func:`list_scan_targets` — enumerate the account's backends and annotate + each with topology-family + size compatibility for a given ``norb``. +2. :func:`scan_qpus` — run the ancilla sweep on each compatible backend using + injected ``get_backend`` / ``get_props`` callables, isolating per-backend + failures and reporting progress via callback. + +Injection, not coupling +------------------------ +This module never touches the service, the network, or the calibration cache +directly. The caller (3b) injects: + +* ``get_backend(name) -> backend`` — resolve a live backend object. +* ``get_props(backend) -> props`` — a ``BackendProperties``-like object + exposing ``readout_error(q)`` and ``gate_error(name, (u, v))``, obtained + through the SAME cache-aware ``data.py`` path the rest of the app uses + (never a parallel fetch). 3b is responsible for that wiring. + +Family detection +---------------- +Family is read cheaply from ``backend.processor_type`` (or +``configuration().processor_type``) — no calibration fetch. We deliberately do +NOT go through ``constants.resolve_coords`` for the *scan*: it ties a family to +one exact qubit count, which would misreport a same-family-but-wrong-size +backend as "unknown" and erase the distinct "too small" signal. ``resolve_coords`` +remains the authority for actually laying a chip out; here we only need the +family label and the raw qubit count, decoupled. + +Cross-QPU comparability of ``best_lqs`` +--------------------------------------- +``best_lqs`` is the max ``product_score`` across ALL strata of a backend's +sweep. Because the LUCJ zigzag template for a given ``norb`` is identical on +every backend (same chain length, same bridge geometry), these multiplicative +fidelity scores are comparable across QPUs at the same ``(norb, k-range)``. +Caveat: ``product_score`` grows as bridges are removed, so the min-k stratum +always dominates ``best_lqs`` — a single headline number understates the +trade-off. The per-stratum table (rendered in 3b) is the honest view; treat +``best_lqs`` as a coarse "which QPU is worth a closer look" ranking only. +""" + +import contextlib +import logging + +_log = logging.getLogger(__name__) + + +def _detect_family(backend): + """Return the topology family label (e.g. ``'Heron'``) or None. + + Mirrors the family-extraction half of ``constants.resolve_coords`` but + without its qubit-count coupling. Reads ``processor_type`` directly, then + falls back to ``configuration().processor_type``. + """ + proc = getattr(backend, 'processor_type', None) + if proc is None: + cfg = getattr(backend, 'configuration', lambda: None)() + if cfg is not None: + proc = getattr(cfg, 'processor_type', None) + if isinstance(proc, dict): + fam = proc.get('family') + return str(fam) if fam else None + if proc is not None: + # e.g. 'Heron_r3' -> 'Heron' + return str(proc).split('_')[0] or None + return None + + +def _family_key(label): + """Normalise a family label to a comparison key, ignoring revision. + + ``'Heron r3'`` and ``'Heron'`` both key to ``'heron'`` — revisions of the + same family share topology, so they scan together. + """ + if not label: + return None + return str(label).strip().split()[0].lower() + + +def list_scan_targets(state_or_service, norb, *, same_family_as=None, + include_other_families=False): + """List account backends annotated with compatibility for ``norb``. + + Args: + state_or_service: a SessionState (``.active_service`` used) or a + service object directly. Must expose ``backends()`` yielding + backend objects with ``name`` / ``num_qubits`` / ``processor_type``. + norb: number of spatial orbitals for the intended LUCJ layout. + same_family_as: the current backend's family label (as + ``resolve_coords`` reports it, e.g. ``'Heron r3'``). When set and + ``include_other_families`` is False, backends of a different family + are marked ineligible. Cross-family zigzag comparison is + apples-to-oranges, so same-family is the default scope. + include_other_families: widen the scan to every family (and to + unknown-family backends). Each result still carries its family + label so the UI can badge it. + + Returns one dict per backend: + ``{name, family, n_qubits, eligible: bool, reason: str|None}`` + ``reason`` is set only when ``eligible`` is False: + * ``'different family (X)'`` — filtered out by family scope, + * ``'needs >= M qubits, has N'`` — too small to host 2*norb+1 qubits, + * ``'family unknown'`` — detection failed (excluded unless + ``include_other_families``). + """ + service = getattr(state_or_service, 'active_service', None) or state_or_service + if not hasattr(service, 'backends'): + return [] + + # Floor: two chains of `norb` plus at least one bridge (k>=1) — the + # smallest layout the sweep can produce. Topology still has to fit (VF2 + # decides that at sweep time); this is only the cheap size pre-filter. + min_needed = 2 * norb + 1 + + targets = [] + for backend in service.backends(): + name = getattr(backend, 'name', None) + family = _detect_family(backend) + n_qubits = int(getattr(backend, 'num_qubits', 0) or 0) + + eligible = True + reason = None + + if family is None: + if not include_other_families: + eligible = False + reason = 'family unknown' + # else: kept, family stays None so 3b can badge "unknown" + elif (same_family_as is not None and not include_other_families + and _family_key(family) != _family_key(same_family_as)): + eligible = False + reason = f'different family ({family})' + + # Size gate applies to whatever survived the family gate. + if eligible and n_qubits < min_needed: + eligible = False + reason = f'needs >= {min_needed} qubits, has {n_qubits}' + + targets.append({ + 'name': name, + 'family': family, + 'n_qubits': n_qubits, + 'eligible': eligible, + 'reason': reason, + }) + return targets + + +def _best_from_sweep(sweep): + """Return ``(best_product_score, best_k)`` over all strata, or (None, None). + + ``best_k`` is the ancilla count of the highest-``product_score`` candidate. + """ + best_lqs = None + best_k = None + for k, entries in sweep.get('strata', {}).items(): + for entry in entries: + ps = entry['product_score'] + if best_lqs is None or ps > best_lqs: + best_lqs = ps + best_k = k + return best_lqs, best_k + + +def scan_qpus(targets, norb, get_backend, get_props, *, + min_bridges=None, top_n=3, progress_cb=None, sweep_fn=None): + """Run the ancilla sweep on each target backend, isolating failures. + + Args: + targets: entries from :func:`list_scan_targets`. Plain name strings are + also accepted. Entries with ``eligible=False`` are skipped (status + ``'skipped'``); everything else is swept. + norb: spatial orbitals (passed straight to the sweep). + get_backend: ``name -> backend object`` (injected; keeps this module + 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 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:: + + { + 'results': [ {name, family, sweep, best_lqs, best_k, error} ... ], + 'n_scanned', 'n_failed', 'n_skipped' + } + + ``results`` is ordered: successful sweeps first, sorted by ``best_lqs`` + descending; skipped/failed backends last (in input order), with ``error`` + set and ``sweep`` None on failures. + """ + # 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: + return + with contextlib.suppress(Exception): + progress_cb(name, status, detail) + + def _entry(name, family, sweep=None, best_lqs=None, best_k=None, error=None): + return {'name': name, 'family': family, 'sweep': sweep, + 'best_lqs': best_lqs, 'best_k': best_k, 'error': error} + + results = [] + n_scanned = n_failed = n_skipped = 0 + + for target in targets: + if isinstance(target, dict): + name = target.get('name') + family = target.get('family') + eligible = target.get('eligible', True) + else: + name, family, eligible = target, None, True + + if not eligible: + n_skipped += 1 + results.append(_entry(name, family)) + _emit(name, 'skipped', target.get('reason', '') if isinstance(target, dict) else '') + continue + + _emit(name, 'start') + try: + backend = get_backend(name) + props = get_props(backend) + sweep = _sweep( + norb, backend, props, + min_bridges=min_bridges, top_n=top_n) + except Exception as exc: + # PER-BACKEND ISOLATION: one bad backend must not kill the scan. + _log.warning("QPU scan: backend %s failed: %s", name, exc) + n_failed += 1 + results.append(_entry(name, family, error=str(exc))) + _emit(name, 'error', str(exc)) + continue + + best_lqs, best_k = _best_from_sweep(sweep) + if best_lqs is None: + # Sweep ran but yielded no candidates — nothing to rank. + n_skipped += 1 + results.append(_entry(name, family, sweep=sweep)) + _emit(name, 'skipped', 'no candidates') + continue + + n_scanned += 1 + results.append(_entry(name, family, sweep=sweep, + best_lqs=best_lqs, best_k=best_k)) + _emit(name, 'ok', f'best LQS {best_lqs * 100:.1f}%') + + # Successful sweeps first, ranked by best_lqs desc; the rest keep input + # order at the end. + 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, + } diff --git a/iqmapper/reservoir.py b/iqmapper/reservoir.py new file mode 100644 index 0000000..0a24a75 --- /dev/null +++ b/iqmapper/reservoir.py @@ -0,0 +1,300 @@ +""" +reservoir.py — make an enumeration cap count DISTINCT candidates. + +The problem +----------- +`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. 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. + +Exact duplicates are NOT the problem: each scaffold appears exactly twice (the +alpha/beta mirror) and the sweep already collapses that. Near-duplicates are. + +What this does +-------------- +A `DiverseReservoir` sits between VF2 and the cap. Every mapping is offered to +it; the cap counts only what it KEEPS. A mapping that overlaps a kept one by +Jaccard >= 0.8 and does not beat it on the lightweight score is discarded +without consuming the cap; one that beats it takes its place. So the 2000 +slots hold 2000 genuinely different candidates rather than 2000 views of the +same few regions. + +WHERE IT ENGAGES +---------------- +Only on the HYBRID path, and that is not an accident of implementation but a +consequence of the measurement above. At k_max the enumeration yields far +fewer mappings than the cap (908 on that device), so nothing is ever +discarded there and the reservoir is a no-op. The cap is only reached at low +k — k=1 and k=0 — which the sweep reaches through its hybrid per-stratum VF2 +pass. With `hybrid=False` the low-k strata are derived from the k_max +survivors by bridge subtraction, no low-k enumeration happens, and the +reservoir never engages. + +This also disposes of the obvious soundness worry. A reservoir sieving at +k_max on the k_max score could in principle discard a scaffold that is weak +with all bridges but excellent with one — and the cascade would then never +see it. It cannot happen, because at k_max the cap is not reached. Where the +reservoir does bite, the stratum is being enumerated directly and scored at +its own k. + +THE SCORE IS THE SWEEP'S +------------------------ +`score_fn` must be the same lightweight product the sweep computes in +`ancilla_sweep._add_variant`: + + product = prod(1 - readout[q]) over the 2*norb CHAIN qubits + * prod(1 - cz_err[e]) over the 2*(norb-1) chain edges + * prod over bridges of (1 - r)(1 - e1)(1 - e2) + +Note the chain readout term covers the chain only — a bridge qubit's readout +enters through its own bridge factor, not through `cr_prod`. The sweep hoists +`readout` and `edge_err` (keyed by `frozenset`, so direction is moot) and the +reservoir is handed closures over those same arrays, so there is one formula +and it cannot drift. `tests/test_reservoir.py` pins the equality to 1e-12. + +The circuit-level LQS is untouched: it remains the final ranking, applied +downstream to whatever this reservoir let through. +""" +import logging + +_log = logging.getLogger(__name__) + +#: Two layouts sharing at least this fraction of their qubits are "the same +#: region" for sieving purposes. 0.8 matches the sweep's own diversity quota +#: (`ancilla_sweep._select_with_diversity`), so enumeration and selection +#: agree on what counts as a different region. +DEFAULT_JACCARD = 0.8 + +#: Mappings considered per kept slot. The cap bounds what is HELD; this +#: 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 + + +class _Entry: + __slots__ = ('mapping', 'layout', 'qubits', 'score', 'key') + + def __init__(self, mapping, layout, qubits, score, key): + self.mapping = mapping + self.layout = layout + self.qubits = qubits + self.score = score + self.key = key + + +class DiverseReservoir: + """Keeps up to `cap` distinct, non-dominated candidates. + + Args: + cap: how many candidates to keep — what the caller's cap now counts. + score_fn: ``callable(layout) -> float``, the lightweight product + proxy. Higher is better. + to_layout: ``callable(mapping) -> list[int] | None``, converting a VF2 + mapping to a physical layout. Return None for an incomplete + mapping; it is counted as offered and otherwise ignored. + jaccard: similarity threshold, or None to disable similarity + filtering entirely (plain cap behaviour, for the parity path). + key_fn: ``callable(layout) -> hashable`` for exact-duplicate + detection. Defaults to `tuple(layout)` — the exact assignment. + Deliberately NOT `frozenset(layout)`: that conflates the + alpha/beta mirror, and the sweep must still see both members of + every mirror pair (see `offer`). + """ + + def __init__(self, cap, score_fn, to_layout, *, jaccard=DEFAULT_JACCARD, + key_fn=None, offer_budget=None): + self.cap = int(cap) + # How many mappings to CONSIDER. Filling stops at `cap`, but the + # reservoir must keep seeing candidates after that or replacement can + # never happen and it degenerates to the plain cap. The cap bounds + # memory (what we keep); this bounds work (what we look at). + self.offer_budget = (int(offer_budget) if offer_budget is not None + else OFFER_BUDGET_FACTOR * int(cap)) + self._score_fn = score_fn + self._to_layout = to_layout + self._jaccard = jaccard + self._key_fn = key_fn or (lambda layout: tuple(layout)) + self._entries = [] + self._by_qubit = {} # physical qubit -> {entry idx} + self._keys = {} # exact key -> entry index + self._stats = {'offered': 0, 'kept': 0, 'replaced': 0, + 'skipped_similar': 0, 'skipped_duplicate': 0, + 'incomplete': 0} + + # ── read-only surface ─────────────────────────────────────── + def __len__(self): + return len(self._entries) + + @property + def mappings(self): + """Kept mappings, in the order they were kept.""" + return [e.mapping for e in self._entries] + + @property + def layouts(self): + return [e.layout for e in self._entries] + + @property + def stats(self): + return dict(self._stats) + + @property + def exhausted(self): + """True once the offer budget is spent — the caller should stop.""" + return self._stats['offered'] >= self.offer_budget + + # ── the sieve ─────────────────────────────────────────────── + def offer(self, mapping): + """Consider one mapping. Returns what happened to it. + + One of 'kept', 'replaced', 'skipped_similar', 'skipped_duplicate' or + 'incomplete'. Only 'kept' grows `len(self)`. + + FILL FIRST, THEN SIEVE. Below the cap every mapping is kept + unconditionally; the sieve engages only once the reservoir is full. + That is not a refinement, it is required for correctness: the sweep + observes the raw enumeration through `n_raw_embeddings` and through + each entry's `source` ('vf2' vs 'derived'), and it relies on seeing + BOTH members of every alpha/beta mirror pair — which have Jaccard + 1.0 and would be the first thing any similarity filter removed. + `tests/test_ancilla_sweep.py::test_dedupe` pins exactly that. Sieving + unconditionally also discards candidates for no gain when there is no + scarcity, and the product score is only a proxy for the circuit-level + LQS that ranks them later — so a near-duplicate dropped here can be + one the real objective preferred. + + Once full, a candidate must earn its slot: it either beats the kept + candidate it most resembles, or — being a genuinely new region — it + beats the weakest thing currently held. + """ + self._stats['offered'] += 1 + layout = self._to_layout(mapping) + if not layout or any(q is None for q in layout): + self._stats['incomplete'] += 1 + return 'incomplete' + + key = self._key_fn(layout) + if key in self._keys: + self._stats['skipped_duplicate'] += 1 + return 'skipped_duplicate' + + qubits = frozenset(layout) + score = float(self._score_fn(layout)) + + if len(self._entries) < self.cap: + return self._keep(mapping, layout, qubits, score, key) + + if self._jaccard is None: + self._stats['skipped_similar'] += 1 + return 'skipped_similar' + + rival_idx = self._most_similar(qubits) + if rival_idx is not None: + rival = self._entries[rival_idx] + overlap = (len(qubits & rival.qubits) + / len(qubits | rival.qubits)) + if overlap >= self._jaccard: + # Same region: keep only the better of the two, so a + # near-duplicate can never occupy a slot it did not earn. + if score > rival.score: + self._replace(rival_idx, mapping, layout, qubits, score, + key) + return 'replaced' + self._stats['skipped_similar'] += 1 + return 'skipped_similar' + + # A genuinely new region, and we are full. Displace the weakest + # candidate held — this is what lets coverage keep growing after the + # cap is reached, instead of freezing on whichever corner of the chip + # VF2 happened to traverse first. + weakest_idx = self._weakest() + if weakest_idx is not None and score > self._entries[weakest_idx].score: + self._replace(weakest_idx, mapping, layout, qubits, score, key) + return 'replaced' + self._stats['skipped_similar'] += 1 + return 'skipped_similar' + + # ── internals ─────────────────────────────────────────────── + def _most_similar(self, qubits): + """Index of the kept entry sharing the most qubits, or None. + + Only entries sharing at least one qubit can reach the threshold, so + the inverted index bounds the work to those — this is O(#kept + sharing a qubit), not O(#kept). + """ + counts = {} + for q in qubits: + for idx in self._by_qubit.get(q, ()): + counts[idx] = counts.get(idx, 0) + 1 + if not counts: + return None + # Deterministic: most shared qubits, then earliest kept. + return min(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0] + + def _weakest(self): + """Index of the lowest-scoring kept entry. Deterministic ties. + + Only consulted when the reservoir is full AND the candidate is a new + region, which is the rare case — the common one is a near-duplicate, + resolved by the inverted index above. + """ + if not self._entries: + return None + return min(range(len(self._entries)), + key=lambda i: (self._entries[i].score, i)) + + def _keep(self, mapping, layout, qubits, score, key): + idx = len(self._entries) + self._entries.append(_Entry(mapping, layout, qubits, score, key)) + for q in qubits: + self._by_qubit.setdefault(q, set()).add(idx) + self._keys[key] = idx + self._stats['kept'] += 1 + return 'kept' + + def _replace(self, idx, mapping, layout, qubits, score, key): + old = self._entries[idx] + for q in old.qubits: + bucket = self._by_qubit.get(q) + if bucket is not None: + bucket.discard(idx) + if not bucket: + del self._by_qubit[q] + self._keys.pop(old.key, None) + + self._entries[idx] = _Entry(mapping, layout, qubits, score, key) + for q in qubits: + self._by_qubit.setdefault(q, set()).add(idx) + self._keys[key] = idx + self._stats['replaced'] += 1 + + def __repr__(self): # pragma: no cover - debug aid + return (f'") + + +def summarise(stats, k=None, hybrid=True): + """The one-line notice the sweep surfaces when a cap was reached. + + Names the hybrid stratum explicitly, because that is the only place the + reservoir engages and a user comparing runs needs to know which pass the + number belongs to. + """ + if not stats or not stats.get('kept'): + return None + where = f'hybrid k={k}' if (hybrid and k is not None) else f'k={k}' + # "(of N seen)" carries what the old truncation banner used to say — that + # the ranking is drawn from a sample, not the whole enumeration — so the + # two notices can be merged into this one line instead of contradicting + # each other about the same stratum. + seen = stats.get('offered') + seen_txt = f' (of {seen:,} seen)' if seen else '' + return (f'{where}: cap reached — kept {stats["kept"]:,} diverse ' + f'candidates, skipped {stats["skipped_similar"]:,} ' + f'near-duplicates{seen_txt}') diff --git a/iqmapper/stability_filter.py b/iqmapper/stability_filter.py new file mode 100644 index 0000000..29afe12 --- /dev/null +++ b/iqmapper/stability_filter.py @@ -0,0 +1,276 @@ +""" +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 + +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, +# 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 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, quality_sigma=3.0): + """Stability-filtered ancilla sweep with an automatic relax valve. + + 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-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). + + ``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( + 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() + + # 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) + + # 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() + + # 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(combined) + 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 + # 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-bad, 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, + } + 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/iqmapper/ui/backend_switch.py b/iqmapper/ui/backend_switch.py index 607cf55..c2bf3b4 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 @@ -38,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 @@ -94,8 +87,8 @@ def _classify_switch_error(exc: BaseException, backend_name: str) -> str: return (f"Backend '{backend_name}' is no longer available " f"(may have been retired or hidden by IBM).") if 'auth' in msg or '401' in msg or '403' in msg or 'token' in msg: - return ("Authentication failed (token may have expired). " - "Re-save your QiskitRuntimeService account and restart the kernel.") + return ("Authentication failed — re-save your IBM Quantum " + "account and restart the kernel.") if 'timeout' in msg or 'timed out' in msg or 'connection' in msg: return f"Network error reaching IBM Quantum: {exc}" return f"Switch failed: {exc}" @@ -120,6 +113,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. """ @@ -137,26 +136,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. @@ -169,9 +148,26 @@ 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 + # 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'] @@ -265,11 +261,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: @@ -318,6 +309,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 @@ -333,8 +329,9 @@ 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() - # Same for the time/delta panel header, which may already - # have been rebuilt with the new name before the failure. + # …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 = ( diff --git a/iqmapper/ui/benchmark_panel.py b/iqmapper/ui/benchmark_panel.py new file mode 100644 index 0000000..82f614c --- /dev/null +++ b/iqmapper/ui/benchmark_panel.py @@ -0,0 +1,1149 @@ +""" +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 + chk_bench_absolute = getattr(ctx, 'chk_bench_absolute', None) + chk_err_threshold = getattr(ctx, 'chk_err_threshold', None) + txt_g_thr_max = getattr(ctx, 'txt_g_thr_max', None) + dd_gate_prop = getattr(ctx, 'dd_gate_prop', None) + lbl_bench_consistency = getattr(ctx, 'lbl_bench_consistency', None) + lbl_bench_details = getattr(ctx, 'lbl_bench_details', None) + acc_bench_details = getattr(ctx, 'acc_bench_details', None) + btn_show_on_map = getattr(ctx, 'btn_bench_show_on_map', None) + #: (gate_key, threshold, n_edges) the map link would apply. + _map_target = [None] + lbl_bench_reuse = ctx.lbl_bench_reuse + btn_bench_reuse = ctx.btn_bench_reuse + btn_bench_reanalyze = getattr(ctx, 'btn_bench_reanalyze', None) + btn_bench_calcheck = getattr(ctx, 'btn_bench_calcheck', None) + lbl_bench_calcheck = getattr(ctx, 'lbl_bench_calcheck', None) + + 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 '' + + # A plan that cannot be split under IBM's per-job shot limit must + # 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: + extra += (f"
\u274c " + f"{esc(reason)}") + + lbl_bench_summary.value = ( + f"
{esc(bench.summary_line(targets, cost, plan_name))}" + f"{extra}{warn}
") + + _sync_calcheck(targets, plan_name, level) + chk_bench_ack.layout.display = '' if needs_ack else 'none' + btn_bench_run.disabled = bool( + (not plan.specs) or (not ok) + 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 _calcheck_plans(): + """(parallel, sequential) over the first N target edges, or None.""" + state, _r = active_target() + targets = bench.select_targets( + state, _sweep_result(), mode=dd_bench_target.value, + custom=txt_bench_custom.value) + if len(targets.edges) < bench.CALIBRATION_CHECK_EDGES: + return None, None, targets + par, seq = bench.build_calibration_check_plans( + targets, len(getattr(state, 'qubit_ids', None) or []), + list(getattr(state, 'edges_list', None) or []), + n_edges=bench.CALIBRATION_CHECK_EDGES) + return par, seq, targets + + def _sync_calcheck(targets, plan_name, level): + """Cost line and enablement for the check, before the click.""" + if btn_bench_calcheck is None: + return + n_edges = len(targets.edges) + if n_edges < bench.CALIBRATION_CHECK_EDGES: + btn_bench_calcheck.disabled = True + if lbl_bench_calcheck is not None: + lbl_bench_calcheck.value = ( + f"
" + f"Calibration check needs at least " + f"{bench.CALIBRATION_CHECK_EDGES} target edges " + f"(have {n_edges}).
") + return + par, seq, _t = _calcheck_plans() + if par is None: + btn_bench_calcheck.disabled = True + return + circuits = (bench.plan_circuit_count(par) + + bench.plan_circuit_count(seq)) + shots = bench.plan_shots(par, par.shots) + bench.plan_shots( + seq, seq.shots) + jobs = (len(bench.split_for_submission(par, par.shots)) + + len(bench.split_for_submission(seq, seq.shots))) + seconds = (bench.estimate_cost(par).qpu_seconds + + bench.estimate_cost(seq).qpu_seconds) + # The check spends QPU time like any run, so the same gate applies. + needs_ack = bench.requires_acknowledgement(plan_name, + bench.LEVEL_TARGETED) + btn_bench_calcheck.disabled = bool( + needs_ack and not chk_bench_ack.value) + if lbl_bench_calcheck is not None: + lbl_bench_calcheck.value = ( + f"
" + f"Calibration check: " + f"{bench.CALIBRATION_CHECK_EDGES} edges \u00d7 2 arms \u00b7 " + f"~{circuits} circuits \u00b7 " + f"{esc(bench._format_shots(shots))} \u00b7 " + f"{jobs} job(s) \u00b7 ~{seconds:.0f} s QPU (estimate)" + f"
") + + def _on_calcheck(_b=None): + """Run both arms in one session. Measures the INSTRUMENT. + + No epoch is applied: the check exists to tell whether the numbers a + benchmark produces are biased, so treating its output as a + calibration would be circular. + """ + state, _refresh_fn = active_target() + par, seq, targets = _calcheck_plans() + if par is None: + lbl_bench_status.value = _err( + f'Calibration check needs at least ' + f'{bench.CALIBRATION_CHECK_EDGES} target edges.') + return + + plan_name = _plan_name() + if bench.requires_acknowledgement(plan_name, bench.LEVEL_TARGETED) \ + and not chk_bench_ack.value: + lbl_bench_status.value = _err( + 'Tick "I understand this uses QPU time" to run the ' + 'calibration check.') + return + + backend_name = getattr(state, 'active_backend_name', None) + reported_g = dict(getattr(state, 'gate_props_data', {}) or {}) + reported_q = dict(getattr(state, 'qubit_props_data', {}) or {}) + edges = list(getattr(state, 'edges_list', None) or []) + import time as _time + started_at = _time.time() + jobs_seen = {} + + def _record_jobs(phase_index, job_ids, status): + jobs_seen[str(phase_index)] = list(job_ids) + if backend_name: + bench.save_job_record( + backend_name, started_at, par, shots=par.shots, + jobs=jobs_seen, statuses={str(phase_index): status}, + kind=bench.RECORD_KIND_CALIBRATION_CHECK, + arms=['parallel', 'sequential']) + + btn_bench_calcheck.disabled = True + lbl_bench_status.value = ( + "
\u23f3 Calibration check: " + "parallel then sequential\u2026
") + + if runner_factory is None: + try: + bench.preload_runtime() + except Exception as exc: # noqa: BLE001 - reported + btn_bench_calcheck.disabled = False + lbl_bench_status.value = _err(exc) + return + + def _work(): + if runner_factory is not None: + runner = runner_factory(state) + return [bench.run_plan(par, runner), + bench.run_plan(seq, runner)], [] + runner = bench.make_calibration_check_runner( + getattr(state, 'active_backend', None), on_jobs=_record_jobs) + return runner([par, seq]), getattr(runner, 'last_expdata', []) + + def _done(payload): + btn_bench_calcheck.disabled = False + raws, expdata = payload + if backend_name and expdata: + try: + bench.save_raw_results(backend_name, started_at, expdata) + except Exception: + _log.debug('raw dump failed', exc_info=True) + try: + par_epoch = bench.results_to_epoch( + raws[0], par, dict(reported_q), dict(reported_g), edges, + when=started_at) + seq_epoch = bench.results_to_epoch( + raws[1], seq, dict(reported_q), dict(reported_g), edges, + when=started_at) + table = bench.calibration_check_table( + edges, reported_g.get('cz_error', []), par_epoch, + seq_epoch) + except Exception as exc: # noqa: BLE001 - reported + _log.exception('calibration check folding failed') + lbl_bench_status.value = _err(exc) + return + + notices = list(par_epoch.notices) + list(seq_epoch.notices) + if backend_name: + bench.save_attempt_notices(backend_name, started_at, notices) + bench.save_calibration_check(backend_name, started_at, table) + _render_calcheck(table) + lbl_bench_status.value = ( + "
\u2705 Calibration check complete — the " + "calibration in use is unchanged.
") + _render_inline_notices(notices) + + def _failed(exc): + btn_bench_calcheck.disabled = False + _log.exception('calibration check failed: %s', exc) + lbl_bench_status.value = _err(exc) + + if spawn_bg is None: + try: + _done(_work()) + except Exception as exc: # noqa: BLE001 - reported + _failed(exc) + return + spawn_bg(_work, on_done=_done, on_error=_failed) + + def _reanalyze_calcheck(state, name, record, job_ids): + """Replay a calibration check from its jobs. Zero QPU, no epoch.""" + par = bench.plan_from_record(record) + if par is None: + lbl_bench_status.value = _err( + 'This calibration-check record has no experiment list, so ' + 'its arms cannot be rebuilt.') + return + _seq_specs = [] + for spec in par.specs: + if spec.kind != 'rb2q_layer': + _seq_specs.append(spec) + continue + for pair in spec.params['pairs']: + params = dict(spec.params) + params['pairs'] = [tuple(pair)] + _seq_specs.append(spec._replace(qubits=tuple(pair), + params=params)) + seq = par._replace(specs=_seq_specs) + + 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 []) + import time as _time + attempt_at = _time.time() + + # One arm's ids per half of the recorded phases. + half = max(1, len(job_ids) // 2) + arms = [job_ids[:half], job_ids[half:] or job_ids[:half]] + + try: + raw_par, exp_par = bench.reanalyze_from_jobs( + par, arms[0], getattr(state, 'active_backend', None), + getattr(state, 'active_service', None)) + raw_seq, exp_seq = bench.reanalyze_from_jobs( + seq, arms[1], getattr(state, 'active_backend', None), + getattr(state, 'active_service', None)) + par_epoch = bench.results_to_epoch(raw_par, par, dict(reported_q), + dict(reported_g), edges, + when=attempt_at) + seq_epoch = bench.results_to_epoch(raw_seq, seq, dict(reported_q), + dict(reported_g), edges, + when=attempt_at) + table = bench.calibration_check_table( + edges, reported_g.get('cz_error', []), par_epoch, seq_epoch) + except Exception as exc: # noqa: BLE001 - reported + _log.exception('calibration-check reanalysis failed') + _persist_attempt(name, attempt_at, exp_par if 'exp_par' in dir() + else [], [f'reanalysis failed: {exc}']) + lbl_bench_status.value = _err(exc) + return + + notices = list(par_epoch.notices) + list(seq_epoch.notices) + _persist_attempt(name, attempt_at, list(exp_par) + list(exp_seq), + notices) + if name: + bench.save_calibration_check(name, attempt_at, table) + _render_calcheck(table) + lbl_bench_status.value = ( + "
\u2705 Calibration check reanalysed (no QPU) — " + "the calibration in use is unchanged.
") + _render_inline_notices(notices) + + def _render_calcheck(table): + if lbl_bench_calcheck is not None: + lbl_bench_calcheck.value = bench.calibration_check_table_html( + table, esc) + + 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. + + 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" — the single outcome this feature must + never produce. + """ + state, refresh_fn = active_target() + _check_consistency(state, epoch) + if getattr(epoch, 'is_empty', False): + lbl_bench_status.value = _empty_sentence() + _surface_notices(epoch) + return False + 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") + + _surface_notices(epoch) + + analysis_failed = [n for n in (getattr(epoch, 'notices', None) or []) + if 'analysis failed' in n] + 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 '' + coverage = (epoch.coverage_text() if hasattr(epoch, 'coverage_text') + else f'{epoch.n_measured_qubits}q/{epoch.n_measured_edges}e') + if getattr(epoch, 'is_complete', True) and not analysis_failed: + lbl_bench_status.value = ( + f"
✅ {esc(qpu_txt)}{esc(source)}: measured " + f"{esc(coverage)} (L{epoch.level}){rank_txt}
") + else: + lbl_bench_status.value = ( + f"
⚠ {esc(qpu_txt)}{esc(source)}: partial — " + f"measured {esc(coverage)} (L{epoch.level}){rank_txt}" + + (f"
{esc(analysis_failed[0])}" if analysis_failed else '') + + "
") + _refresh_reuse_offer() + return True + + def _check_consistency(state, epoch): + """Compare against the reported calibration; rescale if it is off. + + A measured epoch whose median sits 2.8x away from the reported one + across 351 edges is not describing drift — a whole chip does not move + uniformly in one direction. That is an estimator mismatch, and its + absolute values must not reach the LQS. Relative mode keeps the + per-element ratios (the collapsed couplers, which ARE real) and + discards only the offset. + """ + if lbl_bench_consistency is None: + return + try: + reported_q = getattr(state, '_reported_qubit_props', None) or {} + reported_g = getattr(state, '_reported_gate_props', None) or {} + if not reported_q and not reported_g: + lbl_bench_consistency.value = '' + return + stats = bench.consistency_stats(epoch, reported_q, reported_g) + epoch.consistency = stats + offenders = bench.consistency_offenders(stats) + rescale = bool(offenders) and not bool( + getattr(chk_bench_absolute, 'value', False)) + if rescale: + bench.apply_relative_mode(epoch, reported_q, reported_g, + stats) + rescaled = set(offenders) if rescale else set() + + lbl_bench_consistency.value = _result_sentence(epoch, stats, + rescaled) + _render_details(stats, rescaled, reported_g) + except Exception: + _log.exception('consistency check failed') + + #: Property keys → the words a user recognises. + _PROP_NAMES = {'readout_error': 'Readout error', 't1': 'T1', 't2': 'T2', + 'cz_error': 'CZ error', 'rzz_error': 'RZZ error'} + + def _prop_name(key): + if key in _PROP_NAMES: + return _PROP_NAMES[key] + if key.endswith('_error'): + return f'{key[:-len("_error")].upper()} error' + return key + + def _join_names(keys): + # Escape the property names, not the surrounding copy: running the + # whole sentence through esc() turned every apostrophe into '. + names = [esc(_prop_name(k)) for k in keys] + if len(names) <= 1: + return names[0] if names else '' + return ' and '.join([', '.join(names[:-1]), names[-1]]) + + def _is_edge_prop(key): + return key in ('cz_error', 'rzz_error') + + def _result_sentence(epoch, stats, rescaled): + """One plain sentence. No jargon, no warning glyph, no method talk. + + 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'] + + if not rescaled: + parts[0] += (" \u2014 measured values are in line with IBM's " + "reported calibration.") + else: + parts[0] += '.' + if in_band: + parts.append( + f"{_join_names(in_band)} look like real drift today;") + # Names and factors MUST share one ordering — `rescaled` is a + # set, so iterating it for the factors while sorting it for the + # names could pair "T2 and CZ error" with CZ's factor first. + # The stats order (readout, t1, t2, 2Q) is the one the Details + # table uses, so use it here too. + order = [k for k in stats if k in rescaled] + factors = ', '.join( + f"\u00d7{stats[k]['ratio_of_medians']:.1f}" for k in order) + parts.append( + f"{_join_names(order)} differ by a constant factor " + f"({factors}) and are shown on IBM's scale " + f"\u00b7 Reference: Relative mode") + + missing_q = max(0, epoch.planned_count[0] - epoch.measured_count[0]) + missing_e = max(0, epoch.planned_count[1] - epoch.measured_count[1]) + if missing_q or missing_e: + parts.append(f'{missing_q} qubits and {missing_e} edges could ' + f'not be measured and keep their reported values.') + + return (f"
" + f"{' '.join(parts)}
") + + def _empty_sentence(): + return ("
" + "\u26a0 Nothing usable was measured \u2014 IBM's reported " + "calibration is still in use.
") + + def _details_rows(stats, rescaled): + rows = [] + for key, value in stats.items(): + is_rescaled = key in rescaled + ratio = (f"\u00d7{value['ratio_of_medians']:.2f}" + + (' \u26a0' if is_rescaled else '')) + unit = 'edges' if _is_edge_prop(key) else 'qubits' + count = value['n_worse_2x'] + # A rescaled property with nothing individually out of line has + # no "changed a lot" story to tell — the whole difference was the + # constant factor, which the previous column already reports. + changed = ('\u2014' if (is_rescaled and not count) + else f"{count} of {value['n']} {unit} >2\u00d7 worse") + applied = ('rescaled to IBM\'s scale' if is_rescaled + else 'as measured') + if is_rescaled and key in ('t1', 't2'): + applied = 'rescaled (different estimator)' + rows.append({'key': key, 'name': _prop_name(key), 'ratio': ratio, + 'changed': changed, 'applied': applied, + 'count': count}) + return rows + + def _render_details(stats, rescaled, reported_g): + """The numbers, one row per property, collapsed by default.""" + if acc_bench_details is None or lbl_bench_details is None: + return + rows = _details_rows(stats, rescaled) + if not rows: + lbl_bench_details.value = '' + return + + body = '' + for row in rows: + changed_cell = esc(row['changed']) + if (_is_edge_prop(row['key']) and row['count'] + and btn_show_on_map is not None): + # The count becomes actionable: the button below the table + # paints exactly these edges on the device map. + changed_cell = f"{esc(row['changed'])} \u2192" + body += ( + f"{esc(row['name'])}" + f"" + f"{esc(row['ratio'])}" + f"{changed_cell}" + f"{esc(row['applied'])}" + f"") + + lbl_bench_details.value = ( + "" + "" + "" + "" + "" + "" + "" + f"{body}
Propertyvs reportedchanged a lothow applied
" + "
" + "as measured = used directly \u00b7 rescaled = median " + "aligned to IBM\u2019s, ranking kept
") + + _sync_show_on_map(stats, reported_g) + + def _sync_show_on_map(stats, reported_g): + """Offer the map link only when there are edges worth looking at.""" + if btn_show_on_map is None: + return + edge_key = next((k for k in stats + if _is_edge_prop(k) and stats[k]['n_worse_2x']), None) + _map_target[0] = None + if edge_key is None or chk_err_threshold is None \ + or txt_g_thr_max is None: + btn_show_on_map.layout.display = 'none' + return + median = stats[edge_key]['median_reported'] + _map_target[0] = (edge_key, 2.0 * median, + stats[edge_key]['n_worse_2x']) + btn_show_on_map.description = ( + f"show {stats[edge_key]['n_worse_2x']} edges on map") + btn_show_on_map.layout.display = '' + + def _on_show_on_map(_b=None): + """Three writes: pick the 2Q property, set the cap, enable the filter. + + The threshold widgets already drive the Error tab's rendering, so + this needs no plot change — it just points them at "worse than twice + IBM's median", which is exactly what the table counted. + """ + target = _map_target[0] + if target is None: + return + edge_key, cap, _count = target + try: + if dd_gate_prop is not None: + options = [v for _lbl, v in (dd_gate_prop.options or []) + if not isinstance(dd_gate_prop.options, dict)] + if not options or edge_key in options: + dd_gate_prop.value = edge_key + if txt_g_thr_max is not None: + txt_g_thr_max.value = f'{cap:.3e}' + if chk_err_threshold is not None: + chk_err_threshold.value = True + except Exception: + _log.exception('show-on-map wiring failed') + + def _surface_notices(epoch): + _render_inline_notices(getattr(epoch, 'notices', None)) + if notices_label is not None and getattr(epoch, 'notices', None): + notices_label.value = ( + "
⚠ " + + "
".join(esc(n) for n in epoch.notices) + "
") + + def _render_inline_notices(notices): + """Show the run's notices under the status, not only in the Auto tab. + + The benchmark section lives in the sidebar; its notices were going to + the Auto tab's notices bar, which a user running a benchmark is not + looking at. The reason a run came back empty belongs next to the + message saying it came back empty. + """ + if lbl_bench_consistency is None: + return + if not notices: + return + shown = list(notices)[:6] + more = ('' if len(notices) <= 6 + else f"
\u2026and {len(notices) - 6} more") + lbl_bench_status.value += ( + "
" + + "
".join(esc(n) for n in shown) + more + "
") + + 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) + # Kept for the consistency check, which has to compare against what + # was reported BEFORE the measured epoch replaces it. + setattr(state, '_reported_qubit_props', reported_q) + setattr(state, '_reported_gate_props', reported_g) + + import time as _time + started_at = _time.time() + job_ids_seen = {} + + def _record_jobs(chunk_index, job_ids, status): + """Persist ids the moment they exist, not at the end. + + 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: + bench.save_job_record( + backend_name, started_at, plan, shots=plan.shots, + jobs=job_ids_seen, statuses={str(chunk_index): status}) + + 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), + on_jobs=_record_jobs) + result = bench.run_plan(plan, runner) + return result, getattr(runner, 'last_expdata', []) + + def _done(payload): + """Main thread: fold, apply, persist. Raw dump always written.""" + btn_bench_run.disabled = False + raw, expdata = (payload if isinstance(payload, tuple) + 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 for a run that goes wrong. + if backend_name and expdata: + try: + bench.save_raw_results(backend_name, started_at, expdata) + except Exception: + _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. 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) + 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) + _refresh_reanalyze_offer() + + def _failed(exc): + """Main thread: the reported epoch is left exactly as it was. + + The raw dump is written here too: a failed run is precisely when + the diagnostic artefact is most needed. + """ + btn_bench_run.disabled = False + expdata = getattr(exc, 'expdata', None) + if backend_name and expdata: + try: + bench.save_raw_results(backend_name, started_at, expdata) + except Exception: + _log.debug('raw dump on failure path failed', + exc_info=True) + _log.exception("benchmark run failed: %s", exc) + if isinstance(exc, bench.BenchmarkRunError): + ids = ', '.join(exc.job_ids) if exc.job_ids else 'none' + lbl_bench_status.value = _err( + f'Benchmark job failed: {exc} (job ids: {ids})') + else: + lbl_bench_status.value = _err(exc) + _refresh_reanalyze_offer() + + 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 _refresh_reanalyze_offer(): + """Show Reanalyze when a submission record exists for this backend.""" + if btn_bench_reanalyze is None: + return + try: + state, _r = active_target() + name = getattr(state, 'active_backend_name', None) + record = bench.latest_job_record(name) if name else None + has_jobs = bool(record and any(record.get('jobs', {}).values())) + btn_bench_reanalyze.layout.display = '' if has_jobs else 'none' + btn_bench_reanalyze.disabled = not has_jobs + except Exception: + _log.debug('reanalyze offer unavailable', exc_info=True) + + def _on_reanalyze(_b=None): + """Rebuild the epoch from the last submission's jobs. Zero QPU. + + qiskit-experiments fits client-side, so the jobs already hold + everything needed: this re-runs the analysis, never the circuits. + """ + state, _refresh_fn = active_target() + name = getattr(state, 'active_backend_name', None) + record = bench.latest_job_record(name) if name else None + if not record: + lbl_bench_status.value = _err('No previous submission to reanalyze.') + return + # Per-PHASE grouping, not a flat list. `reanalyze_from_jobs` takes + # the two-phase path (1Q RB first, then 2Q RB built with those EPGs) + # only when handed a list of lists; flattening collapsed both phases + # into one batch, so the 2Q analyses were constructed before any 1Q + # EPG existed and came back UN-subtracted — a measured median of + # 4.05e-3 where the phased path gives 2.96e-3. + jobs_by_phase = record.get('jobs') or {} + + def _phase_key(key): + try: + return (0, int(key)) + except (TypeError, ValueError): + return (1, str(key)) + + job_ids = [list(jobs_by_phase[k]) + for k in sorted(jobs_by_phase, key=_phase_key) + if jobs_by_phase[k]] + if not any(job_ids): + lbl_bench_status.value = _err( + 'The last submission recorded no job ids.') + return + + # Replay the plan that PRODUCED these jobs, from the submission + # record. Never `_current_plan()`: the target selector describes what + # the user would run NEXT, and with it on "Current layout(s)" and + # nothing placed the rebuilt plan had zero experiments — so nothing + # was folded, no notice was raised, and the panel reported (0, 0) + # while the raw dump held 348 EPG_cz and 156 T1/T2/readout. + # A calibration check replays as TWO arms and yields a table, never + # an epoch — it measures the instrument, not the device. + if (record.get('kind') == bench.RECORD_KIND_CALIBRATION_CHECK + or record.get('arms')): + _reanalyze_calcheck(state, name, record, job_ids) + return + + plan, how = bench.plan_for_replay( + record, name, + len(getattr(state, 'qubit_ids', None) or []), + list(getattr(state, 'edges_list', None) or [])) + if plan is None: + lbl_bench_status.value = _err( + "Can't rebuild this run's plan (no experiment list " + "saved). Only runs made with the current version can be " + "reanalysed.") + return + + if btn_bench_reanalyze is not None: + btn_bench_reanalyze.disabled = True + if runner_factory is None: + if not bench.runtime_ready(): + lbl_bench_status.value = ( + "
" + "\u23f3 Loading benchmark libraries\u2026
") + try: + bench.preload_runtime() + except Exception as exc: # noqa: BLE001 - reported + if btn_bench_reanalyze is not None: + btn_bench_reanalyze.disabled = False + lbl_bench_status.value = _err(exc) + return + + 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 []) + # `_check_consistency` compares against what was reported BEFORE + # the epoch lands. `_on_run` stashes these; the reanalysis path + # did not, so the check found nothing to compare with, returned + # early, and the epoch was applied unrescaled with no + # consistency line at all. + setattr(state, '_reported_qubit_props', reported_q) + setattr(state, '_reported_gate_props', reported_g) + + import time as _time + attempt_at = _time.time() + expdata = [] + try: + raw, expdata = bench.reanalyze_from_jobs( + plan, job_ids, getattr(state, 'active_backend', None), + getattr(state, 'active_service', None)) + epoch = bench.results_to_epoch(raw, plan, reported_q, reported_g, + edges, when=attempt_at) + except Exception as exc: # noqa: BLE001 - reported + if btn_bench_reanalyze is not None: + 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. + _persist_attempt(name, attempt_at, expdata, + [f'reanalysis failed: {exc}']) + lbl_bench_status.value = _err(exc) + return + + 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. + _persist_attempt(name, attempt_at, expdata, epoch.notices) + if _install_epoch(epoch, + source=f'Reanalysis of L{plan.level} run (no QPU)') \ + and name: + bench.save_measured_epoch(name, epoch) + + def _persist_attempt(backend_name, when, expdata, notices): + """Write the raw dump and the notices for ANY attempt. + + 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 + try: + if expdata: + bench.save_reanalysis_raw(backend_name, when, expdata) + except Exception: + _log.debug('raw dump failed', exc_info=True) + try: + bench.save_attempt_notices(backend_name, when, notices) + except Exception: + _log.debug('notice dump failed', exc_info=True) + + 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) + if btn_show_on_map is not None: + btn_show_on_map.on_click(_on_show_on_map) + if btn_bench_calcheck is not None: + btn_bench_calcheck.on_click(_on_calcheck) + if btn_bench_reanalyze is not None: + btn_bench_reanalyze.on_click(_on_reanalyze) + _refresh_reanalyze_offer() + 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, + 'reanalyze': _on_reanalyze, + 'calibration_check': _on_calcheck, + 'calcheck_plans': _calcheck_plans, + 'show_on_map': _on_show_on_map, + 'result_sentence': _result_sentence, + 'render_details': _render_details, + } diff --git a/iqmapper/ui/builder.py b/iqmapper/ui/builder.py index 0155ea5..839ab36 100644 --- a/iqmapper/ui/builder.py +++ b/iqmapper/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, ) @@ -85,6 +86,9 @@ def __init__(self, state, is_secondary: bool = False): # mutator contract — do not "fix" it. self._loading_device = False self._switching_backend = [False] + # Backend whose per-chip search defaults are applied; a reload of the + # same backend (date / hour change) keeps the user's choices. + self._defaults_backend = None def build(self, return_widgets=False): """Run the full UI construction pipeline. @@ -94,6 +98,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: @@ -266,9 +277,6 @@ def _run_pipeline(self): refresh=self._refresh, get_export=self._get_export, out=self.out, refresh_qpu1_label=self._refresh_qpu1_label, - # Deferred: self._time_api is bound further down (the time panel - # is built after this wiring), but a switch can only fire once - # construction has finished. refresh_time_panel=lambda: self._time_api.rebuild(), )) @@ -299,26 +307,117 @@ def _run_pipeline(self): # ── Auto-LUCJ callbacks (extracted to ui.lucj_panel.py) ────── from .lucj_panel import setup_lucj_callbacks + from ..async_util import default_spawn_bg, marshal_to_main + # Shared cell: ui.inter_qpu populates [0] with its handoff hook + # (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, - 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, + 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, + chk_diverse_cap=self.chk_diverse_cap, + chk_guided_search=self.chk_guided_search, + 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, + 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_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, + joint_params_box=self.joint_params_box, lucj_multi_ancillas=self.lucj_multi_ancillas, - btn_lucj_multi=self.btn_lucj_multi, lbl_lucj_multi=self.lbl_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, + 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, - lucj_multi_ancillas_list=self._lucj_multi_ancillas, - lucj_multi_dropdowns=self._lucj_multi_dropdowns, + rescore_cell=self._bench_rescore, refresh=self._refresh, get_export=self._get_export, update_view=lambda: self._update_view(), chk_line_only=self.chk_line_only, + # 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, + lbl_scan_progress=self.lbl_scan_progress, + scan_results_box=self.scan_results_box, + scan_spawn_bg=default_spawn_bg, + scan_marshal=marshal_to_main, + inter_qpu_handoff=self._inter_qpu_handoff, + # Stability filter. + 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, ) 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, + chk_bench_absolute=self.chk_bench_absolute, + # Read-only from the panel except for the three writes the + # "show on map" link performs (enable the filter, set the gate + # max, select the 2Q property). + chk_err_threshold=self.chk_err_threshold, + txt_g_thr_max=self.txt_g_thr_max, + dd_gate_prop=self.dd_gate_prop, + lbl_bench_consistency=self.lbl_bench_consistency, + lbl_bench_details=self.lbl_bench_details, + acc_bench_details=self.acc_bench_details, + btn_bench_show_on_map=self.btn_bench_show_on_map, + lbl_bench_reuse=self.lbl_bench_reuse, + btn_bench_reuse=self.btn_bench_reuse, + btn_bench_reanalyze=self.btn_bench_reanalyze, + btn_bench_calcheck=self.btn_bench_calcheck, + lbl_bench_calcheck=self.lbl_bench_calcheck, + 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 @@ -332,9 +431,7 @@ def _run_pipeline(self): W=W, plot_mod=plot_mod, safe_path=_safe_path, user_save_path=_user_save_path, save_dir=self._save_dir, out=self.out, lbl_png_status=self.lbl_png_status, - # Live figure: its error-map colorbars get copied onto the - # export figure, which the static renderer doesn't draw. - fig=self.fig, + fig=self.fig, # live figure — copy its visible colorbars into the PNG )) @@ -363,10 +460,10 @@ def _run_pipeline(self): # Built at builder scope so the panel's slider state (intraday # timestamps, range) persists across nav / num_circuits / mode # changes — otherwise every _update_view rebuild would discard a - # fetched scan. The `api` handle (rebuild / status_text) is kept: - # the panel drives its own re-render via observers for in-panel - # changes, but a backend switch happens outside those observers, - # so backend_switch calls api.rebuild() to refresh the header. + # fetched scan. The returned `api` handle is KEPT (self._time_api): + # a backend switch resets the panel's time-state but never fires its + # own observers, so the switch wiring calls api.rebuild() to re-render + # the header + sub-panels for the new backend. self._time_panel, self._time_api = _build_time_panel( state=state, data_mod=data_mod, @@ -518,6 +615,8 @@ def _run_pipeline(self): qpu2_sidebar_box=_qpu2_sidebar_box, 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 @@ -795,9 +894,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'}, ) @@ -1159,21 +1258,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 @@ -1187,20 +1282,287 @@ 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)') + # 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') + # 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 embeddings enumerated per search; the notices say ' + 'when it truncates · Reference: Search cap') self.lucj_chk_score = Checkbox( value=True, description='Score layouts (pick lowest error)', + # 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 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=True, + description='Prefer diverse regions', + layout=W, + tooltip='Second half of each list favors other chip regions; ' + 'top half is always the best') + # ── 📡 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: placed layouts, sweep candidates, ' + 'the whole QPU, or a 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 + two-qubit gates on targets · ' + '3 whole chip (~4 min) · Reference: Levels') + 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.btn_bench_calcheck = Button( + description='🔬 Calibration check', + button_style='info', layout=W, disabled=True, + tooltip='Measures 6 edges twice: crosstalk or estimator bias' + ' · Reference: Calibration check') + self.lbl_bench_calcheck = HTML("") + self.lbl_bench_reuse = HTML("") + self.btn_bench_reuse = Button( + description='Reuse', button_style='info', disabled=True, + layout=Layout(width='120px', margin='2px 0px')) + _reanalyze_layout = Layout(width='200px', margin='2px 0px') + _reanalyze_layout.display = 'none' # only when a job record exists + self.btn_bench_reanalyze = Button( + description='Reanalyze last run', button_style='info', + disabled=True, layout=_reanalyze_layout, + tooltip='Re-analyses the last run\'s results; costs no QPU time') + self.chk_bench_absolute = Checkbox( + value=False, + description='Apply absolute values', + layout=_own(), + tooltip="Use measured values as-is even when far " + "from IBM's scale · Reference: Relative mode") + self.lbl_bench_consistency = HTML("") + self.lbl_bench_details = HTML("") + _map_btn_layout = Layout(width='220px', margin='4px 0px') + _map_btn_layout.display = 'none' # shown only when edges qualify + self.btn_bench_show_on_map = Button( + description='show on map', button_style='', + layout=_map_btn_layout, + tooltip="Filters the Error tab to edges more than 2x worse " + "than IBM's median") + self.acc_bench_details = Accordion( + children=[VBox([self.lbl_bench_details, + self.btn_bench_show_on_map])], layout=W) + self.acc_bench_details.set_title(0, 'Details') + self.acc_bench_details.selected_index = None # collapsed by default + self.lbl_bench_status = HTML("") + self.bench_box = VBox([ + HTML("
Re-measure the device now and re-rank " + "on live numbers. 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.chk_bench_absolute, + self.btn_bench_run, + self.btn_bench_calcheck, + self.lbl_bench_consistency, + self.acc_bench_details, + self.lbl_bench_calcheck, + HBox([self.lbl_bench_reuse, self.btn_bench_reuse, + self.btn_bench_reanalyze], + layout=Layout(align_items='center')), + self.lbl_bench_status, + ], layout=W) + + _diverse_layout = Layout(width=W.width, margin=W.margin, + min_width=W.min_width) + self.chk_diverse_cap = Checkbox( + value=True, + description='Diverse enumeration', + layout=_diverse_layout, + tooltip='Counts only distinct candidates toward the search ' + 'cap · Reference: Diverse enumeration') + + # ── 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 ' + '· Reference: 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) + 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, + self.chk_diverse_cap, + self.chk_guided_search, + self.bench_guided_box])], + 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) 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( + 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)') + # 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': '110px'}, + 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]) + 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') + 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( + description='🌐 Scan all QPUs', button_style='info', layout=W, + tooltip='Run the ancilla sweep on every compatible account ' + 'backend (same norb / min-ancillas as above)') + self.chk_scan_other_families = Checkbox( + value=False, description='include other families', layout=W, + tooltip='Scan every topology family, not just the current one ' + '(cross-family zigzag comparison is apples-to-oranges)') + self.lbl_scan_progress = HTML("") + self.scan_results_box = VBox([]) # ── Inspect Layouts cluster ────────────────────────────── self.dd_lucj_layout = Dropdown( @@ -1210,35 +1572,85 @@ 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( 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)', - layout=W, style={'description_width': 'initial'}) + value='', description='min ancillas per circuit:', + placeholder='blank = auto; or e.g. 2, 2', + layout=W, style={'description_width': 'initial'}, + 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'}) - self.btn_lucj_multi = Button( - description='🤖 Generate Multi-Circuit', - button_style='success', layout=W) + # ── Multi-circuit planner ───────────────────────────────── + # 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='Fast: one circuit at a time', + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width), + tooltip='place circuits one by one instead of planning them ' + 'together · Reference: Multi-circuit planner') + self.int_plans_kept = BoundedIntText( + value=3, min=1, max=50, + description='Plans kept:', + layout=Layout(width='220px'), + style={'description_width': '110px'}, + tooltip='partial plans kept after each circuit ' + '· Reference: 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 ' + '· Reference: 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 · Reference: Multi-circuit planner') + self.joint_params_box = VBox( + [self.int_plans_kept, self.int_cands_per_circuit, + self.ft_boundary_penalty], + 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 + # 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) + # 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("") + # 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. + # user clicks btn_lucj_multi_sweep. self.lucj_multi_detail_box = VBox() # Roles offered by the legend panel — must match plot._LEGEND_ROLE_ORDER. @@ -1318,8 +1730,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 @@ -1508,6 +1919,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 @@ -1553,18 +1967,18 @@ def _build_manual_view(self): ]) def _build_auto_view(self): - """Build the 'Load' nav tab view (General Ansatz mode): four - load-from-outside sections — layout-file upload, paste auto-map, + """Build the 'Load'/Import nav tab view (General Ansatz mode): four + load-from-outside sections — paste auto-map, layout-file upload, session load, style preset load. In LUCJ mode the same nav slot selects ``_build_auto_lucj_view`` via ``nav_bar.value == 'auto_lucj'``. """ return VBox([ - HTML("
📂 Load layout file
"), - self.btn_unified_upload, - HTML("
"), HTML("
✏️ Paste qubit list
"), self.txt_auto, self.btn_auto, + HTML("
"), + HTML("
📂 Load layout file
"), + self.btn_unified_upload, HTML("
"), HTML("
💾 Load Session
"), self.btn_load_session, @@ -1574,6 +1988,41 @@ 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)') + + @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). @@ -1587,44 +2036,113 @@ def _build_auto_lucj_view(self): ``lucj_multi_ancillas`` to override it per sub-circuit (blank falls back to the dropdown). """ - return VBox([ - HTML("
" - "🤖 Auto-LUCJ Layout Engine
"), - HTML("
"), - HTML("
" - "🔬 Single
"), + 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')) + # 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, + self.lucj_min_ancilla, + self.lucj_top_n, self.lucj_chk_score, + self.chk_lucj_diverse, + self.ft_stability_floor, + self.chk_stability_filter, + self.stability_ctrl_box, + self.lbl_lucj_stability, self.btn_lucj_run, + self.lbl_lucj_trunc, self.lbl_lucj_status, - HTML("
" - "📋 Inspect Layouts
"), + self.lbl_lucj_notices, + self.lucj_advanced_acc, + HTML("
"), + HTML(f"
📍 This backend ({name})
"), self.dd_lucj_layout, self.lbl_lucj_detail, - HTML("
"), - HTML("
" - "🔗 Multi
"), + HTML("
"), + 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, + ], layout=Layout(padding='6px')) + # 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, self.lucj_buffer_slider, - self.btn_lucj_multi, + self.multi_advanced_acc, + 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') + tabs.set_title(1, '🔗 Multi') + else: + tabs = Tab(children=[single_panel]) + 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([ + 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 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_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 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, @@ -1659,9 +2177,9 @@ def _build_error_view(self): Returns a ``Tab`` widget with two sub-tabs: * **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). + 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. @@ -1741,8 +2259,46 @@ 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 + #: 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. @@ -1763,6 +2319,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() @@ -1770,8 +2329,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 = ( @@ -2069,7 +2628,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( @@ -2296,6 +2855,7 @@ def _load_device_graph(self, change=None, force=False): prefetched_props=self.state.initial_props) self.state.x_coord, self.state.y_coord, self.state.edges_list = result[0], result[1], result[2] self.state.qubit_ids, self.state.readout_errors, self.state.gate_errors = result[3], result[4], result[5] + self._apply_backend_defaults() self.state.clear_all_layouts() @@ -2306,11 +2866,10 @@ 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 @@ -2350,6 +2909,21 @@ def _load_device_graph(self, change=None, force=False): finally: self._loading_device = False + def _apply_backend_defaults(self): + """Set the per-chip search defaults once per connected backend. + + Diverse enumeration is ON for heavy-hex chips and OFF for the + square-lattice Nighthawk, where the exhaustive search finds so many + layouts that the sieve costs minutes for about 1% LQS. A manual + toggle holds until another backend is connected. + """ + name = self.state.active_backend_name + if name == self._defaults_backend: + return + self._defaults_backend = name + chip = str(self.state.active_chip or '').lower() + self.chk_diverse_cap.value = not chip.startswith('nighthawk') + def _update_view(self, change=None): """Switch the visible content panel based on ``self.nav_bar.value``. @@ -2385,12 +2959,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: @@ -2410,7 +2984,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: @@ -2423,14 +2997,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()] @@ -2510,6 +3083,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 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 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 + 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'] @@ -2921,8 +3519,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) @@ -3214,11 +3812,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/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/inter_qpu.py b/iqmapper/ui/inter_qpu.py index ed7f7f5..56767da 100644 --- a/iqmapper/ui/inter_qpu.py +++ b/iqmapper/ui/inter_qpu.py @@ -31,16 +31,49 @@ returns the `refresh_qpu1_label` hook so `ui.backend_switch` can refresh the QPU-1 switcher label after a backend switch. """ +import contextlib import logging +from types import SimpleNamespace from ipywidgets import VBox, HTML, ToggleButtons +from ..constants import hex_to_rgba from ..html_safe import esc from ..state import SessionState _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. @@ -88,11 +121,22 @@ 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] # race guard: one auto-connect at a time + + # 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 _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 ────────────────────────────────────────── @@ -247,30 +291,129 @@ def refresh_qpu1_label(): toggle.options = options toggle.value = saved_value - # ── Connect-QPU2 handler ──────────────────────────────────── - def _on_connect_qpu2(b): - backend_name = dd_backend_qpu2.value - if not backend_name: - lbl_qpu2_status.value = ( - "" - "Select a backend" - ) + # ── remote-candidate handoff (scan → inter-QPU) ───────── + handoff_cell = getattr(ctx, 'handoff_cell', None) + + def _apply_one_to_slot(d, candidate): + d['alpha'] = []; d['beta'] = []; d['other'] = [] + d['qubits'] = []; d['ancilla'] = []; d['styles'] = {} + defs = d['defaults'] + line = defs['line'] + fills = {'alpha': hex_to_rgba(defs['fill'], 1.0), + 'beta': hex_to_rgba(defs['fill_beta'], 1.0), + 'ancilla': hex_to_rgba(defs['fill_anc'], 1.0)} + d['alpha'] = [str(q) for q in candidate['alpha']] + d['beta'] = [str(q) for q in candidate['beta']] + d['ancilla'] = [str(q) for q in candidate.get('ancillas', [])] + for role in ('alpha', 'beta', 'ancilla'): + for q in d[role]: + d['styles'][q] = {'fill': fills[role], 'line': line, + 'width': 2, 'text_color': '#000000'} + + 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 state.active_service is None: - lbl_qpu2_status.value = ( - "" - "No service connected" - ) - return - - lbl_qpu2_status.value = ( - f"" - f"⏳ Connecting {esc(backend_name)}..." - ) + 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. 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 try: - from ..connection import _check_properties - from ..constants import resolve_coords - # Late import to avoid the ui ↔ ui.inter_qpu cycle that would + 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. + 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)] + + # 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] = (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, + # _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: + # Late import to avoid the ui <-> ui.inter_qpu cycle that would # otherwise trigger at module load time. from . import build_mapper_ui @@ -280,12 +423,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 @@ -295,35 +432,55 @@ 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) - # 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. + + # If this connect was staged from a scan pick for THIS backend, + # paint the chosen candidate now — AFTER the build (which calls + # 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], 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 + + # 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] _state2[0] = s2 _fig2[0] = f2 + _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. + # 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) - # 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: @@ -342,26 +499,18 @@ def _on_connect_qpu2(b): 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 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"
📅 ' + 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))}
") + return None except Exception as e: lbl_qpu2_status.value = ( f"" f"❌ {esc(str(e))}" ) + 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 ─────── + 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, 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, report=None): + """The scan handoff hook (replaces bare staging): stage, then drive the + 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, report) + + # 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 + # 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, _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]) + 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))}.
" + + ("" 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 + btn_connect_qpu2.disabled = True # disable the manual trigger too + lbl_qpu2_status.value = ( + f"
📡 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 + btn_connect_qpu2.disabled = False + + # 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() + err = _connect_qpu2_paint(backend_name, fetched) + if err: # paint reported a failure string + _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, report) + + _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 b5a6715..3c74437 100644 --- a/iqmapper/ui/lucj_panel.py +++ b/iqmapper/ui/lucj_panel.py @@ -4,9 +4,10 @@ Extracted from ui.py for maintainability. All functions receive a `ctx` SimpleNamespace with shared UI state and widgets. """ +import contextlib import logging -from ipywidgets import Dropdown, HTML +from ipywidgets import Button, Dropdown, HBox, HTML, Layout from ..constants import hex_to_rgba from ..html_safe import esc @@ -14,6 +15,109 @@ _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 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: + val, _ = _entry_lqs(entries[0]) + parts.append(f"{k}→{val * 100.0:.1f}%") + return ' · '.join(parts) + + +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 — + 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 "" + + +#: 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', + # data.extract_props, when a scanned backend's snapshot is cached. + '%s: %d of %d %s without a value', +) + + +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. 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) + self._context_getter = context_getter + self.records = [] # list of (backend_context, message) + + def emit(self, record): + try: + if _log_only(record): + return + self.records.append((self._context_getter(), record.getMessage())) + except Exception: + pass + + +@contextlib.contextmanager +def _capture_qpu_notices(context_getter): + """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. + 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('iqmapper') + 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 + + class _SnapshotProps: """UI-layer adapter: dict-array calibration (state.qubit_props_data / gate_props_data + edges_list) → the BackendProperties surface the @@ -72,32 +176,47 @@ 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 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 + chk_lucj_diverse = ctx.chk_lucj_diverse + chk_diverse_cap = getattr(ctx, 'chk_diverse_cap', 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) + 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 + lbl_lucj_notices = ctx.lbl_lucj_notices dd_lucj_layout = ctx.dd_lucj_layout lbl_lucj_detail = ctx.lbl_lucj_detail lucj_multi_norbs = ctx.lucj_multi_norbs lucj_multi_ancillas = ctx.lucj_multi_ancillas lucj_buffer_slider = ctx.lucj_buffer_slider - btn_lucj_multi = ctx.btn_lucj_multi + 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) + joint_params_box = getattr(ctx, 'joint_params_box', None) + 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 + 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 - _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() @@ -129,6 +248,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. + 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): @@ -155,6 +282,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() @@ -198,16 +337,454 @@ 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: 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']) + 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 {pct} " + f"{scale}; internal ranking " + f"sum {entry['additive_score']:.4f}, " + f"{esc(str(entry.get('source', '')))}") + # 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}
{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})
{counts}
" + ) + # 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. + dd_lucj_layout.tooltip = ( + 'LQS = circuit-level fidelity; "(template)" = fallback ' + 'heuristic \u00b7 Reference: LQS') 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. + 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]) + + # ── 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 + + # ── Temporal anchoring: one epoch per search ───────────────────── + def _selected_date_anchor(): + """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_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')}" + + # ── 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 (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 + 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, + # 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 — + # combined_sweep passes it to the exhaustive half only. + 'diverse_cap': bool(getattr(chk_diverse_cap, 'value', True)), + } + + # ── 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 { + '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 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. + """ + from ..engine_select import combined_sweep + return combined_sweep(norb, backend, props, use_guided=_guided_on(), + **kwargs, **_guided_params()) + + 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' + (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 _guided_on() else 'none' + + if chk_guided_search is not None: + chk_guided_search.observe(_on_guided_toggle, names='value') + _on_guided_toggle() + + # ── Multi-circuit planner: Joint (default) or Sequential (Fast) ── + def _selected_planner(): + """'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', 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, 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 (planner or _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_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: + 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 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 Fast is off.""" + if joint_params_box is not None: + joint_params_box.layout.display = ( + '' if _selected_planner() == 'joint' else 'none') + + 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 + # active backend's reference in the scan table, 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 + + all_layouts, num_ab = get_all_zigzag_layouts( + num_orbitals=norb, + backend=state.active_backend, + score=lucj_chk_score.value, + props=_local_scoring_props(), # loaded snapshot, not live + 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}{_epoch_suffix()}
") + 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}{_epoch_suffix()}
") + + # ── Stratified ancilla sweep (the default) ─────────────────── + def _generate_sweep(norb): + + # exact same params the scan uses (min_bridges / top_n / hybrid). + kwargs = _sweep_kwargs_from_ui() + + # pre-rank on the same epoch as the circuit-score (selected date). + scoring_props = _local_scoring_props() + 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 + res = sweep_with_stability( + 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'], + 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. + _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 = _run_sweep( + 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. + 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 + # 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]: + pct, is_tmpl = _entry_lqs_pct(entry) + suffix = " (template)" if is_tmpl else "" + dd_opts.append(( + f"k={k} · #{entry['rank_in_stratum']} · LQS {pct}{suffix}" + f"{_source_tag(entry)}", + len(flat), + )) + 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: 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. + # With the diverse reservoir engaged, the ℹ line below already says + # this stratum's cap was reached AND how much it saw — so repeating + # it as a warning is noise that also contradicts it ("ranking may be + # non-exhaustive" reads as a problem; "kept 2,000 diverse candidates + # of 4,498 seen" reads as what actually happened). Warn only about + # strata the reservoir did NOT cover. + _reservoir_ks = {k for k, st in (res.get('reservoir') or {}).items() + if st.get('kept')} + _trunc_ks = sorted( + (k for k, m in res.get('per_stratum', {}).items() + if m.get('truncated') and k not in _reservoir_ks), reverse=True) + if res['vf2_truncated'] and _trunc_ks: + ks_txt = ', '.join(f"k={k}" for k in _trunc_ks) + cap = res.get('mapping_cap') + cap_txt = f"{cap:,}" if isinstance(cap, int) else "the" + lbl_lucj_trunc.value = ( + f"
⚠️ direct search truncated at " + f"{esc(cap_txt)} mappings for {esc(ks_txt)} — ranking may " + f"be non-exhaustive.
") + else: + lbl_lucj_trunc.value = "" + + # 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: + # 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"
✅ {len(flat)} layout" + f"{'s' if len(flat) != 1 else ''} found{vin_txt}
") + else: + lbl_lucj_status.value = ( + "
⚠️ Sweep produced no candidates.
") + # ── Single circuit LUCJ generate ───────────────────────────── def _on_lucj_generate(b): if state.active_backend is None: @@ -223,73 +800,21 @@ def _on_lucj_generate(b): btn_lucj_run.disabled = True btn_lucj_run.description = '⏳ Generating...' lbl_lucj_status.value = "" + lbl_lucj_trunc.value = "" + lbl_lucj_notices.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=_local_scoring_props(), # loaded snapshot, not live - 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}{_epoch_suffix()}
") - 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}" - f"{_epoch_suffix()}
") - + # 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: + # 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"
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 + + 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, anchor=None): + """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.""" + # "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 = ( + "
" + "🛡 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: + total = len(stab.get('excluded_final', [])) + 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 = ( + f"
🛡 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.""" + 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') + 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 + 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): + """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: + props = get_props(get_backend(r['name'])) + 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) + scorer = _scan_circuit_score(props) + for k, entries in sweep.get('strata', {}).items(): + for e in entries: + if e.get('lqs_circuit') is None: + try: + e['lqs_circuit'] = scorer(e) + except Exception as exc: + # Annotation failure is data absence — surface + # it in the notices with backend + stratum + reason, + # never a silent 0.0. + e['lqs_circuit'] = None + _log.warning("circuit score unavailable for %s " + "k=%d: %s", r['name'], k, exc) + + def _scan_backends(eligible, norb, get_backend, get_props, use_filter): + """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. + 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() # 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 + # 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: + # 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=''): + # Preserve the '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)) + r['floor_excluded'] = (sweep.get('floor_excluded', 0) + if sweep is not None else 0) + return result + + _scan = {'progress': {}, 'order': []} + _STATUS_ICON = {'start': '⏳', 'ok': '✓', 'skipped': '·', 'error': '✗'} + + def _clear_scan_results(): + # 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 + _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()) + + def _render_progress_line(): + chips = [] + for name in _scan['order']: + st, detail = _scan['progress'].get(name, ('', '')) + txt = f"{esc(str(name))} {_STATUS_ICON.get(st, '')}" + if st in ('start', 'error') and detail: + txt += f" {esc(str(detail))}" + chips.append(txt) + lbl_scan_progress.value = ( + ("
" + + " · ".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. + # Track the active backend SYNCHRONOUSLY (before marshaling) so log + # records emitted by the sweep that follows are attributed correctly. + if status == 'start': + _scan['current'] = name + 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']) + pct, is_tmpl = _entry_lqs_pct(entry) + suffix = " (template)" if is_tmpl else "" + 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 + summary (the full string lives in the line's tooltip).""" + 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' + if r.startswith('needs'): + return 'too small' + if r.startswith('family unknown'): + return 'unknown family' + return r or 'skipped' + + def _render_targets(targets): + # 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( + f"
" + f"{line}
")] + + _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: + report('error', "QPU 2 panel unavailable here — open from " + "QPU 1's scan") + return + 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 + 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.""" + if not 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.""" + 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, 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 [] + 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')) + status = HTML("") # handoff outcome, next to btn + report = _handoff_reporter(status) + + def _sync(idx): + r = rows[idx] + det.value = detail_fn(r) + ok = open_ok_fn(r) + btn.disabled = not ok + 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') + + 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, report) # one OR a list + + btn.on_click(_open) + _sync(0) + return [dd, det, HBox([btn, status], + layout=Layout(align_items='center'))] + + def _scan_detail_line2(r): + """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 = [] + 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 ·
" + sweep = r.get('sweep') or {} + strata = sweep.get('strata', {}) + if not strata or r.get('best_lqs') is None: + return box + "no candidates" + 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('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=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 + + 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 "" + from collections import OrderedDict + groups = OrderedDict() + for bctx, msg in notices: + groups.setdefault(bctx, OrderedDict()) + groups[bctx][msg] = groups[bctx].get(msg, 0) + 1 + parts = [] + 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)}") + # 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) + "
" + "
") + + 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): + scan_result, notices = payload + _render_results(scan_result) + _append_notices(notices) + 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, _detect_family + from ..props_shim import make_scan_get_props + + norb = lucj_norb_slider.value + try: + family = _detect_family(state.active_backend) + except Exception: + family = None + + _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) + + # 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']] + if not eligible: + lbl_scan_progress.value = ( + "
No eligible " + "backends for this norb / family scope.
") + return + + _scan['norb'] = norb + btn_scan_qpus.disabled = True + 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(): + # 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: + # 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_b, + get_props, use_scan_filter) + # Circuit-level LQS per backend — one scale everywhere. + _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) + + btn_scan_qpus.on_click(_on_scan_click) + + # ── 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 # 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']) + _refresh() + _get_export() + + #: Keys of a multi-circuit result that belong to one placement plan. + _PLAN_KEYS = ('circuits', 'total_product', 'total_lqs_circuit', + 'placed_qubits', 'buffer_qubits_used', 'boundary_couplers', + 'joint_total', 'failed_at') + + def _multi_plans(result): + """Complete plans (every circuit placed), best first: the planner's + `plans` when the result carries them, else the result's own plan + when it is complete. Each item is a dict of `_PLAN_KEYS`.""" + if result.get('plans'): + return [p for p in result['plans'] if p.get('circuits') + and p.get('failed_at') is None] + if result.get('failed_at') is None and result.get('circuits'): + return [{k: result.get(k) for k in _PLAN_KEYS}] + return [] + + def _plan_label(n, plan): + """'Plan 1 · total 48.2% · C1 79.2% + C2 61.0%'.""" + total, tmpl, parts = 1.0, False, [] + for c in plan['circuits']: + pct, is_tmpl = _entry_lqs_pct(c['chosen']) + tmpl = tmpl or is_tmpl + lqs = c['chosen'].get('lqs_circuit') + total *= lqs if lqs is not None else c['chosen']['product_score'] + parts.append(f"C{c['circuit_idx'] + 1} {pct}") + return (f"Plan {n} · total {total * 100.0:.1f}%" + f"{' (template)' if tmpl else ''} · " + " + ".join(parts)) + + def _multi_failed_banner(result): + i = result.get('failed_at') + if i is None: + return "" + return ( + f"
⚠️ 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(): + 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 _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 _on_plan_select(result, plans, j): + """Apply plan `j` of `result` to every circuit at once.""" + if _multi_sweep['replan_in_flight']: + return + new_result = dict(result) + new_result.update(plans[j]) + new_result['selected_plan'] = j + _multi_sweep['result'] = new_result + _apply_multi_sweep(new_result) + _render_multi_sweep_output(new_result) + + def _plans_dropdown(result): + """The Plans menu over the complete plans; [] when there are none.""" + plans = _multi_plans(result) + if not plans: + return [] + selected = min(result.get('selected_plan', 0), len(plans) - 1) + dd = Dropdown(options=[(_plan_label(n, p), n - 1) + for n, p in enumerate(plans, start=1)], + value=selected, description='Plans:', + layout=Layout(width=W.width, margin=W.margin, + min_width=W.min_width), + style={'description_width': 'initial'}) + dd.observe(lambda ch: ch['new'] is not None and ch['new'] != selected + and _on_plan_select(result, plans, ch['new']), + names='value') + _multi_sweep['dropdowns']['plans'] = dd + return [dd] + + def _build_multi_override_dropdowns(result): + from ..fit_check import LaterFit + _multi_sweep['dropdowns'] = {} + widgets = _plans_dropdown(result) + fit = LaterFit(result) + 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. + # An alternative after which a later circuit no longer fits is + # left out (the chosen layout always stays). + entries = sorted( + (e for k in c['strata'] for e in c['strata'][k]), + key=_multi_override_sort_key) + flat, opts, hidden = [], [], 0 + for e in entries: + if e is not c['chosen'] and not fit.later_circuits_fit(i, e): + hidden += 1 + continue + 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 hidden: + widgets.append(HTML( + f"
" + f"{hidden} alternative{'s' if hidden != 1 else ''} " + f"hidden: the other circuits would not fit
")) + 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): + n = len(result['circuits']) + lbl_lucj_multi.value = ( + f"
✅ {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) + + 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(): + with _capture_qpu_notices(lambda: f'replan C{i + 1}') as handler: + new_result = _replan_multi(result, i, choice) + return (new_result, list(handler.records)) + + 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 + _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.") + "❌ 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 - raw = lucj_multi_norbs.value.strip() - if not raw: + btn_lucj_multi_sweep.disabled = True + btn_lucj_multi_sweep.description = '⏳ Sweeping...' + 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() + 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' + + def _work(): + with _capture_qpu_notices(lambda: 'multi sweep') as handler: + 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'], + 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) # 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() + 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_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: + # 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, unsupported=()): + """Complete batches first, by batch metric; then partial batches (more + 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: + 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.""" + 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 + if not _batch_complete(local, len(norbs)): + return None + return local + + 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] + 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, unsupported) + + 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 + # 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, 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') + 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 ''}") + + 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 {}))}" + + def _open_ok(r): + res = r.get('sweep') or {} + 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', [])] + + 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( + 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: lbl_lucj_multi.value = ( - "❌ Enter norb values (e.g. 8, 8)") + "❌ No backend " + "connected.") return - try: - norb_list = [int(x.strip()) for x in raw.split(',') if x.strip()] - except ValueError: + if state.active_service is None: lbl_lucj_multi.value = ( - "❌ Invalid norb values") + "❌ No service " + "connected — cannot scan other QPUs.") return - if len(norb_list) < 1: + 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 - # 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: + 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 + 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)) + # 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, + 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'], + # 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}]} + 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: - 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"❌ 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.") - 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 - num_circuits.value = 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"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in 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) - ) - + 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) + # 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' + # 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, + min_bridges=kwargs['min_bridges'], top_n=kwargs['top_n'], + sweep_fn=_batch_sweep_fn) + + def _done(result): + _reset() + _render_batch_results(result, active_name, norbs, + batch['unsupported']) + + def _err(exc): + _reset() 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.
") + f"
❌ batch scan " + f"failed: {esc(str(exc))}
") - ctx.update_view() + scan_spawn_bg(_work, on_done=_done, on_error=_err) - 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) - - # ── Re-optimization (F3) ───────────────────────────────────── - def _reoptimize_downstream(changed_idx): - try: - from ..auto_lucj import reoptimize_after_change + btn_scan_batch.on_click(_on_scan_batch) - 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"α: {', '.join(str(q) for q in entry['alpha'])}
" - f"β: {', '.join(str(q) for q in 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/png_export.py b/iqmapper/ui/png_export.py index e7df4e9..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 ( @@ -42,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. @@ -64,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. @@ -144,10 +130,9 @@ def setup_png_export(ctx): out — Output widget for log messages Optional ctx fields: - fig — the live FigureWidget. Supplied, its visible - error-map colorbars are copied onto the export - figure (the static renderer has none of its - own). Omitted, the PNG is written without them. + 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 @@ -158,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, @@ -246,10 +232,10 @@ def _on_confirm(b): margin=margin_px, crop_to_selection=crop_checkbox.value, ) - # The static renderer draws no colorbars — carry the live - # figure's across so the PNG keeps the error-map scales. - _append_live_colorbars(export_fig, getattr(ctx, 'fig', None), - plot_mod) + # 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/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 = ( "
" - 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"· Reference: 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 cabac0a..4c71c9c 100644 --- a/iqmapper/ui/time_panel.py +++ b/iqmapper/ui/time_panel.py @@ -1,8 +1,7 @@ """ ui.time_panel.py — Unified time/delta panel for the ERROR tab. -Drop-in replacement for the Snapshot/Range/Delta widgets currently -scattered in ui.py. Two clean orthogonal blocks: +Two orthogonal blocks: Block 1 — CALIBRATION SOURCE (pick one) • Live (current calibration) @@ -17,49 +16,19 @@ • Previous in sequence (slider's previous point — step-by-step) The panel is self-contained: it owns all widgets and callbacks, keeps -state in `SessionState`, and calls back into your existing `data` and +state in `SessionState`, and calls back into the `data` and `export` modules. No other UI code needs to know about it. -──────────────────────────────────────────────────────────────────── -USAGE (in ui.py, inside build_mapper_ui, ERROR tab assembly): - - from .time_panel import build_time_panel - - time_panel, time_api = build_time_panel( - state=state, - data_mod=data_mod, # your data.py - export_mod=export_mod, # your export.py - refresh_plot=_refresh, # your existing _refresh() - load_device_graph=_load_device_graph, - spawn_bg=None, # optional background thread helper - ) - - _err_tab_map = VBox([ - ... # property selector, threshold filter, etc. - time_panel, # <- single widget replaces 6+ blocks - ... # qubit info, calibration date label - ]) - -Delete from ui.py: time_mode, dp_snapshot_date, txt_snapshot_hour, - dd_known_cals, btn_snapshot_load, btn_scan_day, lbl_snapshot_status, - chk_delta_ref, dp_ref_date, txt_ref_hour, dd_known_ref, - btn_ref_compute, btn_scan_ref_day, lbl_ref_status, - snapshot_panel, range_panel, ref_panel, - hist_start_date, hist_end_date, btn_fetch_hist, hist_progress, - hist_status, hist_slider_box. - -ui_calibration.py: removed from the tree (its logic lives here now). -──────────────────────────────────────────────────────────────────── +Built by ``MapperUIBuilder`` through ``build_time_panel`` and placed in +the ERROR tab. Dependencies: - ipywidgets (already required by the app) - numpy (already required) - - your data.py must expose: get_props_for_datetime, scan_day_calibrations, + - data.py must expose: get_props_for_datetime, scan_day_calibrations, fetch_calibration_history, apply_history_snapshot, - list_known_calibrations, _extract_last_update - - your export.py must expose: compute_error_delta - - your cache.py (SQLite, new) is used if present; otherwise the - older _load_calibration function from data.py is used as fallback + list_known_calibrations, _extract_last_update, _load_calibration + - export.py must expose: compute_error_delta """ from __future__ import annotations @@ -204,8 +173,7 @@ def _format_hm_from_ts(ts: str, ref_date=None) -> 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 @@ -314,8 +268,22 @@ def resolve_reference_props(state, data_mod) -> Optional[Tuple[dict, dict]]: # ───────────────────────────────────────────────────────────────────── def describe_current_view(state) -> str: - """What is the panel showing right now?""" + """What is the panel showing right now? + + A measured epoch (from `iqmapper.benchmark`) is installed through the same + channel as the live calibration — it replaces `qubit_props_data` / + `gate_props_data` without changing `time_mode`. So the header read "Live + calibration" while the map was in fact showing benchmark measurements, + which is exactly the confusion the calibration label exists to prevent. + A measured epoch therefore takes precedence in this description, and says + whether the values are absolute or rescaled. + """ backend = state.active_backend_name or '?' + epoch = getattr(state, '_measured_epoch', None) + if epoch is not None and state.time_mode == 'live': + mode = 'relative' if getattr(epoch, 'relative', False) else 'absolute' + return (f"Measured {epoch.time_label()} (L{epoch.level}, {mode}) " + f"— {backend}") if state.time_mode == 'live': return f"Live calibration — {backend}" if state.time_mode == 'point': @@ -383,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 @@ -813,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. @@ -1015,10 +982,8 @@ def _build_widgets(self): # ── 3. Per-mode sub-panels ────────────────────────────────── - # 3a — Live. Deliberately empty: the panel header already states - # "Showing: Live calibration — ", so an info line here - # only repeated it. _show_sub toggles this box's display like any - # other sub-panel, which works fine with no children. + # 3a — Live: no sub-panel content needed; the header already states + # what is shown ("Showing: Live calibration — "). self.sub_live = VBox([]) # 3b — Snapshot @@ -1183,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) @@ -1233,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( @@ -1254,140 +1213,9 @@ 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 Reference: 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 Reference: 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/pyproject.toml b/pyproject.toml index 357eac2..0688e9b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta" [project] name = "i-qmapper" -version = "0.0.5" +version = "0.1.0" 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"] @@ -39,16 +39,22 @@ dependencies = [ ] [project.optional-dependencies] +benchmark = ["qiskit-experiments>=0.12"] png = ["kaleido"] 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.pytest.ini_options] +markers = [ + "integration: exercises real qiskit-experiments objects against a local fake backend (no network, no QPU); skipped when the optional stack is absent", +] + [tool.setuptools.packages.find] where = ["."] include = ["iqmapper", "iqmapper.*"] diff --git a/tests/conftest.py b/tests/conftest.py index cf74f73..79b97b1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,10 @@ import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +# ...and the tests directory itself, so a test module can reuse another's +# fixture (test_guided_search cross-checks against test_ancilla_sweep's +# GOOD/BAD-block backend rather than cloning it and letting the two drift). +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # Fixtures for iqmapper.export pure-function tests @@ -59,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_ancilla_sweep.py b/tests/test_ancilla_sweep.py new file mode 100644 index 0000000..c7e790d --- /dev/null +++ b/tests/test_ancilla_sweep.py @@ -0,0 +1,478 @@ +"""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: + + 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 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 + +import pytest +import rustworkx + +from types import SimpleNamespace + +from iqmapper.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() + + +# ── 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)) + + +# ── regression — the good-region k-1 layout is derived for free ───────── + +def test_kminus1_variant_present(backend, props): + """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' + 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") + + +# ── 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 + + +# ── 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). 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 + 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") + + +# ── circuit_score_fn on the sliced survivors only ────────────────────── + +def test_circuit_score_fn_scores_widened_window(backend, props): + """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): + 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 # 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_sinks_below_slice_not_aborts(backend, props): + """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): + 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 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): + """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 + + +# ── 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") + + +# ── 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) + + +# ── 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]) + + +# ── 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]) + + +# ── 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 + + +# ── Hybrid mode ──────────────────────────────────────────────────────── + +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'=3.10 deprecation + # with no running loop — init_main_loop must NOT let it escape. + import sys + import types + + class _IOLoop: + @staticmethod + 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 None # no current IOLoop headless + + 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) + + import asyncio + 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 = [] + async_util.marshal_to_main(lambda: ran.append(1)) + assert ran == [1] + + +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 + + async def _main(): + 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' + + +# ── 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) + + +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 rather than give 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) + + +# ── 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("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' + 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()) + + +# ── 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() + + +# ── 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 = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append # defer — don't run + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) captured = [] 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 + 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: # drain the deferred queue + for cb in queued: cb() - assert len(captured) == 1, "on_error must run exactly once" - assert isinstance(captured[0], ValueError) + assert len(captured) == 1 and 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.""" +def test_on_done_receives_result_with_deferred_scheduler(monkeypatch, + _capture_isolation): queued = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append - + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) sentinel = object() captured = [] - def _ok(): - return sentinel - - def _on_done(r): - captured.append(r) - - t = async_util.default_spawn_bg(_ok, on_done=_on_done) + 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_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() - +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 = [] - def _boom(): - raise RuntimeError("inline-boom") - - def _on_error(e): - captured.append(e) - - t = async_util.default_spawn_bg(_boom, on_error=_on_error) + 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 - assert isinstance(captured[0], RuntimeError) + assert len(captured) == 1 and isinstance(captured[0], RuntimeError) assert str(captured[0]) == "inline-boom" -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.""" +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 = [] - async_util._MAIN_LOOP_SCHEDULER = queued.append + monkeypatch.setattr(async_util, 'marshal_to_main', queued.append) - def _ok(): - return 1 - - def _on_done_that_raises(_r): + def _raises(_r): raise RuntimeError("callback failure — must be contained by _safe") - 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: + 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_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 new file mode 100644 index 0000000..04bc2dd --- /dev/null +++ b/tests/test_auto_panel_ui_polish.py @@ -0,0 +1,435 @@ +"""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 logging + +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) + # 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 + + +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} + + +# ── 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 + + +# ── 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}") + + +# ── 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") + + +# ── 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) + + +# ── 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' + + +# ── the search (engine widgets: see test_search_ui.py) ───────────────────── + +def test_exhaustive_still_routes_to_the_frozen_sweep(monkeypatch): + b, _ = _build(monkeypatch) + called = [] + monkeypatch.setattr( + 'iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: called.append(k) or { + '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}) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + assert called, 'the frozen sweep was not used for Exhaustive' + assert 'mapping_cap' in called[0], 'VF2 must still receive its cap' + + +def test_guided_results_render_through_the_existing_display(monkeypatch): + """The display code must not be able to tell the engines apart.""" + import sys + sys.path.insert(0, 'tests') + from test_ancilla_sweep import FakeProps, make_backend + from iqmapper.guided_search import guided_sweep + + b, _ = _build(monkeypatch) + res = guided_sweep(4, make_backend(), FakeProps(), min_bridges=1, top_n=3) + + 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' + + +# ── diverse enumeration ──────────────────────────────────────────────────── + +def test_diverse_enumeration_checkbox_defaults_on(monkeypatch): + b, _ = _build(monkeypatch) + assert b.chk_diverse_cap.value is True + assert any(w is b.chk_diverse_cap + for w in _descendants(b.lucj_advanced_acc)), \ + 'the checkbox is not in the Advanced accordion' + tip = b.chk_diverse_cap.tooltip + assert 'distinct candidates' in tip, tip + assert 'Reference: Diverse enumeration' in tip, tip + assert len(tip) <= 90, f'tooltip is {len(tip)} chars' + + +def test_diverse_enumeration_reaches_the_sweep(monkeypatch): + b, _ = _build(monkeypatch) + seen = {} + monkeypatch.setattr( + 'iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: seen.update(k) or { + '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, + 'reservoir': {}, 'reservoir_notices': []}) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + assert seen.get('diverse_cap') is True + + seen.clear() + b.chk_diverse_cap.value = False + b.btn_lucj_run.click() + assert seen.get('diverse_cap') is False + + +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, + 'additive_score': 0.1, 'lqs_circuit': 0.8, 'rank_in_stratum': 1, + 'source': 'vf2'} + note = ('hybrid k=1: cap reached — kept 2,000 diverse candidates, ' + 'skipped 34,812 near-duplicates') + monkeypatch.setattr( + 'iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: { + 'strata': {1: [entry]}, 'k_max_effective': 1, 'min_bridges': 1, + 'vf2_truncated': True, 'n_raw_embeddings': 2000, + 'n_candidates_scored': 2000, 'excluded_qubits': [], + 'per_stratum': {1: {'n_direct': 2000, 'n_derived': 0, + 'truncated': True, 'shuffled': False}}, + 'mapping_cap': 2000, + 'reservoir': {1: {'kept': 2000, 'skipped_similar': 34812}}, + 'reservoir_notices': [note]}) + + b.lucj_ancilla_dd.value = -1 + 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 '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) + + +# ── 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, + 'additive_score': 0.1, 'lqs_circuit': 0.8, + 'rank_in_stratum': 1, 'source': 'vf2'} + + +def _capped_result(*, reservoir, notices): + """A sweep result whose k=3 stratum hit the cap.""" + return { + 'strata': {3: [dict(_CAP_ENTRY)]}, 'k_max_effective': 3, + 'min_bridges': 3, 'vf2_truncated': True, + 'n_raw_embeddings': 2000, 'n_candidates_scored': 2000, + 'excluded_qubits': [], + 'per_stratum': {3: {'n_direct': 2000, 'n_derived': 0, + 'truncated': True, 'shuffled': False}}, + 'mapping_cap': 2000, + 'reservoir': reservoir, 'reservoir_notices': notices, + } + + +def test_reservoir_replaces_the_truncation_warning(monkeypatch): + """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)') + monkeypatch.setattr( + 'iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: _capped_result( + reservoir={3: {'kept': 2000, 'skipped_similar': 2498, + 'offered': 4498}}, + notices=[note])) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + + assert b.lbl_lucj_trunc.value == '', ( + f'the ⚠️ banner was not suppressed: {b.lbl_lucj_trunc.value}') + status = b.lbl_lucj_status.value + assert 'cap reached' not in status, status + assert 'non-exhaustive' not in status + + +def test_the_warning_survives_when_diverse_cap_is_off(monkeypatch): + """With no reservoir there is nothing else saying the cap was hit.""" + b, _ = _build(monkeypatch) + monkeypatch.setattr( + 'iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: _capped_result(reservoir={}, + notices=[])) + + b.chk_diverse_cap.value = False + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + + banner = b.lbl_lucj_trunc.value + assert '⚠️ direct search truncated at' in banner, banner + assert '2,000 mappings for k=3' in banner, banner + assert 'non-exhaustive' in banner + + +def test_a_stratum_the_reservoir_missed_still_warns(monkeypatch): + """Mixed case: k=3 covered by the reservoir, k=2 truncated without it.""" + b, _ = _build(monkeypatch) + result = _capped_result( + reservoir={3: {'kept': 2000, 'skipped_similar': 10, 'offered': 2010}}, + notices=['hybrid k=3: cap reached — kept 2,000 diverse candidates, ' + 'skipped 10 near-duplicates (of 2,010 seen)']) + result['per_stratum'][2] = {'n_direct': 2000, 'n_derived': 0, + 'truncated': True, 'shuffled': False} + result['strata'][2] = [dict(_CAP_ENTRY)] + monkeypatch.setattr('iqmapper.ancilla_sweep.sweep_ancilla_layouts', + lambda norb, backend, props, **k: result) + + b.lucj_ancilla_dd.value = -1 + b.btn_lucj_run.click() + + banner = b.lbl_lucj_trunc.value + assert 'k=2' in banner, banner + assert 'k=3' not in banner, 'the reservoir-covered stratum was re-warned' diff --git a/tests/test_auto_subpanels.py b/tests/test_auto_subpanels.py new file mode 100644 index 0000000..687c504 --- /dev/null +++ b/tests/test_auto_subpanels.py @@ -0,0 +1,126 @@ +"""Auto-tab Single/Multi subpanels, candidate-detail declutter, and the +export-is-auto-current pin. +""" +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("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() + b.chk_guided_search.value = False # stubbed exhaustive engine only + return b, state + + +# ── 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' + # 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' + assert b.btn_scan_batch in b._auto_multi_panel.children + assert b.btn_lucj_multi_sweep in b._auto_multi_panel.children + + +# ── 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 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. + assert b.lucj_multi_ancillas.tooltip == 'min ancillas per circuit (blank = auto)' + assert 'Legacy' not in (b.lucj_multi_ancillas.tooltip or '') + + +# ── candidate detail shows counts, never qubit index lists ────────────────── + +def test_detail_panel_counts_not_qubit_lists(monkeypatch): + b, state = _build(monkeypatch) + 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() + 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 + + +# ── 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 + 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_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_batch_scan_active.py b/tests/test_batch_scan_active.py new file mode 100644 index 0000000..d6a337b --- /dev/null +++ b/tests/test_batch_scan_active.py @@ -0,0 +1,146 @@ +"""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.chk_fast_multi.value = True # local run on the stubbed planner + 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)) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py new file mode 100644 index 0000000..e8cd8bd --- /dev/null +++ b/tests/test_benchmark.py @@ -0,0 +1,1657 @@ +"""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. +""" +import json +import os +import types +from types import SimpleNamespace + +import numpy as np +import pytest +import rustworkx + +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 + self.device_components = list(qubits or []) + 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_layer'] + assert rb, 'no layered 2Q RB specs' + covered = {tuple(p) for spec in rb for p in spec.params['pairs']} + assert covered == {(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) + + # Each layer is ONE parallel experiment, so its pairs must be disjoint. + for spec in rb: + seen = set() + for pair in spec.params['pairs']: + assert not (seen & set(pair)), f'layer {spec.layer} reuses a qubit' + seen |= set(pair) + # 30 circuits per layer, whatever the number of pairs in it. + assert bench._spec_circuits(spec) == 30 + + +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_layer'} + + 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 = {tuple(p) for s in plan.specs if s.kind == 'rb2q_layer' + for p in s.params['pairs']} + 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_layer': + raw[idx] = [_Res(name='EPG', value=0.004, qubits=[1, 2])] + + 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_layer': + raw[idx] = [_Res(name='EPG', value=float('nan'), + qubits=[1, 2])] # 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) == {} + + +@pytest.mark.skipif(bench.have_qiskit_experiments(), + reason='the extra IS installed here; nothing to miss') +def test_make_runtime_runner_raises_the_documented_install_hint(): + """With no qiskit-experiments installed the hint names the extra. + + Environment-dependent by nature, so it is skipped where the extra is + present. Call-shape contracts live in test_benchmark_runtime_contract.py. + """ + with pytest.raises(ImportError, match=r'i-qmapper\[benchmark\]'): + bench.make_runtime_runner(object()) + + +# ── 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 documented one. + 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 + + +# ── 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_layer_count_not_edge_count(): + """Layering is the whole saving: 44 disjointly-colourable edges cost the + same as 4 if they fit the same number of layers.""" + coupling = _line_edges(127) + # A path graph 2-colours, so any number of path edges needs 2 layers. + 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.circuits == few.circuits, ( + 'more edges in the same layers must not add circuits') + # ...and a plan with MORE layers does cost more. + one_edge = bench.estimate_cost(bench.build_plan( + 2, bench.Targets([0, 1], coupling[:1]), 127, coupling)) + assert few.circuits >= one_edge.circuits + + +# ── 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.""" + coupling = _line_edges(156) + for n in (3, 10, 156): + plan = bench.build_plan(1, bench.Targets(list(range(n)), []), 156, + coupling) + assert bench.plan_circuit_count(plan) == 2, f'{n} qubits' + assert len([s for s in plan.specs if s.kind == 'readout']) == 1 + + +def test_level2_is_bounded_by_layers_not_edges(): + """44 edges must cost at most 2 + n_layers x 30 circuits.""" + coupling = _line_edges(64) + targets = bench.Targets(list(range(45)), coupling[:44]) + plan = bench.build_plan(2, targets, 64, coupling) + + layers = [s for s in plan.specs if s.kind == 'rb2q_layer'] + assert 0 < len(layers) <= 3, f'{len(layers)} layers for a path graph' + assert bench.plan_circuit_count(plan) <= 2 + 3 * 30 + # Every target edge is covered exactly once, and layers stay disjoint. + covered = [tuple(p) for s in layers for p in s.params['pairs']] + assert sorted(covered) == sorted(coupling[:44]) + assert len(covered) == len(set(covered)) + + +def test_full_chip_level3_is_about_134_circuits(): + """The number that decides whether the job is accepted at all. + + 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()] + plan = bench.build_plan(3, bench.Targets([], []), 156, coupling) + + circuits = bench.plan_circuit_count(plan) + assert abs(circuits - 134) <= 10, f'{circuits} circuits, expected ~134' + assert bench.plan_shots(plan) == circuits * 1000 + assert len(bench.split_for_submission(plan)) == 1, 'L3 must fit one job' + ok, reason = bench.plan_is_submittable(plan) + assert ok, reason + + +def test_split_never_drops_an_experiment(): + coupling = _line_edges(64) + plan = bench.build_plan(2, bench.Targets(list(range(45)), coupling[:44]), + 64, coupling) + chunks = bench.split_for_submission(plan) + assert sum(len(c.specs) for c in chunks) >= len(plan.specs) + kinds_in = sorted(s.kind for s in plan.specs) + kinds_out = sorted(s.kind for c in chunks for s in c.specs) + assert kinds_out[:len(kinds_in)] == kinds_in or set(kinds_out) == set(kinds_in) + for chunk in chunks: + assert chunk.shots <= bench._JOB_SHOT_BUDGET + + +def test_an_over_budget_plan_is_split_into_several_jobs(): + """A plan bigger than one job's shot budget must chunk, not fail.""" + coupling = _line_edges(64) + plan = bench.build_plan(2, bench.Targets(list(range(45)), coupling[:44]), + 64, coupling) + huge = 200_000 # shots per circuit + chunks = bench.split_for_submission(plan, huge) + assert len(chunks) > 1, 'an over-budget plan must split' + for chunk in chunks: + assert chunk.shots <= bench._JOB_SHOT_BUDGET + + +def test_planned_count_reflects_the_plan_not_the_targets(): + """L1 targets edges but measures none, so it must still read complete.""" + coupling = _line_edges(8) + targets = bench.Targets([0, 1, 2, 3], [(0, 1), (1, 2), (2, 3)]) + l1 = bench.build_plan(1, targets, 8, coupling) + assert bench.plan_planned_count(l1) == (4, 0) + l2 = bench.build_plan(2, targets, 8, coupling) + assert bench.plan_planned_count(l2) == (4, 3) + + +def test_summary_line_states_circuits_shots_and_jobs(): + graph = rustworkx.generators.heavy_hex_graph(9) + coupling = [tuple(e) for e in graph.edge_list()] + cost = bench.estimate_cost(bench.build_plan(3, bench.Targets([], []), 156, + coupling)) + assert 'circuits' in cost.text and 'shots' in cost.text + assert '1 job' in cost.text + assert 'estimate' in cost.text + + +# ── an empty epoch is a failure ──────────────────────────────────── + +def test_epoch_reports_emptiness_partiality_and_completeness(): + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(1, bench.Targets([1, 2], []), 8, coupling) + + empty = bench.results_to_epoch({0: []}, plan, qp, gp, coupling) + assert empty.is_empty is True + assert empty.is_complete is False + assert empty.measured_count == (0, 0) + + full = bench.results_to_epoch( + {0: [_Res(qubits=[1], assignment_matrix=[[0.99, 0.01], [0.01, 0.99]]), + _Res(qubits=[2], assignment_matrix=[[0.98, 0.02], [0.02, 0.98]])]}, + plan, qp, gp, coupling) + assert full.is_empty is False + assert full.measured_count == (2, 0) == full.planned_count + assert full.is_complete is True + assert '2/2 qubits' in full.coverage_text() + + partial = bench.results_to_epoch( + {0: [_Res(qubits=[1], assignment_matrix=[[0.99, 0.01], [0.01, 0.99]])]}, + plan, qp, gp, coupling) + assert partial.is_empty is False and partial.is_complete is False + assert partial.measured_count == (1, 0) + + +# ── a failed job is an error, not an empty parse ─────────────────── + +def test_check_chunk_status_raises_on_an_errored_job(): + class _Errored: + job_ids = ['abc123'] + + def status(self): + return SimpleNamespace(name='ERROR') + + def errors(self): + return ('The number of circuit shots 43433984 exceeds the ' + 'system limit 10000000') + + with pytest.raises(bench.BenchmarkRunError) as excinfo: + bench._check_chunk_status(_Errored(), 0) + assert 'exceeds the system limit' in str(excinfo.value) + assert excinfo.value.job_ids == ['abc123'] + + +def test_check_chunk_status_passes_a_healthy_job(): + class _Done: + job_ids = ['ok1'] + + def status(self): + return SimpleNamespace(name='DONE') + + def errors(self): + return None + + assert bench._check_chunk_status(_Done(), 0) == ['ok1'] + + +# ── the analysis-result shape adapter ────────────────────────────── + +def test_result_adapter_handles_the_list_shape(): + items = [_Res(name='T1', value=1.0, qubits=[3])] + + class _Data: + def analysis_results(self, *a, **k): + return items + + def child_data(self): + return [] + + out = list(bench._iter_analysis_results(_Data())) + assert len(out) == 1 and out[0].name == 'T1' + + +def test_result_adapter_handles_the_dataframe_shape(): + """Newer qiskit-experiments returns a DataFrame from analysis_results().""" + pd = pytest.importorskip('pandas') + frame = pd.DataFrame([{'name': 'T1', 'value': 1.5, + 'device_components': ['Q3'], 'quality': 'good'}]) + + class _Data: + def analysis_results(self, *a, **k): + return frame + + def child_data(self): + return [] + + out = list(bench._iter_analysis_results(_Data())) + assert len(out) == 1 + assert out[0].name == 'T1' + assert bench._components_to_qubits(out[0]) == [3] + + +def test_result_adapter_recurses_into_children(): + child_items = [_Res(name='EPG', value=0.01, qubits=[0, 1])] + + class _Child: + def analysis_results(self, *a, **k): + return child_items + + def child_data(self): + return [] + + class _Parent: + def analysis_results(self, *a, **k): + return [] + + def child_data(self): + return [_Child()] + + out = list(bench._iter_analysis_results(_Parent())) + assert len(out) == 1 and out[0].name == 'EPG' + + +def test_components_to_qubits_parses_both_forms(): + assert bench._components_to_qubits( + SimpleNamespace(device_components=['Q7'])) == [7] + assert bench._components_to_qubits( + SimpleNamespace(device_components=[SimpleNamespace(index=4)])) == [4] + assert bench._components_to_qubits( + SimpleNamespace(device_components=[]), fallback=(9,)) == [9] + + +# ── persistence and diagnosis ────────────────────────────────────── + +def test_job_record_is_written_at_submission(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + coupling = _line_edges(8) + plan = bench.build_plan(2, bench.Targets([0, 1, 2, 3], coupling[:3]), 8, + coupling) + when = 1_700_000_000.0 + + path = bench.save_job_record('ibm_test', when, plan, + jobs={'0': ['job-1']}, + statuses={'0': 'submitted'}) + assert path and os.path.exists(path) + with open(path, encoding='utf-8') as fh: + record = json.load(fh) + for key in ('level', 'shots', 'circuits', 'total_shots', 'targets', + 'specs', 'chunks', 'jobs', 'statuses'): + assert key in record, key + assert record['jobs'] == {'0': ['job-1']} + assert record['circuits'] == bench.plan_circuit_count(plan) + + back = bench.latest_job_record('ibm_test') + assert back and back['jobs'] == {'0': ['job-1']} + + +def test_raw_dump_captures_nesting_status_and_errors(): + class _Node: + def __init__(self, name, results, children=(), status='DONE', + errors=None, jobs=()): + self.experiment_type = name + self._results = results + self._children = list(children) + self._status = status + self._errors = errors + self.job_ids = list(jobs) + + def status(self): + return SimpleNamespace(name=self._status) + + def errors(self): + return self._errors + + def analysis_results(self, *a, **k): + return self._results + + def child_data(self): + return self._children + + leaf = _Node('StandardRB', [_Res(name='EPG_cz', value=0.004, + qubits=[0, 1])]) + root = _Node('BatchExperiment', [], [leaf], status='ERROR', + errors='shot limit exceeded', jobs=['j1']) + + dump = bench.dump_raw_results([root]) + assert dump['experiments'][0]['status'] == 'ERROR' + assert dump['experiments'][0]['job_ids'] == ['j1'] + assert dump['experiments'][0]['children'][0]['results'][0]['name'] == \ + 'EPG_cz' + + text = bench.diagnose_raw(dump) + assert 'ERROR' in text + assert 'EPG_cz' in text + assert 'shot limit exceeded' in text + assert 'depth 1' in text, 'the summary must say WHERE results were found' + + +def test_diagnose_raw_says_so_when_nothing_was_produced(): + class _Empty: + job_ids = [] + experiment_type = 'BatchExperiment' + + def status(self): + return SimpleNamespace(name='ERROR') + + def errors(self): + return 'error 1520' + + def analysis_results(self, *a, **k): + return [] + + def child_data(self): + return [] + + text = bench.diagnose_raw(bench.dump_raw_results([_Empty()])) + assert 'NO analysis results at any depth' in text + assert 'error 1520' in text + + +def test_diagnose_raw_on_a_missing_file(): + assert 'Could not read' in bench.diagnose_raw('/nonexistent/path.json') + + +# ── live-run result shapes, reproduced offline ───────────────────── +# +# 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. + + Reading it as an attribute is what produced + "float() argument must be a string or a real number, not 'method'" + for all 156 qubits. + """ + + def __init__(self, matrices): + self._m = dict(matrices) + + def assignment_matrix(self, qubits=None): + if qubits is None: + raise TypeError('qubits required') + q = list(qubits)[0] + return np.asarray(self._m[int(q)], dtype=float) + + +def _readout_result(qubits, matrices): + """ONE result covering every qubit, as the live dump shows.""" + return SimpleNamespace( + name=bench.RESULT_READOUT_MITIGATOR, + device_components=[f'Q{q}' for q in qubits], + value=_Mitigator(matrices)) + + +def test_readout_assignment_matrix_is_called_not_read(): + """Live symptom 2: readout failed for all 156 qubits.""" + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(1, bench.Targets([0, 1, 2], []), 8, coupling) + + good = [[0.99, 0.01], [0.01, 0.99]] + skewed = [[0.9, 0.1], [0.2, 0.8]] + raw = {0: [_readout_result([0, 1, 2], + {0: good, 1: skewed, 2: good})]} + + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert epoch.n_measured_qubits == 3, epoch.notices + assert epoch.qubit_props['readout_error'][1] == pytest.approx(0.15) + assert epoch.qubit_props['readout_error'][0] == pytest.approx(0.01) + values = epoch.qubit_props['readout_error'][[0, 1, 2]] + assert np.all((values >= 0.0) & (values <= 0.5)) + + +def test_t1_t2_are_attributed_by_device_components(): + """Live symptom 3: 156 T1 results existed, but only 1 qubit was measured. + + The parser read `.qubits`, which these results do not carry, and fell back + to `spec.qubits[0]` — so every one of the 156 results was written onto + qubit 0. + """ + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(3, bench.Targets([], []), 8, coupling) + + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 't1': + # Shape from the live dump: device_components=['Q0'], seconds. + raw[idx] = [SimpleNamespace(name='T1', device_components=[f'Q{q}'], + value=1.0e-4 + q * 1e-5) + for q in range(8)] + elif spec.kind == 't2hahn': + raw[idx] = [SimpleNamespace(name='T2', device_components=[f'Q{q}'], + value=8.0e-5) + for q in range(8)] + else: + raw[idx] = [] + + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert epoch.n_measured_qubits == 8, ( + f'expected every qubit, got {epoch.n_measured_qubits}: {epoch.notices}') + # Seconds -> microseconds, and each result on its OWN qubit. + assert epoch.qubit_props['t1'][0] == pytest.approx(100.0) + assert epoch.qubit_props['t1'][3] == pytest.approx(130.0) + assert epoch.qubit_props['t2'][5] == pytest.approx(80.0) + + +def test_one_qubit_rb_counts_qubits_not_gate_results(): + """Live symptom 4: '1Q RB: median EPG over 624 qubit(s)' — 156 x 4 gates.""" + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(3, bench.Targets([], []), 8, coupling) + + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'rb1q': + raw[idx] = [ + SimpleNamespace(name=f'EPG_{g}', device_components=[f'Q{q}'], + value=7e-4) + for q in range(8) for g in ('rz', 'sx', 'x')] + else: + raw[idx] = [] + + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + note = next((n for n in epoch.notices if '1Q RB' in n), '') + 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. + assert epoch.extra.get('epg_1q'), 'per-qubit 1Q EPGs must be retained' + assert set(epoch.extra['epg_1q']) == set(range(8)) + + +def test_notices_are_summarised_not_a_list_of_indices(): + """Live symptom 5: a notice listing all 156 qubit indices verbatim.""" + qp, gp = _reported(n_q=40, n_e=39) + coupling = _line_edges(40) + plan = bench.build_plan(1, bench.Targets(list(range(40)), []), 40, + coupling) + + epoch = bench.results_to_epoch({0: []}, plan, qp, gp, coupling) + + joined = ' '.join(epoch.notices) + assert '[0, 1, 2, 3, 4, 5' not in joined, ( + f'notice still lists indices: {joined[:120]}') + assert any('40' in n for n in epoch.notices), epoch.notices + assert len(joined) < 400, f'notice too verbose ({len(joined)} chars)' + + +# ── 1Q EPG subtraction wiring ────────────────────────────────────── + +def test_level2_now_includes_one_qubit_rb(): + """The 2Q analysis cannot subtract what was never measured.""" + coupling = _line_edges(8) + plan = bench.build_plan(2, bench.Targets([0, 1, 2, 3], coupling[:3]), 8, + coupling) + kinds = [s.kind for s in plan.specs] + assert 'rb1q' in kinds, kinds + # ...and it comes before the two-qubit layers. + assert kinds.index('rb1q') < kinds.index('rb2q_layer') + assert bench.plan_circuit_count(plan) == 2 + 30 + 2 * 30 + + +class _EpgResult: + """A 1Q EPG analysis result: what the 2Q analysis actually consumes.""" + + def __init__(self, qubit, gate='sx', value=7e-4): + self.name = f'EPG_{gate}' + self.value = value + self.device_components = [f'Q{qubit}'] + + +class _Analysis: + def __init__(self, reject=False): + self.options = {} + self.reject = reject + + def set_options(self, **kw): + if self.reject: + raise TypeError('unexpected keyword epg_1_qubit') + self.options.update(kw) + + +def test_epg_1_qubit_receives_result_objects_not_floats(): + """`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. 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) + epg_results = {0: [_EpgResult(0, 'sx'), _EpgResult(0, 'x')], + 1: [_EpgResult(1, 'sx')]} + + notices = [] + assert bench.apply_epg_1q_options(experiment, (0, 1), epg_results, + notices) is True + passed = analysis.options['epg_1_qubit'] + assert len(passed) == 3 + for item in passed: + assert not isinstance(item, float), 'floats are what broke the run' + assert hasattr(item, 'device_components') + assert hasattr(item, 'value') + assert not notices + + +def test_harvest_keeps_the_result_objects_per_qubit(): + entry = [_EpgResult(0, 'sx'), _EpgResult(0, 'rz'), _EpgResult(3, 'x'), + SimpleNamespace(name='alpha', device_components=['Q0'], + value=0.9)] + harvested = bench.harvest_epg_results(entry).results + assert set(harvested) == {0, 3} + assert len(harvested[0]) == 2 + assert all(hasattr(r, 'device_components') for r in harvested[0]) + assert all(not str(r.name).startswith('alpha') + for rs in harvested.values() for r in rs) + + +def test_a_pair_without_1q_results_skips_subtraction_with_a_notice(): + """Fabricating a stand-in would risk repeating the live crash. + + A wrong shape does not fail when the option is set — it fails inside the + fit callback, after the QPU time is spent. So a missing 1Q result means + no subtraction for that pair, said out loud. + """ + analysis = _Analysis() + notices = [] + ok = bench.apply_epg_1q_options(SimpleNamespace(analysis=analysis), + (0, 1), {0: [_EpgResult(0)]}, notices) + assert ok is False + assert 'epg_1_qubit' not in analysis.options + # The per-pair chatter is gone; the run-level tally reports it instead, + # so a 352-edge run does not emit 352 near-identical notices. + context = {'_epg_tally': {'applied': 0, 'skipped': [(0, 1)]}} + text = bench.epg_tally_notice(context) + assert 'applied to 0 pairs' in text, text + assert 'skipped 1' in text and 'qubits 0, 1' in text + + +def test_a_rejected_option_is_a_notice_not_a_crash(): + notices = [] + ok = bench.apply_epg_1q_options( + SimpleNamespace(analysis=_Analysis(reject=True)), (0, 1), + {0: [_EpgResult(0)], 1: [_EpgResult(1)]}, notices) + assert ok is False + assert any('rejected epg_1_qubit' in n for n in notices), notices + + +# ── 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.""" + boom = ("AttributeError: 'float' object has no attribute " + "'device_components'") + + class _Child: + def status(self): + return SimpleNamespace(name='DONE') + + def analysis_errors(self): + return boom + + def errors(self): + return None + + def child_data(self): + return [] + + class _Root(_Child): + def analysis_errors(self): + return None # composites record it on the child that raised + + def child_data(self): + return [_Child(), _Child(), _Child()] + + errors = bench.collect_analysis_errors(_Root()) + assert len(errors) == 3, errors + summary = bench.summarise_analysis_errors(errors) + assert summary.startswith('analysis failed:') + assert '3x' in summary + assert 'device_components' in summary + + +def test_summarise_analysis_errors_is_empty_when_clean(): + assert bench.summarise_analysis_errors([]) is None + + +# ── consistency and relative mode ────────────────────────────────── + +def _epoch_with(measured_gate, reported_gate, mask): + qp = {'readout_error': np.full(4, 0.01)} + gp = {'cz_error': np.asarray(measured_gate, dtype=float)} + return bench.MeasuredEpoch(qp, gp, np.zeros(4, dtype=bool), mask, 2, + 1_700_000_000.0) + + +def test_consistency_stats_reports_both_ratio_statistics(): + """They differ on skewed data — quoting one as 'the' ratio misleads.""" + reported = np.array([1e-3, 1e-3, 1e-3, 1e-3]) + measured = np.array([2e-3, 2e-3, 2e-3, 20e-3]) + mask = np.ones(4, dtype=bool) + epoch = _epoch_with(measured, reported, mask) + + stats = bench.consistency_stats(epoch, {}, {'cz_error': reported}) + cz = stats['cz_error'] + assert cz['n'] == 4 + assert cz['median_ratio'] == pytest.approx(2.0) + assert cz['ratio_of_medians'] == pytest.approx(2.0) + assert cz['n_worse_2x'] == 1 # only the 20x outlier is >2x + assert cz['top_degradations'][0]['index'] == 3 + + +def test_an_untouched_property_is_not_reported(): + reported = np.array([1e-3, 2e-3, 3e-3, 4e-3]) + epoch = _epoch_with(reported.copy(), reported, np.ones(4, dtype=bool)) + assert 'cz_error' not in bench.consistency_stats( + epoch, {}, {'cz_error': reported}) + + +def test_relative_mode_matches_medians_and_preserves_ratios(): + """The uniform offset goes; the outlier stays an outlier.""" + reported = np.array([1e-3, 1e-3, 1e-3, 1e-3]) + measured = np.array([3e-3, 3e-3, 3e-3, 30e-3]) + mask = np.ones(4, dtype=bool) + epoch = _epoch_with(measured.copy(), reported, mask) + + stats = bench.consistency_stats(epoch, {}, {'cz_error': reported}) + assert list(bench.consistency_offenders(stats)) == ['cz_error'] + + before = epoch.gate_props['cz_error'].copy() + n = bench.apply_relative_mode(epoch, {}, {'cz_error': reported}, stats) + after = epoch.gate_props['cz_error'] + + assert n == 1 and epoch.relative is True + assert np.median(after[mask]) == pytest.approx(np.median(reported[mask])) + # Every pairwise ratio is untouched — that is what makes outliers survive. + np.testing.assert_allclose(after / after[0], before / before[0]) + assert after[3] / after[0] == pytest.approx(10.0) + + +def test_relative_mode_is_a_no_op_inside_the_band(): + reported = np.array([1e-3, 1e-3, 1e-3, 1e-3]) + measured = np.array([1.2e-3, 1.1e-3, 1.3e-3, 1.2e-3]) + epoch = _epoch_with(measured.copy(), reported, np.ones(4, dtype=bool)) + stats = bench.consistency_stats(epoch, {}, {'cz_error': reported}) + assert bench.consistency_offenders(stats) == {} + assert bench.apply_relative_mode(epoch, {}, {'cz_error': reported}, + stats) == 0 + assert epoch.relative is False + + +def test_relative_label_says_so(): + state = _state(4) + epoch = _epoch_with(np.full(3, 3e-3), np.full(3, 1e-3), + np.ones(3, dtype=bool)) + epoch.qubit_props = {'readout_error': np.full(4, 0.01)} + epoch.relative = True + assert bench.apply_measured_epoch(state, epoch) is True + assert 'relative' in state.calibration_data_label + + +def test_job_ids_are_recovered_per_phase_from_a_raw_dump(): + """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']}]}, + {'job_ids': [], 'children': [{'job_ids': ['phase2-job']}]}, + ]} + assert bench.job_ids_from_raw(dump) == [['phase1-job'], ['phase2-job']] + + +def test_phased_runner_records_job_ids(): + """Without this the run cannot be reanalysed, which is how today's was + nearly lost.""" + recorded = [] + + class _Data: + job_ids = ['j-abc'] + + def status(self): + return SimpleNamespace(name='DONE') + + def errors(self): + return None + + def analysis_errors(self): + return None + + def block_for_results(self): + pass + + def child_data(self, idx=None): + return SimpleNamespace(analysis_results=lambda *a, **k: []) + + class _Batch: + def __init__(self, experiments, **kw): + pass + + def run(self, **kw): + return _Data() + + class _Exp: + def __init__(self, *a, **k): + self.analysis = SimpleNamespace(set_options=lambda **k: None) + + class _Session: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + api = SimpleNamespace(Session=_Session, SamplerV2=lambda mode=None: None, + BatchExperiment=_Batch, ParallelExperiment=_Exp, + LocalReadoutError=_Exp, StandardRB=_Exp, T1=_Exp, + T2Hahn=_Exp) + bench._reset_runtime_cache() + try: + import iqmapper.benchmark as mod + original = mod._runtime_api + mod._runtime_api = lambda: api + try: + coupling = _line_edges(8) + plan = bench.build_plan(2, bench.Targets([0, 1, 2, 3], + coupling[:3]), 8, coupling) + runner = bench.make_runtime_runner( + object(), + on_jobs=lambda i, ids, st: recorded.append((i, list(ids), st))) + runner(plan) + finally: + mod._runtime_api = original + finally: + bench._reset_runtime_cache() + + assert recorded, 'the phased runner recorded no job ids' + assert {r[0] for r in recorded} == {0, 1}, 'both phases must be recorded' + assert all('j-abc' in r[1] for r in recorded) + + +# ── 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'. + + `BaseExperiment.run()` creates the composite container (children + + component metadata) BEFORE submitting. Reanalysis built a bare + ExperimentData instead, so `CompositeAnalysis._component_experiment_data` + had nothing to walk. + """ + calls = [] + + class _Container: + metadata = {'component_child_index': [0, 1]} + + def child_data(self): + return [object(), object()] + + class _Composite: + _experiments = [object(), object()] + + def _initialize_experiment_data(self): + calls.append('init') + return _Container() + + notices = [] + experiment = _Composite() + out = bench._initialize_container(experiment, backend='bk', + notices=notices) + assert calls == ['init'], 'run()-style initialiser was not used' + assert isinstance(out, _Container) + assert experiment.backend == 'bk' + assert not notices + + +def test_a_container_without_composite_metadata_is_flagged(): + """If the container is wrong again, say which piece is missing.""" + class _Bare: + metadata = {} + + def child_data(self): + return [] + + class _Composite: + _experiments = [object(), object()] + + def _initialize_experiment_data(self): + return _Bare() + + notices = [] + bench._initialize_container(_Composite(), 'bk', 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(): + """qiskit-experiments 0.10 creates child containers during add_jobs / + analysis, not at initialisation, so an empty child list at init is + normal — flagging it produced a false alarm on runs that then worked.""" + class _Partial: + metadata = {'component_child_index': [0]} + + def child_data(self): + return [] + + class _Composite: + _experiments = [object()] + + def _initialize_experiment_data(self): + return _Partial() + + notices = [] + bench._initialize_container(_Composite(), 'bk', notices) + assert notices == [], notices + + +def test_a_non_composite_experiment_needs_no_composite_metadata(): + class _Plain: + metadata = {} + + def child_data(self): + return [] + + class _Single: + _experiments = None + + def _initialize_experiment_data(self): + return _Plain() + + notices = [] + bench._initialize_container(_Single(), 'bk', notices) + assert notices == [] + + +def test_the_public_constructor_is_the_fallback(monkeypatch): + """An initialiser that raises must not abort the reanalysis.""" + class _Composite: + _experiments = [object()] + + def _initialize_experiment_data(self): + raise RuntimeError('private API moved') + + made = {} + + class _FakeED: + def __init__(self, experiment=None, backend=None): + made['experiment'] = experiment + made['backend'] = backend + self.metadata = {'component_child_index': [0]} + + def child_data(self): + return [object()] + + import sys + module = types.ModuleType('qiskit_experiments.framework') + module.ExperimentData = _FakeED + pkg = types.ModuleType('qiskit_experiments') + monkeypatch.setitem(sys.modules, 'qiskit_experiments', pkg) + monkeypatch.setitem(sys.modules, 'qiskit_experiments.framework', module) + + notices = [] + out = bench._initialize_container(_Composite(), 'bk', notices) + assert isinstance(out, _FakeED) + assert made['backend'] == 'bk' + assert any('private API moved' in n for n in notices), notices + + +# ── 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 + the header read "Live calibration" while the map showed benchmark data.""" + from iqmapper.ui.time_panel import describe_current_view + + state = _state(8) + state.time_mode = 'live' + assert describe_current_view(state) == 'Live calibration — ibm_test' + + epoch = bench.MeasuredEpoch( + {'readout_error': np.full(8, 0.01)}, + {'cz_error': np.full(7, 0.01)}, + np.ones(8, dtype=bool), np.ones(7, dtype=bool), + 3, 1_700_000_000.0) + bench.apply_measured_epoch(state, epoch) + + text = describe_current_view(state) + assert text.startswith('Measured '), text + assert '(L3, absolute)' in text, text + assert 'ibm_test' in text + assert 'Live calibration' not in text + + epoch.relative = True + assert '(L3, relative)' in describe_current_view(state) + + +def test_describe_current_view_leaves_other_modes_alone(): + """Only the live view is displaced; history/snapshot still describe + themselves.""" + from iqmapper.ui.time_panel import describe_current_view + + state = _state(8) + epoch = bench.MeasuredEpoch( + {'readout_error': np.full(8, 0.01)}, + {'cz_error': np.full(7, 0.01)}, + np.ones(8, dtype=bool), np.ones(7, dtype=bool), 1, 1.0) + bench.apply_measured_epoch(state, epoch) + + state.time_mode = 'point' + state.point_timestamp = '2026-09-20T12:00:00Z' + assert describe_current_view(state).startswith('Snapshot:') + + +def test_epg_tally_notice_reports_a_clean_run(): + assert bench.epg_tally_notice( + {'_epg_tally': {'applied': 176, 'skipped': []}}) == \ + '1Q EPG subtraction: applied to 176 pairs' + assert bench.epg_tally_notice({}) is None + + +def test_epoch_round_trips_relative_consistency_and_extra(tmp_path, + monkeypatch): + """A saved epoch must read back as what it IS. + + Without this, a rescaled epoch reloaded with `relative=None` and no + `extra.epg_1q`, so nothing on disk recorded that the values had been + adjusted or that the 1Q EPGs had ever been measured. + """ + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + when = 1_700_000_100.0 + epoch = bench.MeasuredEpoch( + {'readout_error': np.full(4, 0.02)}, {'cz_error': np.full(3, 0.004)}, + np.ones(4, dtype=bool), np.ones(3, dtype=bool), 3, when, + ['a notice'], planned_count=(4, 3), + extra={'epg_1q': {0: 7e-4, 1: 8e-4}}, + consistency={'cz_error': {'n': 3, 'ratio_of_medians': 2.8, + 'top_degradations': [{'index': 1}]}}, + relative=True) + + assert bench.save_measured_epoch('ibm_test', epoch) + back = bench.load_measured_epoch('ibm_test', when) + + assert back is not None + assert back.relative is True + assert back.planned_count == (4, 3) + assert back.extra.get('epg_1q') == {0: pytest.approx(7e-4), + 1: pytest.approx(8e-4)} + assert back.consistency['cz_error']['ratio_of_medians'] == \ + pytest.approx(2.8) + assert back.notices == ['a notice'] + + +def test_latest_run_skips_a_replay_dump(tmp_path, monkeypatch): + """A reanalysis dumped as a plain _raw.json must not become the target. + + Its job ids belong to an older submission; replaying it would keep + resurrecting that older run — which is how the panel stayed pinned to + the 12:38 single-phase run. + """ + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + dirn = bench._measured_dir('ibm_test') + + def _dump(stamp, ids): + with open(os.path.join(dirn, f'measured_{stamp}_raw.json'), 'w', + encoding='utf-8') as fh: + json.dump({'experiments': [{'job_ids': ids, 'children': []}]}, fh) + + _dump('20260920T130000', ['real-a', 'real-b']) # the genuine run + _dump('20260920T140000', ['real-a']) # a replay of it + + record = bench.latest_job_record('ibm_test') + assert record['_stamp'] == '20260920T130000', record['_stamp'] + assert sorted(j for ids in record['jobs'].values() for j in ids) == \ + ['real-a', 'real-b'] + + +def test_reanalysis_dumps_do_not_shadow_submissions(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + dirn = bench._measured_dir('ibm_test') + with open(os.path.join(dirn, 'measured_20260920T130000_raw.json'), 'w', + encoding='utf-8') as fh: + json.dump({'experiments': [{'job_ids': ['sub'], 'children': []}]}, fh) + with open(os.path.join(dirn, 'measured_20260920T150000_rean.json'), 'w', + encoding='utf-8') as fh: + json.dump({'experiments': [{'job_ids': ['sub'], 'children': []}]}, fh) + + record = bench.latest_job_record('ibm_test') + assert record['_stamp'] == '20260920T130000' + + +# ── 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 + `rb_analysis._exclude_1q_error` evaluate (1 - 2*epg)**n on a negative + base and raise "The uncertainties module does not handle complex + results", killing every 2Q callback of the calibration check. + """ + entry = [_EpgResult(0, 'sx', 7e-4), _EpgResult(0, 'x', 6e-4), + _EpgResult(17, 'sx', 0.71), _EpgResult(17, 'x', 5e-4)] + harvest = bench.harvest_epg_results(entry) + + assert set(harvest.results) == {0}, 'the bad qubit was still forwarded' + assert 17 in harvest.rejected + assert harvest.rejected[17] == pytest.approx(0.71) + + # A pair touching q17 is skipped, and the tally names it with its value. + analysis = _Analysis() + notices = [] + assert bench.apply_epg_1q_options(SimpleNamespace(analysis=analysis), + (0, 17), harvest.results, + notices) is False + assert 'epg_1_qubit' not in analysis.options + + context = {'_epg_tally': {'applied': 174, 'skipped': [(0, 17), (17, 18)]}, + '_epg_rejected': harvest.rejected} + text = bench.epg_tally_notice(context) + assert 'applied to 174 pairs' in text, text + assert 'skipped 2' in text, text + assert 'q17: 1Q EPG 0.71 implausible' in text, text + + +def test_a_nan_1q_epg_is_rejected_as_a_failed_fit(): + harvest = bench.harvest_epg_results( + [_EpgResult(3, 'sx', float('nan'))]) + assert harvest.results == {} + assert 3 in harvest.rejected + text = bench.epg_tally_notice( + {'_epg_tally': {'applied': 0, 'skipped': [(3, 4)]}, + '_epg_rejected': harvest.rejected}) + assert 'q3: 1Q EPG fit failed' in text, text + + +def test_plausible_epgs_pass_through_untouched(): + harvest = bench.harvest_epg_results( + [_EpgResult(1, 'sx', 6.9e-4), _EpgResult(1, 'x', 7.1e-4)]) + assert set(harvest.results) == {1} + assert len(harvest.results[1]) == 2 + assert harvest.rejected == {} + + +def test_extra_epg_1q_only_records_plausible_values(): + """An implausible EPG must not be persisted as if it were measured.""" + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(3, bench.Targets([], []), 8, coupling) + raw = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'rb1q': + raw[idx] = [_EpgResult(0, 'sx', 7e-4), _EpgResult(5, 'sx', 0.9)] + else: + raw[idx] = [] + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert set(epoch.extra.get('epg_1q') or {}) == {0} + assert any('implausible EPG' in n and 'q5' in n for n in epoch.notices), \ + epoch.notices + + +# ── bounds on the other measured kinds ───────────────────────────── + +def test_an_implausible_readout_error_falls_back_with_a_notice(): + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(1, bench.Targets([0, 1], []), 8, coupling) + # q1's matrix implies an error of 0.9 — worse than chance. + raw = {0: [_readout_result([0, 1], {0: [[0.99, 0.01], [0.01, 0.99]], + 1: [[0.1, 0.9], [0.9, 0.1]]})]} + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert epoch.qubit_props['readout_error'][0] == pytest.approx(0.01) + assert epoch.qubit_props['readout_error'][1] == pytest.approx(0.05), \ + 'the implausible value was written instead of the reported one' + assert epoch.measured_qubit_mask[0] and not epoch.measured_qubit_mask[1] + assert any('implausible readout' in n for n in epoch.notices), \ + epoch.notices + + +@pytest.mark.parametrize('seconds,ok', [ + (1.5e-4, True), # 150 us — normal + (-1.0, False), # negative + (0.02, False), # 20 ms — a runaway fit + (float('nan'), False), +]) +def test_coherence_bounds(seconds, ok): + qp, gp = _reported() + coupling = _line_edges(8) + plan = bench.build_plan(3, bench.Targets([], []), 8, coupling) + raw = {} + for idx, spec in enumerate(plan.specs): + raw[idx] = ([SimpleNamespace(name='T1', device_components=['Q2'], + value=seconds)] + if spec.kind == 't1' else []) + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + if ok: + assert epoch.qubit_props['t1'][2] == pytest.approx(seconds * 1e6) + assert epoch.measured_qubit_mask[2] + else: + assert epoch.qubit_props['t1'][2] == pytest.approx(100.0), 'reported' + assert not epoch.measured_qubit_mask[2] + assert any('implausible t1' in n.lower() or 'T1' in n + for n in epoch.notices), epoch.notices diff --git a/tests/test_benchmark_integration.py b/tests/test_benchmark_integration.py new file mode 100644 index 0000000..1d09a40 --- /dev/null +++ b/tests/test_benchmark_integration.py @@ -0,0 +1,440 @@ +"""Integration tests: the benchmark pipeline against REAL qiskit-experiments. + +Why these exist +--------------- +Every offline test fed the parser fake results shaped the way WE assumed +qiskit-experiments shapes them. It never ran a real experiment, never saw a +real `AnalysisResult`, and never submitted anything. So when the live Level 3 +run was rejected by IBM and came back with no analysis results at all, nothing +in the suite noticed — the parser found nothing, reported "no results +returned" for every experiment, and the panel called it a success. + +These tests close that gap without a QPU: real experiment objects, real +analysis, real result shapes, executed on a local fake backend or Aer. No +network, no credentials, no queue. + +They are marked `integration` and skip cleanly when the optional stack is +absent, so the default suite stays runnable on a bare install: + + python -m pytest -m integration -q +""" + +import numpy as np +import pytest + +from iqmapper import benchmark as bench + +pytestmark = pytest.mark.integration + +qiskit_experiments = pytest.importorskip( + 'qiskit_experiments', reason='needs the [benchmark] extra') +pytest.importorskip('qiskit_aer', reason='needs qiskit-aer for local execution') + + +# ── a local backend + sampler ─────────────────────────────────────── + +@pytest.fixture(scope='module') +def fake_backend(): + """A small local backend. Real target, real coupling, no network.""" + from qiskit_ibm_runtime.fake_provider import FakeManilaV2 + return FakeManilaV2() + + +@pytest.fixture(scope='module') +def local_api(fake_backend): + """The runtime API namespace with execution pointed at Aer. + + Only the EXECUTION is substituted: the experiment classes, the composite + machinery and the analysis are the real ones, which is the entire point. + """ + from types import SimpleNamespace + + from qiskit_aer import AerSimulator + from qiskit_aer.primitives import SamplerV2 as AerSampler + from qiskit_experiments.framework import (BatchExperiment, + ParallelExperiment) + from qiskit_experiments.library import (LocalReadoutError, StandardRB, T1, + T2Hahn) + + simulator = AerSimulator.from_backend(fake_backend) + + class _Session: + """Context manager with the production shape, backed by Aer.""" + + def __init__(self, backend=None): + self.backend = backend + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + return SimpleNamespace( + Session=_Session, + SamplerV2=lambda mode=None: AerSampler(), + BatchExperiment=BatchExperiment, ParallelExperiment=ParallelExperiment, + LocalReadoutError=LocalReadoutError, StandardRB=StandardRB, + T1=T1, T2Hahn=T2Hahn, + _simulator=simulator) + + +def _reported(n_q, n_e): + return ({'readout_error': np.full(n_q, 0.05), + 't1': np.full(n_q, 100.0), + 't2': np.full(n_q, 80.0)}, + {'cz_error': np.full(n_e, 0.01)}) + + +def _coupling_of(backend): + edges = [] + seen = set() + for u, v in backend.coupling_map.get_edges(): + key = frozenset((u, v)) + if key not in seen: + seen.add(key) + edges.append((int(u), int(v))) + return edges + + +def _run_through_production_runner(monkeypatch, local_api, backend, plan, + counter=None): + """Drive the REAL runner with only execution substituted.""" + api = local_api + if counter is not None: + inner = api.SamplerV2 + + def _counting(mode=None): + sampler = inner(mode) + original = sampler.run + + def _run(circuits, **kwargs): + counter['circuits'] += len(list(circuits)) + return original(circuits, **kwargs) + + sampler.run = _run + return sampler + + api = type(api)(**{**vars(api), 'SamplerV2': _counting}) + + monkeypatch.setattr(bench, '_runtime_api', lambda: api) + bench._reset_runtime_cache() + try: + runner = bench.make_runtime_runner(backend) + return bench.run_plan(plan, runner), getattr(runner, 'last_expdata', []) + finally: + bench._reset_runtime_cache() + + +# ── 1. Level 1 really produces readout measurements ───────────────── + +def test_l1_plan_on_fake_backend_yields_measurements(monkeypatch, fake_backend, + local_api): + """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) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, targets, + fake_backend.num_qubits, coupling) + plan = plan._replace(shots=100) + + raw, _expdata = _run_through_production_runner( + monkeypatch, local_api, fake_backend, plan) + + qp, gp = _reported(fake_backend.num_qubits, len(coupling)) + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert not epoch.is_empty, ( + f'no measurements came back; notices: {epoch.notices}') + assert epoch.n_measured_qubits >= 3, epoch.notices + values = epoch.qubit_props['readout_error'][list(targets.qubits)] + assert np.all(np.isfinite(values)) + assert np.all((values >= 0.0) & (values <= 0.5)), values + + +# ── 2. Level 2: a 2Q RB pair produces a finite EPG ────────────────── + +def test_l2_single_pair_on_fake_backend(monkeypatch, fake_backend, local_api): + coupling = _coupling_of(fake_backend) + pair = coupling[0] + targets = bench.Targets(list(pair), [pair]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, + fake_backend.num_qubits, coupling) + # Keep it to seconds: short sequences, few samples, few shots. + specs = [] + for spec in plan.specs: + if spec.kind == 'rb2q_layer': + params = dict(spec.params) + params['lengths'] = [2, 4] + params['num_samples'] = 2 + spec = spec._replace(params=params) + specs.append(spec) + plan = plan._replace(specs=specs, shots=100) + + raw, _expdata = _run_through_production_runner( + monkeypatch, local_api, fake_backend, plan) + + qp, gp = _reported(fake_backend.num_qubits, len(coupling)) + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert epoch.n_measured_edges >= 1, epoch.notices + idx = coupling.index(pair) + epg = epoch.gate_props['cz_error'][idx] + assert np.isfinite(epg) and 0.0 <= epg < 1.0, epg + + +# ── 3. what we submit is what we planned ──────────────────────────── + +def test_submitted_circuit_count_matches_plan(monkeypatch, fake_backend, + local_api): + """The accounting bug that caused error 1520, asserted directly.""" + targets = bench.Targets([0, 1, 2], []) + coupling = _coupling_of(fake_backend) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, targets, + fake_backend.num_qubits, coupling) + plan = plan._replace(shots=100) + + counter = {'circuits': 0} + _run_through_production_runner(monkeypatch, local_api, fake_backend, plan, + counter) + + expected = bench.plan_circuit_count(plan) + assert counter['circuits'] == expected, ( + f'submitted {counter["circuits"]} circuits, planned {expected}') + + +# ── 4. the full suite, small ──────────────────────────────────────── + +def test_l3_small_fake_full_suite(monkeypatch, fake_backend, local_api): + """Every experiment kind produces results, and diagnose_raw finds them.""" + coupling = _coupling_of(fake_backend) + n_q = fake_backend.num_qubits + plan = bench.build_plan(bench.LEVEL_FULL, bench.Targets([], []), n_q, + coupling) + specs = [] + for spec in plan.specs: + params = dict(spec.params) + if spec.kind in ('t1', 't2hahn'): + params['delays'] = [1e-6, 20e-6, 40e-6] + if spec.kind in ('rb1q', 'rb2q_layer'): + params['lengths'] = [2, 4] + params['num_samples'] = 2 + specs.append(spec._replace(params=params)) + plan = plan._replace(specs=specs, shots=100) + + raw, expdata = _run_through_production_runner( + monkeypatch, local_api, fake_backend, plan) + + qp, gp = _reported(n_q, len(coupling)) + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + assert not epoch.is_empty, epoch.notices + assert epoch.n_measured_qubits > 0 and epoch.n_measured_edges > 0 + + text = bench.diagnose_raw(bench.dump_raw_results(expdata)) + assert 'NO analysis results' not in text, text + assert 'depth' in text + + +# ── 5. delays must be legal on the device ─────────────────────────── + +def test_t1_delays_are_within_the_backend_limits(fake_backend): + """A delay longer than the device allows is rejected at submission.""" + target = getattr(fake_backend, 'target', None) + max_delay = None + try: + granularity = target.granularity + dt = target.dt + max_delay = getattr(target, 'max_delay', None) + if max_delay is not None and dt: + max_delay = max_delay * dt + assert granularity is not None + except Exception: + pytest.skip('backend exposes no delay limits') + if max_delay is None: + pytest.skip('backend declares no max_delay') + assert max(bench.T1T2_DELAYS) <= max_delay, ( + f'longest tutorial delay {max(bench.T1T2_DELAYS)}s exceeds the ' + f'device limit {max_delay}s') + + +# ── reanalysis reproduces the direct run ──────────────────────────── + +def _jobs_of(expdata_list): + """The job OBJECTS a run produced, for reanalysis to consume.""" + jobs = [] + for expdata in expdata_list or []: + getter = getattr(expdata, 'jobs', None) + if callable(getter): + try: + jobs.extend(list(getter())) + continue + except Exception: + pass + return jobs + + +def test_reanalysis_from_jobs_reproduces_the_direct_run(monkeypatch, + fake_backend, + local_api): + """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 + re-fitted. + """ + targets = bench.Targets([0, 1, 2], []) + coupling = _coupling_of(fake_backend) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, targets, + fake_backend.num_qubits, coupling)._replace( + shots=100) + + raw, expdata = _run_through_production_runner(monkeypatch, local_api, + fake_backend, plan) + qp, gp = _reported(fake_backend.num_qubits, len(coupling)) + direct = bench.results_to_epoch(raw, plan, qp, gp, coupling) + assert not direct.is_empty, direct.notices + + jobs = _jobs_of(expdata) + if not jobs: + pytest.skip('the local sampler exposes no job objects to reanalyze') + + monkeypatch.setattr(bench, '_runtime_api', lambda: local_api) + bench._reset_runtime_cache() + try: + # A pre-built job list is passed straight through (service=None), so + # this exercises container construction + add_jobs + analysis.run. + raw2, expdata2 = bench.reanalyze_from_jobs(plan, [jobs], fake_backend, + service=None) + finally: + bench._reset_runtime_cache() + + assert not any('Unable to extract component' in str(n) + for n in (raw2.get('_notices') or [])), raw2.get('_notices') + qp2, gp2 = _reported(fake_backend.num_qubits, len(coupling)) + again = bench.results_to_epoch(raw2, plan, qp2, gp2, coupling) + + assert not again.is_empty, again.notices + assert again.measured_count == direct.measured_count + np.testing.assert_allclose( + again.qubit_props['readout_error'][list(targets.qubits)], + direct.qubit_props['readout_error'][list(targets.qubits)], + rtol=1e-9) + + +def test_reanalysis_container_has_the_composite_structure(fake_backend, + local_api): + """The container itself, before any jobs: children + metadata present.""" + coupling = _coupling_of(fake_backend) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, + bench.Targets([0, 1, 2], []), + fake_backend.num_qubits, coupling) + experiments = [bench._build_experiment(sp, local_api) for sp in plan.specs] + batch = local_api.BatchExperiment(experiments, flatten_results=False) + + notices = [] + container = bench._initialize_container(batch, fake_backend, notices) + + assert notices == [], notices + # Children are allocated later (during add_jobs/analysis) in 0.10; the + # metadata naming the components is what must exist up front. + metadata = dict(container.metadata or {}) + assert any(k in metadata for k in bench._COMPOSITE_METADATA_KEYS), metadata + + +def test_two_phase_reanalysis_keeps_the_1q_subtraction(monkeypatch, + fake_backend, + local_api): + """Reanalysing both phases as one batch would lose the subtraction. + + The 1Q EPG results come from phase 1 and must be harvested before + phase 2's analyses are constructed, exactly as the live runner does. + """ + coupling = _coupling_of(fake_backend) + pair = coupling[0] + targets = bench.Targets(list(pair), [pair]) + plan = bench.build_plan(bench.LEVEL_TARGETED, targets, + fake_backend.num_qubits, coupling) + specs = [] + for spec in plan.specs: + params = dict(spec.params) + if spec.kind in ('rb1q', 'rb2q_layer'): + params['lengths'] = [2, 4] + params['num_samples'] = 2 + specs.append(spec._replace(params=params)) + plan = plan._replace(specs=specs, shots=100) + + raw, expdata = _run_through_production_runner(monkeypatch, local_api, + fake_backend, plan) + assert len(expdata) == 2, 'expected a two-phase run' + per_phase = [_jobs_of([d]) for d in expdata] + if not all(per_phase): + pytest.skip('the local sampler exposes no job objects to reanalyze') + + monkeypatch.setattr(bench, '_runtime_api', lambda: local_api) + bench._reset_runtime_cache() + try: + raw2, _ = bench.reanalyze_from_jobs(plan, per_phase, fake_backend, + service=None) + finally: + bench._reset_runtime_cache() + + qp, gp = _reported(fake_backend.num_qubits, len(coupling)) + again = bench.results_to_epoch(raw2, plan, qp, gp, coupling) + assert again.n_measured_edges >= 1, again.notices + assert not any('device_components' in n for n in again.notices), ( + again.notices) + + +def test_calibration_check_runs_both_ways(monkeypatch, fake_backend, + local_api): + """Parallel vs sequential over the same edges, and a verdict. + + Restored after being lost in a file rewrite. It is the experiment that + distinguishes estimator bias (both arms offset) from crosstalk (only the + parallel arm offset), so losing it silently was a real gap. + """ + coupling = _coupling_of(fake_backend) + edges = coupling[:2] + targets = bench.Targets(sorted({q for e in edges for q in e}), edges) + par_plan, seq_plan = bench.build_calibration_check_plans( + targets, fake_backend.num_qubits, coupling, n_edges=2) + + # The sequential arm must run one pair per experiment. + seq_layers = [s for s in seq_plan.specs if s.kind == 'rb2q_layer'] + assert all(len(s.params['pairs']) == 1 for s in seq_layers), seq_layers + par_layers = [s for s in par_plan.specs if s.kind == 'rb2q_layer'] + assert len(par_layers) <= len(seq_layers) + + def _shrink(plan): + specs = [] + for spec in plan.specs: + params = dict(spec.params) + if spec.kind in ('rb1q', 'rb2q_layer'): + params['lengths'] = [2, 4] + params['num_samples'] = 2 + specs.append(spec._replace(params=params)) + return plan._replace(specs=specs, shots=100) + + qp, gp = _reported(fake_backend.num_qubits, len(coupling)) + epochs = [] + for plan in (_shrink(par_plan), _shrink(seq_plan)): + raw, _ = _run_through_production_runner(monkeypatch, local_api, + fake_backend, plan) + epochs.append(bench.results_to_epoch(raw, plan, dict(qp), dict(gp), + coupling)) + + table = bench.calibration_check_table(coupling, gp['cz_error'], + epochs[0], epochs[1]) + assert table['rows'], 'the check produced no rows' + assert table['ratio_parallel'] is not None + assert table['ratio_sequential'] is not None + assert table['verdict'] + for row in table['rows']: + assert np.isfinite(row['parallel']) and np.isfinite(row['sequential']) diff --git a/tests/test_benchmark_runtime_contract.py b/tests/test_benchmark_runtime_contract.py new file mode 100644 index 0000000..31a2c50 --- /dev/null +++ b/tests/test_benchmark_runtime_contract.py @@ -0,0 +1,318 @@ +"""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): + """Every spec gets an entry, keyed by its index in the PLAN. + + The runner submits in two phases (non-2Q first, so its 1Q EPGs can be fed + to the 2Q analyses), so a spec's position within its batch is not its + position in the plan — the mapping must be by plan index. + """ + plan = _plan() + runner = bench.make_runtime_runner(object()) + out = runner(plan) + + indices = {k for k in out if isinstance(k, int)} + assert indices == set(range(len(plan.specs))) + assert all(out[i] is not None for i in indices) + + +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): + """Across both phases, every spec is built exactly once.""" + plan = _plan(bench.LEVEL_FULL) + runner = bench.make_runtime_runner(object()) + runner(plan) + + built = sum(len(b.experiments) for b in _FakeBatch.instances) + assert built == len(plan.specs) + assert all(b.kwargs == {'flatten_results': False} + for b in _FakeBatch.instances) + + +def test_two_qubit_rb_is_submitted_after_one_qubit_rb(api): + """Ordering is the whole point of the phase split. + + The 2Q analyses can only subtract single-qubit error if the 1Q EPGs exist + when they are CONSTRUCTED, so 1Q RB must be a separate, earlier submission. + """ + plan = _plan(bench.LEVEL_FULL) + runner = bench.make_runtime_runner(object()) + runner(plan) + + assert len(_FakeBatch.instances) == 2, 'expected a two-phase submission' + first, second = _FakeBatch.instances + assert len(first.experiments) + len(second.experiments) == len(plan.specs) + # The 2Q layers are all in the SECOND submission. + n_2q = len([s for s in plan.specs if s.kind == 'rb2q_layer']) + assert len(second.experiments) == n_2q + + +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..fa5bcb0 --- /dev/null +++ b/tests/test_benchmark_ui.py @@ -0,0 +1,1750 @@ +"""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. +""" +import json +from types import SimpleNamespace + +import numpy as np +import pytest + +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(), + chk_bench_absolute=_Dropdown(value=False), + lbl_bench_consistency=_RecLabel(), + lbl_bench_details=_RecLabel(), + acc_bench_details=_Stub(selected_index=None), + btn_bench_show_on_map=_Stub(description='show on map'), + chk_err_threshold=_Dropdown(value=False), + txt_g_thr_max=_Dropdown(value=''), + dd_gate_prop=_Dropdown(value='cz_error', options=[('CZ', 'cz_error')]), + lbl_bench_reuse=_RecLabel(), + btn_bench_reuse=_Stub(disabled=True), + btn_bench_reanalyze=_Stub(disabled=True), + btn_bench_calcheck=_Stub(disabled=True), + lbl_bench_calcheck=_RecLabel(), + 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, + ) + + +class _MitigatorStub: + """assignment_matrix is a METHOD, as the real mitigator's is.""" + + def __init__(self, errors): + self._e = dict(errors) + + def assignment_matrix(self, qubits=None): + e = self._e[int(list(qubits)[0])] + return np.array([[1 - e, e], [e, 1 - e]]) + + +def _fake_runner(plan): + """Plausible results for whatever the plan asked for.""" + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + # One mitigator for the whole target set, with assignment_matrix + # as a METHOD — the real shape. Errors sit just above the + # reported 0.05 so the run stays inside the consistency band and + # is applied in absolute mode. + out[idx] = [SimpleNamespace( + name='Local Readout Mitigator', + device_components=[f'Q{q}' for q in spec.qubits], + value=_MitigatorStub({q: 0.06 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] == pytest.approx(0.06) + assert state.qubit_props_data['readout_error'][7] == 0.05 # unmeasured + 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' + + +# ── 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' + + +# ── 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 + + +# ── 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) + + +# ── no false success ──────────────────────────────────────────────── + +def test_empty_epoch_is_not_applied_and_not_called_measured(monkeypatch, + tmp_path): + """A run that produced nothing must not say ✅. + + 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) + state = _state() + before_label = state.calibration_data_label + before_readout = state.qubit_props_data['readout_error'].copy() + + def _nothing_runner(plan): + return {i: [] for i, _s in enumerate(plan.specs)} + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_nothing_runner) + api = _setup(ctx) + api['run']() + + status = ctx.lbl_bench_status.value + assert '✅' not in status, f'a run that measured nothing reported success: {status}' + assert 'Nothing usable was measured' in status + assert "IBM's reported calibration is still in use" in status + # The reported epoch is untouched, and nothing claims to be measured. + assert state.calibration_data_label == before_label + assert 'measured' not in state.calibration_data_label + assert getattr(state, '_measured_epoch', None) is None + np.testing.assert_array_equal( + state.qubit_props_data['readout_error'], before_readout) + # ...and it is not offered for reuse. + assert not bench.list_measured_epochs('ibm_test') + # ...but the failure IS visible. + assert ctx.lbl_lucj_notices.value + + +def test_partial_measurement_is_applied_but_labelled_partial(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + + def _half_runner(plan): + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + # Only the first target qubit comes back. + q = spec.qubits[0] + out[idx] = [SimpleNamespace( + qubits=[q], device_components=[q], + value=SimpleNamespace(assignment_matrix=np.array( + [[0.99, 0.01], [0.01, 0.99]])))] + else: + out[idx] = [] + return out + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_half_runner) + api = _setup(ctx) + api['run']() + + status = ctx.lbl_bench_status.value + assert '⚠' in status and 'partial' in status, status + assert '1/4 qubits' in status, status + assert 'measured' in state.calibration_data_label, 'a partial run applies' + assert getattr(state, '_measured_epoch', None) is not None + + +def test_complete_measurement_reports_real_coverage(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_fake_runner) + api = _setup(ctx) + api['run']() + + status = ctx.lbl_bench_status.value + assert '✅' in status, status + assert '4/4 qubits' in status, status + + +# ── 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)) + _have_qe(monkeypatch) + state = _state() + before = state.calibration_data_label + + def _rejecting_runner(_plan): + raise bench.BenchmarkRunError( + 'chunk 1: job error — The number of circuit shots 43433984 ' + 'exceeds the system limit 10000000', + job_ids=['d3adb33f']) + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_rejecting_runner) + api = _setup(ctx) + api['run']() + + status = ctx.lbl_bench_status.value + assert '❌' in status + assert 'exceeds the system limit' in status, status + assert 'd3adb33f' in status, 'the job id must be reported for diagnosis' + assert state.calibration_data_label == before + assert getattr(state, '_measured_epoch', None) is None + assert ctx.btn_bench_run.disabled is False + + +# ── submittability gating ─────────────────────────────────────────── + +def test_run_is_disabled_when_the_plan_cannot_fit_a_job(monkeypatch, + tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + monkeypatch.setattr(bench, 'plan_is_submittable', + lambda plan, shots=1000: (False, 'too many shots')) + ctx = _ctx(candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP) + _setup(ctx) + assert ctx.btn_bench_run.disabled is True + assert 'too many shots' in ctx.lbl_bench_summary.value + + +def test_summary_states_circuits_shots_and_jobs(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(target=bench.TARGET_WHOLE) + _setup(ctx) + summary = ctx.lbl_bench_summary.value + assert 'circuits' in summary and 'shots' in summary and 'job' in summary + + +# ── consistency check and relative mode in the panel ─────────────── + +def _offset_runner(factor): + """A runner whose readout comes back `factor` times the reported value.""" + def _run(plan): + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + out[idx] = [SimpleNamespace( + name='Local Readout Mitigator', + device_components=[f'Q{q}' for q in spec.qubits], + value=_MitigatorStub({q: 0.05 * factor + for q in spec.qubits}))] + else: + out[idx] = [] + return out + return _run + + +def test_a_systematic_offset_triggers_relative_mode(monkeypatch, tmp_path): + """Everything uniformly worse than reported.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_offset_runner(3.0)) + api = _setup(ctx) + api['run']() + + consistency = ctx.lbl_bench_consistency.value + assert 'Benchmark applied' in consistency, consistency + assert 'constant factor' in consistency + assert 'Readout error' in consistency + for jargon in ('estimator mismatch', 'RELATIVE', 'systematic offset'): + assert jargon not in consistency, consistency + # Applied, and the label says which mode. + assert 'measured' in state.calibration_data_label + assert 'relative' in state.calibration_data_label + # Rescaled back onto the reported median. + epoch = state._measured_epoch + mask = epoch.measured_qubit_mask + assert np.median(epoch.qubit_props['readout_error'][mask]) == \ + pytest.approx(0.05, rel=1e-6) + + +def test_absolute_checkbox_opts_into_the_raw_values(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_offset_runner(3.0)) + ctx.chk_bench_absolute = _Dropdown(value=True) + api = _setup(ctx) + api['run']() + + epoch = state._measured_epoch + mask = epoch.measured_qubit_mask + assert np.median(epoch.qubit_props['readout_error'][mask]) == \ + pytest.approx(0.15, rel=1e-6), 'absolute mode must not rescale' + assert 'relative' not in state.calibration_data_label + + +def test_an_in_band_run_stays_absolute(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state() + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_offset_runner(1.2)) + api = _setup(ctx) + api['run']() + + consistency = ctx.lbl_bench_consistency.value + assert "in line with IBM's reported calibration" in consistency, \ + consistency + assert 'constant factor' not in consistency + assert 'relative' not in state.calibration_data_label + + +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. + + 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) + state = _state() + + def _runner_with_analysis_failure(plan): + out = {i: [] for i, _s in enumerate(plan.specs)} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + out[idx] = [SimpleNamespace( + name='Local Readout Mitigator', + device_components=[f'Q{q}' for q in spec.qubits], + value=_MitigatorStub({q: 0.06 for q in spec.qubits}))] + out['_notices'] = [ + "phase 2: analysis failed: 6x AttributeError: 'float' object " + "has no attribute 'device_components'"] + return out + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, + runner=_runner_with_analysis_failure) + api = _setup(ctx) + api['run']() + + status = ctx.lbl_bench_status.value + assert '✅' not in status, f'analysis failure reported as success: {status}' + assert 'partial' in status + assert 'analysis failed' in status, status + assert 'device_components' in status + assert 'analysis failed' in ctx.lbl_lucj_notices.value + + +# ── 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.""" + return { + 'when': when, 'level': plan.level, 'shots': plan.shots, + 'targets': {'qubits': list(plan.targets.qubits), + 'edges': [list(e) for e in plan.targets.edges]}, + 'specs': [{'kind': s.kind, 'qubits': list(s.qubits), 'layer': s.layer, + 'params': {k: ([list(p) for p in v] if k == 'pairs' + else v) + for k, v in s.params.items()}} + for s in plan.specs], + 'jobs': jobs or {'0': ['job-a'], '1': ['job-b']}, + } + + +def _readout_results(qubits, error=0.06): + return [SimpleNamespace( + name='Local Readout Mitigator', + device_components=[f'Q{q}' for q in qubits], + value=_MitigatorStub({q: error for q in qubits}))] + + +@pytest.mark.parametrize('selector_mode', [ + bench.TARGET_CURRENT, bench.TARGET_SWEEP, bench.TARGET_WHOLE, + bench.TARGET_CUSTOM, +]) +def test_reanalysis_ignores_the_selector_and_replays_the_run( + monkeypatch, tmp_path, selector_mode): + """Whatever the selector says, reanalysis must reproduce the run. + + Live bug: with the selector on "Current layout(s)" and nothing placed, + the rebuilt plan had ZERO specs, so the panel returned (0, 0) with an + empty notice list while the raw dump held every result. + """ + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(8) + original = bench.build_plan(bench.LEVEL_QUICK_READOUT, + bench.Targets([0, 1, 2, 3], []), 8, coupling) + record = _record_for(original) + monkeypatch.setattr(bench, 'latest_job_record', lambda name: record) + + seen = {} + + def _fake_reanalyze(plan, job_ids, backend, service=None): + seen['plan'] = plan + raw = {} + for idx, spec in enumerate(plan.specs): + raw[idx] = (_readout_results(spec.qubits) + if spec.kind == 'readout' else []) + return raw, [] + + monkeypatch.setattr(bench, 'reanalyze_from_jobs', _fake_reanalyze) + + state = _state() + # A runner_factory marks this as an injected-stack test, so the panel + # skips the main-thread preload of the real quantum stack. + ctx = _ctx(state=state, candidates=[], target=selector_mode, + runner=lambda plan: {}) + api = _setup(ctx) + api['reanalyze']() + + # The plan replayed is the recorded one, not the selector's. + assert seen['plan'].specs, 'reanalysis rebuilt an empty plan' + assert [s.kind for s in seen['plan'].specs] == \ + [s.kind for s in original.specs] + assert seen['plan'].targets.qubits == [0, 1, 2, 3] + + epoch = getattr(state, '_measured_epoch', None) + assert epoch is not None, ctx.lbl_bench_status.value + assert epoch.measured_count == (4, 0), epoch.notices + assert '✅' in ctx.lbl_bench_status.value + + +def test_reanalysis_without_a_plan_in_the_record_refuses_clearly(monkeypatch, + tmp_path): + """Old records predate the spec list; refuse rather than guess.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + monkeypatch.setattr(bench, 'latest_job_record', + lambda name: {'jobs': {'0': ['j']}, 'specs': []}) + called = [] + monkeypatch.setattr(bench, 'reanalyze_from_jobs', + lambda *a, **k: called.append(1) or ({}, [])) + + ctx = _ctx(candidates=[], runner=lambda plan: {}) + api = _setup(ctx) + api['reanalyze']() + + assert not called, 'must not reanalyse without the original plan' + status = ctx.lbl_bench_status.value + assert '❌' in status + assert 'no experiment list saved' in status, status + assert 'rebuild' in status + + +def test_results_found_but_none_attributed_is_never_silent(monkeypatch, + tmp_path): + """The mandatory invariant, on a deliberate target mismatch.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(8) + plan = bench.build_plan(bench.LEVEL_QUICK_READOUT, + bench.Targets([0, 1], []), 8, coupling) + qp = {'readout_error': np.full(8, 0.05)} + gp = {'cz_error': np.full(7, 0.01)} + + # Results for qubits that are NOT in the plan's targets and not in range. + raw = {0: _readout_results([90, 91])} + epoch = bench.results_to_epoch(raw, plan, qp, gp, coupling) + + assert epoch.measured_count == (0, 0) + 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 '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='Nothing to reanalyse'): + bench.reanalyze_from_jobs(empty, ['j'], object(), None) + + +def test_plan_from_record_round_trips(): + coupling = _line_edges(8) + original = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets([0, 1, 2, 3], coupling[:3]), 8, + coupling) + rebuilt = bench.plan_from_record(_record_for(original)) + + assert rebuilt is not None + assert rebuilt.level == original.level + assert rebuilt.shots == original.shots + assert [s.kind for s in rebuilt.specs] == [s.kind for s in original.specs] + assert bench.plan_circuit_count(rebuilt) == \ + bench.plan_circuit_count(original) + for a, b in zip(rebuilt.specs, original.specs): + assert a.qubits == b.qubits + assert a.params.get('pairs') == b.params.get('pairs') + + +# ── 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. + + `reanalyze_from_jobs` only runs 1Q RB before the 2Q layers when it is + given a list of lists. The panel flattened `record['jobs'].values()`, so + both phases went into one batch, the 2Q analyses were built before any + EPG existed, and the epoch carried un-subtracted values (median 4.05e-3 + instead of 2.96e-3) with nothing to indicate it. + """ + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(8) + original = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets([0, 1, 2, 3], coupling[:3]), 8, + coupling) + record = _record_for(original, + jobs={'0': ['phase1-job'], '1': ['phase2-job']}) + monkeypatch.setattr(bench, 'latest_job_record', lambda name: record) + + seen = {} + + def _fake_reanalyze(plan, job_ids, backend, service=None): + seen['job_ids'] = job_ids + raw = {i: (_readout_results(s.qubits) if s.kind == 'readout' else []) + for i, s in enumerate(plan.specs)} + return raw, [] + + monkeypatch.setattr(bench, 'reanalyze_from_jobs', _fake_reanalyze) + + ctx = _ctx(candidates=[], runner=lambda plan: {}) + _setup(ctx)['reanalyze']() + + passed = seen['job_ids'] + assert isinstance(passed[0], list), ( + f'phases were flattened into a single list: {passed}') + assert passed == [['phase1-job'], ['phase2-job']], passed + + +def test_reanalysis_runs_the_consistency_check_and_relative_mode(monkeypatch, + tmp_path): + """The reanalysis path never stashed the reported props, so the check + returned early: no consistency line, and no rescaling despite a x3 + offset.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(8) + original = bench.build_plan(bench.LEVEL_QUICK_READOUT, + bench.Targets([0, 1, 2, 3], []), 8, coupling) + monkeypatch.setattr(bench, 'latest_job_record', + lambda name: _record_for(original)) + + def _fake_reanalyze(plan, job_ids, backend, service=None): + raw = {} + for idx, spec in enumerate(plan.specs): + raw[idx] = (_readout_results(spec.qubits, error=0.15) + if spec.kind == 'readout' else []) + return raw, [] + + monkeypatch.setattr(bench, 'reanalyze_from_jobs', _fake_reanalyze) + + state = _state() # reported readout_error == 0.05 + ctx = _ctx(state=state, candidates=[], runner=lambda plan: {}) + _setup(ctx)['reanalyze']() + + consistency = ctx.lbl_bench_consistency.value + assert consistency, 'no consistency line was rendered after reanalysis' + assert 'Benchmark applied' in consistency, consistency + assert 'constant factor' in consistency + + epoch = state._measured_epoch + assert epoch.relative is True + mask = epoch.measured_qubit_mask + assert np.median(epoch.qubit_props['readout_error'][mask]) == \ + pytest.approx(0.05, rel=1e-6), 'values were not rescaled' + assert 'relative' in state.calibration_data_label + + +# ── the UI path must equal the direct path ───────────────────────── + +class _SpyAnalysis: + """Records what the 2Q analysis was given.""" + + def __init__(self, log): + self._log = log + self.options = {} + + def set_options(self, **kw): + self.options.update(kw) + if 'epg_1_qubit' in kw: + self._log.append(list(kw['epg_1_qubit'])) + + +def _spy_api(set_options_log, order_log): + """A runtime API whose 2Q analyses record their epg_1_qubit input.""" + class _Exp: + def __init__(self, *a, **k): + self.analysis = _SpyAnalysis(set_options_log) + + class _RB1Q(_Exp): + pass + + class _Data: + job_ids = ['j'] + + def __init__(self, kinds): + self._kinds = kinds + + def status(self): + return SimpleNamespace(name='DONE') + + def errors(self): + return None + + def analysis_errors(self): + return None + + def block_for_results(self): + pass + + def child_data(self, idx=None): + kind = self._kinds[idx if idx is not None else 0] + results = [] + if kind == 'rb1q': + results = [SimpleNamespace(name='EPG_sx', + device_components=[f'Q{q}'], + value=7e-4) for q in (0, 1)] + return SimpleNamespace( + analysis_results=lambda *a, **k: results, + child_data=lambda *a, **k: []) + + class _Batch: + def __init__(self, experiments, **kw): + self._n = len(experiments) + + def run(self, **kw): + return _Data(['rb1q'] * self._n) + + class _Session: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + return SimpleNamespace( + Session=_Session, SamplerV2=lambda mode=None: None, + BatchExperiment=_Batch, ParallelExperiment=_Exp, + LocalReadoutError=_Exp, StandardRB=_RB1Q, T1=_Exp, T2Hahn=_Exp) + + +def test_phase_one_is_analysed_before_phase_two(monkeypatch): + """Order is the whole mechanism: the 2Q analyses are CONSTRUCTED with the + phase-1 EPGs, so phase 1 must be submitted and folded first.""" + coupling = _line_edges(8) + plan = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets([0, 1], [(0, 1)]), 8, coupling) + order = [] + set_log = [] + api = _spy_api(set_log, order) + + class _Batch(api.BatchExperiment): + def __init__(self, experiments, **kw): + order.append(len(experiments)) + super().__init__(experiments, **kw) + + api.BatchExperiment = _Batch + monkeypatch.setattr(bench, '_runtime_api', lambda: api) + bench._reset_runtime_cache() + try: + runner = bench.make_runtime_runner(object()) + runner(plan) + finally: + bench._reset_runtime_cache() + + assert len(order) == 2, f'expected two phases, got {order}' + # Phase 1 carries readout + rb1q; phase 2 carries only the 2Q layers. + n_2q = len([s for s in plan.specs if s.kind == 'rb2q_layer']) + assert order[1] == n_2q, order + assert set_log, 'the 2Q analysis was never given epg_1_qubit' + + +def test_ui_reanalysis_matches_direct_reanalysis(monkeypatch, tmp_path): + """Same record, same jobs -> identical epoch, and the same EPG objects + handed to set_options on the UI path.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(8) + original = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets([0, 1], [(0, 1)]), 8, coupling) + record = _record_for(original, jobs={'0': ['p1'], '1': ['p2']}) + + ui_calls, direct_calls = [], [] + + def _make_reanalyze(sink): + def _rean(plan, job_ids, backend, service=None): + sink.append({'plan_kinds': [s.kind for s in plan.specs], + 'job_ids': job_ids}) + raw = {} + for idx, spec in enumerate(plan.specs): + raw[idx] = (_readout_results(spec.qubits) + if spec.kind == 'readout' else []) + raw['_notices'] = ['1Q EPG subtraction: applied to 1 pairs'] + return raw, [] + return _rean + + # Direct path. + monkeypatch.setattr(bench, 'reanalyze_from_jobs', + _make_reanalyze(direct_calls)) + raw_d, _ = bench.reanalyze_from_jobs( + original, [['p1'], ['p2']], object(), None) + qp = {'readout_error': np.full(8, 0.05)} + gp = {'cz_error': np.full(7, 0.01)} + direct_epoch = bench.results_to_epoch(raw_d, original, dict(qp), dict(gp), + coupling, when=1.0) + + # UI path. + monkeypatch.setattr(bench, 'latest_job_record', lambda name: record) + monkeypatch.setattr(bench, 'reanalyze_from_jobs', + _make_reanalyze(ui_calls)) + state = _state() + ctx = _ctx(state=state, candidates=[], runner=lambda plan: {}) + _setup(ctx)['reanalyze']() + ui_epoch = state._measured_epoch + + assert ui_calls, 'the UI never reached reanalyze_from_jobs' + assert ui_calls[0]['plan_kinds'] == direct_calls[0]['plan_kinds'] + assert ui_calls[0]['job_ids'] == direct_calls[0]['job_ids'] == \ + [['p1'], ['p2']] + assert ui_epoch.measured_count == direct_epoch.measured_count + np.testing.assert_allclose(ui_epoch.qubit_props['readout_error'], + direct_epoch.qubit_props['readout_error']) + assert any('1Q EPG subtraction' in n for n in ui_epoch.notices), \ + ui_epoch.notices + + +# ── the calibration check, wired ─────────────────────────────────── + +def _calcheck_state(n_q=16): + state = _state(n_q) + state.layouts_data = {0: {'alpha': [str(q) for q in range(8)], + 'beta': [str(q) for q in range(8, 14)], + 'ancilla': [], 'other': []}} + return state + + +def _calcheck_runner(par_factor=3.0, seq_factor=3.0): + """Both arms measure; each arm's cz_error is `factor` x the reported.""" + calls = {'n': 0} + + def _run(plan): + calls['n'] += 1 + factor = par_factor if calls['n'] == 1 else seq_factor + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + out[idx] = _readout_results(spec.qubits) + elif spec.kind == 'rb1q': + out[idx] = [SimpleNamespace(name='EPG_sx', + device_components=[f'Q{q}'], + value=7e-4) + for q in spec.qubits] + elif spec.kind == 'rb2q_layer': + out[idx] = [ + SimpleNamespace(name='EPG_cz', + device_components=[f'Q{p[0]}', f'Q{p[1]}'], + value=0.01 * factor) + for p in spec.params['pairs']] + else: + out[idx] = [] + return out + + _run.calls = calls + return _run + + +def test_calibration_check_button_needs_six_edges(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + # Only 3 edges reachable -> disabled, and it says why. + ctx = _ctx(state=_state(8), candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP) + _setup(ctx) + assert ctx.btn_bench_calcheck.disabled is True + assert 'at least 6 target edges' in ctx.lbl_bench_calcheck.value + + # Whole QPU on a 16-qubit line -> 15 edges -> enabled, with a cost line. + ctx = _ctx(state=_calcheck_state(), candidates=[], + target=bench.TARGET_WHOLE) + _setup(ctx) + line = ctx.lbl_bench_calcheck.value + assert '6 edges × 2 arms' in line, line + assert 'circuits' in line and 'job(s)' in line and 'QPU (estimate)' in line + # It spends QPU time, so the Open-plan acknowledgement gates it too. + assert ctx.btn_bench_calcheck.disabled is True + ctx.chk_bench_ack.value = True + assert ctx.btn_bench_calcheck.disabled is False + + +def test_calibration_check_renders_the_verdict_table(monkeypatch, tmp_path): + """Both arms run, the table renders, and NO epoch is applied.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _calcheck_state() + before_label = state.calibration_data_label + before_gate = state.gate_props_data['cz_error'].copy() + + runner = _calcheck_runner(par_factor=3.0, seq_factor=3.0) + ctx = _ctx(state=state, candidates=[], target=bench.TARGET_WHOLE, + runner=runner) + api = _setup(ctx) + ctx.chk_bench_ack.value = True # Open plan: acknowledge first + api['calibration_check']() + + assert runner.calls['n'] == 2, 'both arms must run' + table_html = ctx.lbl_bench_calcheck.value + 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 bias' in table_html, table_html + + # THE INVARIANT: a calibration check measures the instrument. + assert getattr(state, '_measured_epoch', None) is None, \ + 'the calibration check must not apply an epoch' + assert state.calibration_data_label == before_label + np.testing.assert_array_equal(state.gate_props_data['cz_error'], + before_gate) + assert 'unchanged' in ctx.lbl_bench_status.value + + +def test_calibration_check_distinguishes_crosstalk(monkeypatch, tmp_path): + """Parallel offset, sequential clean -> crosstalk, not estimator bias.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(state=_calcheck_state(), candidates=[], + target=bench.TARGET_WHOLE, + runner=_calcheck_runner(par_factor=3.0, seq_factor=1.0)) + api = _setup(ctx) + ctx.chk_bench_ack.value = True + api['calibration_check']() + assert 'crosstalk' in ctx.lbl_bench_calcheck.value, \ + ctx.lbl_bench_calcheck.value + + +def test_calibration_check_writes_its_record_kind(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + coupling = _line_edges(16) + plan = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets(list(range(8)), coupling[:6]), 16, + coupling) + when = 1_700_000_500.0 + path = bench.save_job_record( + 'ibm_test', when, plan, jobs={'0': ['a'], '1': ['b']}, + kind=bench.RECORD_KIND_CALIBRATION_CHECK, + arms=['parallel', 'sequential']) + assert path + + with open(path, encoding='utf-8') as fh: + record = json.load(fh) + assert record['kind'] == bench.RECORD_KIND_CALIBRATION_CHECK + assert record['arms'] == ['parallel', 'sequential'] + + back = bench.latest_job_record('ibm_test') + assert back['kind'] == bench.RECORD_KIND_CALIBRATION_CHECK + assert back['arms'] == ['parallel', 'sequential'] + + +def test_reanalyze_routes_a_calibration_check_record(monkeypatch, tmp_path): + """Reanalyze must reproduce the table and still apply no epoch.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + + coupling = _line_edges(16) + par = bench.build_plan(bench.LEVEL_TARGETED, + bench.Targets(list(range(8)), coupling[:6]), 16, + coupling) + record = _record_for(par, jobs={'0': ['p1'], '1': ['p2']}) + record['kind'] = bench.RECORD_KIND_CALIBRATION_CHECK + record['arms'] = ['parallel', 'sequential'] + monkeypatch.setattr(bench, 'latest_job_record', lambda name: record) + + runner = _calcheck_runner(par_factor=3.0, seq_factor=3.0) + + def _fake_rean(plan, job_ids, backend, service=None): + return runner(plan), [] + + monkeypatch.setattr(bench, 'reanalyze_from_jobs', _fake_rean) + + state = _calcheck_state() + ctx = _ctx(state=state, candidates=[], runner=lambda plan: {}) + _setup(ctx)['reanalyze']() + + assert 'Calibration check' in ctx.lbl_bench_calcheck.value + assert 'reanalysed (no QPU)' in ctx.lbl_bench_status.value + assert getattr(state, '_measured_epoch', None) is None, \ + 'reanalysing a calibration check must not apply an epoch' + + +def test_calibration_check_table_is_saved(tmp_path, monkeypatch): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + table = {'rows': [{'edge': (0, 1), 'reported': 1e-3, 'parallel': 3e-3, + 'sequential': 3e-3}], + 'ratio_parallel': 3.0, 'ratio_sequential': 3.0, + 'verdict': 'estimator mismatch: both runs are offset'} + path = bench.save_calibration_check('ibm_test', 1_700_000_600.0, table) + assert path and path.endswith('_calcheck.json') + with open(path, encoding='utf-8') as fh: + back = json.load(fh) + assert back['ratio_parallel'] == 3.0 + assert back['rows'][0]['edge'] == [0, 1] + assert 'estimator' in back['verdict'] + + +def _descend(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 child in getattr(node, 'children', ()) or (): + _descend(child, seen) + return seen + + +def _build_real_ui(monkeypatch): + """A real MapperUIBuilder, for checks that need the actual widgets.""" + 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, [(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 + 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() + return builder, st + + +# ── 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.""" + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + state = _state(n_q) + + def _runner(plan): + out = {} + for idx, spec in enumerate(plan.specs): + if spec.kind == 'readout': + out[idx] = _readout_results( + spec.qubits, error=0.05 * factors.get('readout_error', 1)) + else: + out[idx] = [] + return out + + ctx = _ctx(state=state, candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, runner=_runner) + api = _setup(ctx) + api['run']() + return ctx, state + + +def test_copy_all_in_band(monkeypatch, tmp_path): + ctx, _ = _run_with_factors(monkeypatch, tmp_path, + {'readout_error': 1.2}) + line = ctx.lbl_bench_consistency.value + assert '✅ Benchmark applied' in line + assert "measured values are in line with IBM's reported calibration" \ + in line, line + assert 'constant factor' not in line + + +def test_copy_names_in_band_and_rescaled_properties(): + """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) + + stats = { + 'readout_error': {'ratio_of_medians': 1.55, 'n_worse_2x': 53, + 'n': 156, 'median_reported': 3.4e-3}, + 't1': {'ratio_of_medians': 0.70, 'n_worse_2x': 0, 'n': 156, + 'median_reported': 250.0}, + 't2': {'ratio_of_medians': 0.24, 'n_worse_2x': 0, 'n': 156, + 'median_reported': 297.0}, + 'cz_error': {'ratio_of_medians': 2.11, 'n_worse_2x': 170, 'n': 352, + 'median_reported': 1.4e-3}, + } + epoch = SimpleNamespace(planned_count=(156, 352), + measured_count=(156, 352)) + line = api['result_sentence'](epoch, stats, {'t2', 'cz_error'}) + + 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" in line + assert 'Reference: Relative mode' in line + for jargon in ('estimator mismatch', 'RELATIVE', 'systematic offset', + '⚠'): + assert jargon not in line, f'{jargon!r} leaked into the sentence' + + +def test_copy_reports_unmeasured_elements(): + from iqmapper.ui.benchmark_panel import setup_benchmark_panel + api = setup_benchmark_panel(_ctx()) + stats = {'readout_error': {'ratio_of_medians': 1.1, 'n_worse_2x': 0, + 'n': 120, 'median_reported': 3e-3}} + epoch = SimpleNamespace(planned_count=(156, 352), + measured_count=(120, 340)) + line = api['result_sentence'](epoch, stats, set()) + assert '36 qubits and 12 edges could not be measured and keep their '\ + 'reported values.' in line, line + + +def test_copy_for_an_empty_result(monkeypatch, tmp_path): + monkeypatch.setattr('iqmapper.data._CACHE_DIR', str(tmp_path)) + _have_qe(monkeypatch) + ctx = _ctx(state=_state(), candidates=[_entry([0, 1], [2], [3])], + target=bench.TARGET_SWEEP, + runner=lambda plan: {i: [] for i, _ in enumerate(plan.specs)}) + _setup(ctx)['run']() + status = ctx.lbl_bench_status.value + assert '⚠ Nothing usable was measured' in status, status + assert "IBM's reported calibration is still in use" in status + + +def test_no_developer_jargon_anywhere_after_a_run(monkeypatch, tmp_path): + """The whole rendered panel, not just the one line.""" + ctx, _ = _run_with_factors(monkeypatch, tmp_path, + {'readout_error': 3.0}) + rendered = ' '.join([ + ctx.lbl_bench_consistency.value, ctx.lbl_bench_details.value, + ctx.lbl_bench_status.value, ctx.lbl_bench_summary.value]) + for jargon in ('estimator mismatch', 'RELATIVE', 'systematic offset'): + assert jargon not in rendered, f'{jargon!r} still shown to the user' + + +def test_details_table_rows_and_legend(): + from iqmapper.ui.benchmark_panel import setup_benchmark_panel + ctx = _ctx() + api = setup_benchmark_panel(ctx) + stats = { + 'readout_error': {'ratio_of_medians': 1.55, 'n_worse_2x': 53, + 'n': 156, 'median_reported': 3.4e-3}, + 't2': {'ratio_of_medians': 0.24, 'n_worse_2x': 0, 'n': 156, + 'median_reported': 297.0}, + 'cz_error': {'ratio_of_medians': 2.11, 'n_worse_2x': 170, 'n': 352, + 'median_reported': 1.4e-3}, + } + api['render_details'](stats, {'t2', 'cz_error'}, {}) + html = ctx.lbl_bench_details.value + + assert 'Readout error' in html and '×1.55' in html + assert ('53 of 156 qubits >2× worse' in html + or '53 of 156 qubits >2× worse' in html), html + # rescaled rows carry the marker; in-band rows do not + assert '×0.24 ⚠' in html and '×2.11 ⚠' in html, html + assert '×1.55 ⚠' not in html, 'an in-band row was marked' + # a rescaled property with no individual outliers shows a dash + assert '—' in html + assert 'rescaled (different estimator)' in html + assert 'as measured' in html + assert 'median aligned to IBM' in html, 'legend missing' + + +def test_details_accordion_is_collapsed_by_default(monkeypatch): + b, _ = _build_real_ui(monkeypatch) + assert b.acc_bench_details.selected_index is None + assert b.acc_bench_details.get_title(0) == 'Details' + inside = _descend(b.acc_bench_details) + assert any(w is b.lbl_bench_details for w in inside) + assert any(w is b.btn_bench_show_on_map for w in inside) + + +def test_show_on_map_sets_the_threshold(monkeypatch, tmp_path): + """"170 edges" becomes something you can see.""" + from iqmapper.ui.benchmark_panel import setup_benchmark_panel + ctx = _ctx() + api = setup_benchmark_panel(ctx) + stats = {'cz_error': {'ratio_of_medians': 2.11, 'n_worse_2x': 170, + 'n': 352, 'median_reported': 1.4e-3}} + api['render_details'](stats, {'cz_error'}, {}) + + assert ctx.btn_bench_show_on_map.layout.display == '' + assert '170 edges' in ctx.btn_bench_show_on_map.description + + api['show_on_map']() + assert ctx.chk_err_threshold.value is True + assert ctx.dd_gate_prop.value == 'cz_error' + assert float(ctx.txt_g_thr_max.value) == pytest.approx(2 * 1.4e-3) + + +def test_show_on_map_is_hidden_when_nothing_qualifies(): + from iqmapper.ui.benchmark_panel import setup_benchmark_panel + ctx = _ctx() + api = setup_benchmark_panel(ctx) + api['render_details']( + {'cz_error': {'ratio_of_medians': 1.1, 'n_worse_2x': 0, 'n': 352, + 'median_reported': 1.4e-3}}, set(), {}) + assert ctx.btn_bench_show_on_map.layout.display == 'none' + api['show_on_map']() # a no-op, not a crash + assert ctx.chk_err_threshold.value is False diff --git a/tests/test_calibration_epoch.py b/tests/test_calibration_epoch.py index b3fdc53..7dd550d 100644 --- a/tests/test_calibration_epoch.py +++ b/tests/test_calibration_epoch.py @@ -34,7 +34,7 @@ def t2(self, q): return 1e-9 _SNAP_T2 = np.array([80.0, 82.0, 84.0, 86.0, 88.0]) # µs -def _build(monkeypatch, *, snapshot): +def _build(monkeypatch, *, snapshot, ancilla=0): monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) captured = {} monkeypatch.setattr( @@ -68,10 +68,13 @@ def _build(monkeypatch, *, snapshot): if snapshot: state.time_mode = 'point' state.point_timestamp = '2026-07-01 08:00:00' + # Run now routes by ancilla count: a fixed count (>= 0) → the legacy + # get_all_zigzag_layouts search these tests mock; Auto (-1) → the sweep. + b.lucj_ancilla_dd.value = ancilla 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) @@ -86,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) @@ -103,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' @@ -113,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) @@ -123,3 +126,29 @@ def test_status_note_only_for_snapshot(monkeypatch): b2, state2, _ = _build(monkeypatch, snapshot=False) b2.btn_lucj_run.click() assert 'scored on' not in b2.lbl_lucj_status.value + + +# ── 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 + snapshot's props — the SAME epoch as the circuit score — never the live + sentinel. Capture the props object sweep_ancilla_layouts receives.""" + swept = {} + + def _fake_sweep(norb, backend, props, **kw): + swept['props'] = props + # Minimal well-formed result: no strata → the handler renders the + # "no candidates" note without needing a real backend/coupling map. + return {'strata': {}, 'vf2_truncated': False, 'per_stratum': {}, + 'mapping_cap': None, 'k_max_effective': None} + + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", _fake_sweep) + b, state, _ = _build(monkeypatch, snapshot=True, ancilla=-1) + b.btn_lucj_run.click() + pr = swept['props'] + assert pr is not state.initial_props + # Live sentinel would be 0.99; the snapshot readout is 0.004. + assert pr.readout_error(3) == _SNAP_RO[3] + assert pr.gate_error('cz', (2, 3)) == _SNAP_CZ[2] diff --git a/tests/test_cascade.py b/tests/test_cascade.py new file mode 100644 index 0000000..a8e9e7d --- /dev/null +++ b/tests/test_cascade.py @@ -0,0 +1,244 @@ +"""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 iqmapper.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(): + # 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, + shuffle_seed=None) + + +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) + # 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 + + +# ── 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 + + +# ── 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 — 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 + + +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 (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 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'] + assert 'lqs_circuit' not in res['strata'][2][0] # byte-compat shape intact diff --git a/tests/test_combined_sweep.py b/tests/test_combined_sweep.py new file mode 100644 index 0000000..a8b81a2 --- /dev/null +++ b/tests/test_combined_sweep.py @@ -0,0 +1,281 @@ +"""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 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_copy_lengths.py b/tests/test_copy_lengths.py new file mode 100644 index 0000000..ae07456 --- /dev/null +++ b/tests/test_copy_lengths.py @@ -0,0 +1,214 @@ +"""The message diet, enforced. + +The interface says what happened and what to do, in one short sentence; the +reference page (docs/reference.md) 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 + +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)) + + +# ── reference anchors ─────────────────────────────────────────────── + +REFERENCE = 'docs/reference.md' + + +def _reference_anchors(): + headings = set() + with open(REFERENCE, encoding='utf-8') as fh: + for line in fh: + if line.startswith('#'): + headings.add(line.lstrip('#').strip()) + return headings + + +def test_every_reference_pointer_has_a_matching_heading(): + """A dangling `· Reference: X` is worse than no pointer at all.""" + anchors = _reference_anchors() + pointer = re.compile(r'Reference:\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, ( + 'Reference pointers with no matching heading:\n ' + + '\n '.join(missing) + + f'\nheadings present: {sorted(anchors)}') + + +def test_no_ui_string_still_points_at_the_readme(): + stale = [f'{path}:{lineno}' for path in SOURCES + for lineno, raw in _string_constants(path) if 'README:' in raw] + assert not stale, stale + + +def test_the_reference_page_covers_every_entry_used(): + anchors = _reference_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', + 'Multi-circuit planner'): + assert name in anchors, f'{REFERENCE} is missing the {name!r} entry' 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_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) diff --git a/tests/test_diverse_default.py b/tests/test_diverse_default.py new file mode 100644 index 0000000..bc89ca9 --- /dev/null +++ b/tests/test_diverse_default.py @@ -0,0 +1,91 @@ +"""Diverse enumeration follows the chip family when a backend connects: ON +for heavy-hex (Heron), OFF for the square-lattice Nighthawk. A manual toggle +holds until another backend is connected. +""" +from types import SimpleNamespace + +import pytest + +from iqmapper.constants import resolve_coords + +from test_scan_ui import _fake_device_data, _sync_spawn + +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') + + +def _connect(monkeypatch, backends, first): + """A builder connected to `backends[first]`, as launch_mapper builds it.""" + import iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr("iqmapper.data.generate_device_data", _fake_device_data) + monkeypatch.setattr("iqmapper.connection._check_properties", + lambda b, n: (object(), None)) + + from iqmapper.state import SessionState + from iqmapper.ui.builder import MapperUIBuilder + + backend = backends[first] + coords, chip = resolve_coords(backend) + state = SessionState() + state.active_backend, state.active_backend_name = backend, first + state.active_chip, state.active_coords = chip, coords + state.active_service = SimpleNamespace(backend=lambda n: backends[n]) + state.available_backends = list(backends) + state.props_warning = None + state.initial_props = object() + state.active_ansatz = 'lucj' + state.active_vendor = 'IBM' + state.custom_colors = [] + state.cal_history_dates = ['_seed_'] + b = MapperUIBuilder(state) + b.build() + return b + + +def _switch(b, name): + dd = b.dd_backend_switch + if name not in [o[1] if isinstance(o, tuple) else o for o in dd.options]: + dd.options = list(dd.options) + [name] + dd.value = name + assert b.state.active_backend_name == name + + +@pytest.fixture +def backends(): + return {'fake_fez': fake_provider.FakeFez(), + 'fake_nighthawk': fake_provider.FakeNighthawk()} + + +def test_heron_connects_with_diverse_enumeration_on(monkeypatch, backends): + b = _connect(monkeypatch, backends, 'fake_fez') + assert b.state.active_chip.startswith('Heron') + assert b.chk_diverse_cap.value is True + + +def test_nighthawk_connects_with_diverse_enumeration_off(monkeypatch, + backends): + b = _connect(monkeypatch, backends, 'fake_nighthawk') + assert b.state.active_chip.startswith('Nighthawk') + assert b.chk_diverse_cap.value is False + + +def test_a_manual_toggle_holds_until_another_backend_connects(monkeypatch, + backends): + b = _connect(monkeypatch, backends, 'fake_nighthawk') + b.chk_diverse_cap.value = True # the user opts in + b._load_device_graph() # date / hour reload + assert b.chk_diverse_cap.value is True + + _switch(b, 'fake_fez') + assert b.chk_diverse_cap.value is True + b.chk_diverse_cap.value = False # the user opts out + b._load_device_graph() + assert b.chk_diverse_cap.value is False + + _switch(b, 'fake_nighthawk') + assert b.chk_diverse_cap.value is False + _switch(b, 'fake_fez') + assert b.chk_diverse_cap.value is True # Heron default again diff --git a/tests/test_diversity.py b/tests/test_diversity.py new file mode 100644 index 0000000..8ec17e0 --- /dev/null +++ b/tests/test_diversity.py @@ -0,0 +1,121 @@ +"""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 iqmapper.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 + + +# ── 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 + + +# ── 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 + + +# ── 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) == [] + + +# ── 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_engine_dedupe_plans.py b/tests/test_engine_dedupe_plans.py new file mode 100644 index 0000000..53382d7 --- /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()} + + +# ── 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] + + +# ── 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_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_error_tab_backend_switch.py b/tests/test_error_tab_backend_switch.py index 4860d81..3f51238 100644 --- a/tests/test_error_tab_backend_switch.py +++ b/tests/test_error_tab_backend_switch.py @@ -1,258 +1,146 @@ -"""Regression tests for the Error tab's "Showing:" header after a backend switch. +"""Error-tab header must follow a backend switch. -The bug: ui.builder discarded the time panel's `api` handle -(``self._time_panel, _ = _build_time_panel(...)``), so nothing could re-render -the panel from outside its own observers. A backend switch happens outside -those observers, so the header kept naming the PREVIOUS backend while the plot -below it already showed the new one. - -The fix threads an optional ``refresh_time_panel`` hook through the -setup_backend_switch ctx and calls it on both the success and rollback paths. -These tests lock in all three halves: - * the panel's api.rebuild() actually re-renders the header from live state; - * the switch handler invokes the hook exactly once on success, and a hook - that raises does not break the switch; - * the rollback path invokes it too, so a failed switch doesn't strand the - header on a backend that never finished loading. - -Fully offline: no service, no network, no calibration fetch. +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 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 -import iqmapper.ui.backend_switch as bs -import iqmapper.ui.time_panel as tp +# ── stubs shared by the switch-wiring tests ───────────────────────────────── -# ═══════════════════════════════════════════════════════════════════════ -# (a) api.rebuild() re-renders the header with the CURRENT backend name -# ═══════════════════════════════════════════════════════════════════════ +class _W: + """Minimal widget stub: settable attrs + a no-op observe.""" + def __init__(self, **kw): + self.__dict__.update(kw) -def _build_panel(backend_name): - """Build a real time panel in 'live' mode against a stub state.""" - from iqmapper.state import SessionState + def observe(self, *a, **k): + pass - state = SessionState() - state.active_backend_name = backend_name - state.time_mode = 'live' - panel, api = tp.build_time_panel( - state=state, - data_mod=SimpleNamespace(), - export_mod=SimpleNamespace(), - refresh_plot=lambda: None, - load_device_graph=lambda *a, **k: None, - spawn_bg=lambda fn, *a, **k: None, # never run background work +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, ) - return state, api -def _header_text(api): - return api._b.lbl_header.value +def _export_stub(): + return types.SimpleNamespace(compute_error_delta=lambda a, b, c, d: ({}, {})) -def test_rebuild_updates_header_to_new_backend(): - """The header must follow state.active_backend_name across a switch.""" - state, api = _build_panel('ibm_old') - assert 'ibm_old' in _header_text(api) +# ── 1. header re-renders on api.rebuild() (the switch hook's effect) ───────── - # Simulate what a backend switch does to state, then refresh. - state.active_backend_name = 'ibm_new' - api.rebuild() - - header = _header_text(api) - assert 'ibm_new' in header - assert 'ibm_old' not in header +def test_header_updates_after_backend_switch(): + from iqmapper.ui.time_panel import build_time_panel + from iqmapper.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 -def test_status_text_follows_state_without_rebuild(): - """status_text() reads state directly — it is the pure describer, and is - what the header renders. Guards against the describer regressing.""" - state, api = _build_panel('ibm_old') + # Post-switch condition (as the builder's reset produces it, then the + # switch wiring calls api.rebuild()). state.active_backend_name = 'ibm_new' - assert api.status_text() == 'Live calibration — ibm_new' - - -# ═══════════════════════════════════════════════════════════════════════ -# (b) + (c) setup_backend_switch invokes the hook -# ═══════════════════════════════════════════════════════════════════════ - -class _FakeWidget: - """Minimal stand-in for the widgets the handler touches.""" - - def __init__(self, value=None): - self.value = value - self.disabled = False - self.options = () - self._handlers = [] + state.time_mode = 'live' + state._live_qubit_props = None + api.rebuild() - def observe(self, handler, names=None): - self._handlers.append(handler) + assert 'ibm_new' in api._b.lbl_header.value + assert 'ibm_old' not in api._b.lbl_header.value -def _switch_ctx(monkeypatch, *, load_device_graph, refresh_time_panel, - available=('ibm_old', 'ibm_new')): - """Wire a switch context whose every external dependency is stubbed.""" - # Lazy imports inside the handler → patch at the source modules. - monkeypatch.setattr('iqmapper.connection._check_properties', - lambda backend, name: ({'props': True}, ''), - raising=False) - monkeypatch.setattr('iqmapper.constants.resolve_coords', - lambda backend: ({0: (0, 0)}, 'Heron r3'), - raising=False) +# ── switch-wiring: hook fires on success (after load) + tolerates failure ──── - state = SimpleNamespace( - active_service=SimpleNamespace(backend=lambda name: SimpleNamespace(name=name)), - active_backend=SimpleNamespace(name='ibm_old'), - active_backend_name='ibm_old', - active_chip='Heron r3', - initial_props={}, - props_warning='', - active_coords={}, - qubit_ids=[0, 1], - layouts_data={}, - available_backends=list(available), - ) - dd = _FakeWidget('ibm_old') - ctx = SimpleNamespace( +def _switch_ctx(state, *, load_device_graph, refresh_time_panel): + return SimpleNamespace( state=state, - dd_backend_switch=dd, - lbl_switch_status=_FakeWidget(''), - lbl_calibration_date=_FakeWidget(''), - lbl_props_warning=_FakeWidget(''), - chk_keep_layout=_FakeWidget(False), + 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, + refresh=lambda: None, get_export=lambda: None, out=SimpleNamespace(), refresh_time_panel=refresh_time_panel, ) - handler = bs.setup_backend_switch(ctx) - return handler, state, ctx - - -def test_hook_invoked_once_on_successful_switch(monkeypatch): - """Success path: the hook fires exactly once, after load_device_graph.""" - order = [] - handler, state, _ = _switch_ctx( - monkeypatch, - load_device_graph=lambda **kw: order.append('load'), - refresh_time_panel=lambda: order.append('refresh'), - ) - - handler({'new': 'ibm_new'}) - - assert order.count('refresh') == 1, order - assert order == ['load', 'refresh'], "hook must run AFTER the graph reload" - assert state.active_backend_name == 'ibm_new' - - -def test_raising_hook_does_not_break_the_switch(monkeypatch): - """A refresh failure must never abort a switch that otherwise succeeded.""" - def _boom(): - raise RuntimeError("panel exploded") - - handler, state, ctx = _switch_ctx( - monkeypatch, - load_device_graph=lambda **kw: None, - refresh_time_panel=_boom, - ) - - handler({'new': 'ibm_new'}) # must not raise - - assert state.active_backend_name == 'ibm_new' - assert '✅' in ctx.lbl_switch_status.value - assert ctx.switching_backend[0] is False - - -def test_hook_invoked_on_rollback_path(monkeypatch): - """Failed switch: state rolls back, so the header must be refreshed too.""" - calls = [] - - def _explode(**kw): - raise RuntimeError("graph load failed") - - handler, state, ctx = _switch_ctx( - monkeypatch, - load_device_graph=_explode, - refresh_time_panel=lambda: calls.append(state.active_backend_name), - ) - - handler({'new': 'ibm_new'}) # must not raise - - # Rolled back to the original backend... - assert state.active_backend_name == 'ibm_old' - # ...and the hook saw the rolled-back name, not the failed one. - assert calls == ['ibm_old'], calls - assert '❌' in ctx.lbl_switch_status.value - - -def test_builder_retains_time_api_and_wires_the_hook(monkeypatch): - """The original bug lived here: the builder threw the api handle away. - - Locks both halves of the wiring — the handle is kept as `_time_api`, and - the ctx passed to setup_backend_switch carries a working hook. - """ - import numpy as np - - def _fake_device_data(state, vendor, chip, date, prefetched_props=None): - n = 5 - 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("iqmapper.data.generate_device_data", _fake_device_data) - - captured = {} - real_setup = bs.setup_backend_switch - monkeypatch.setattr( - "iqmapper.ui.backend_switch.setup_backend_switch", - lambda ctx: (captured.setdefault('ctx', ctx), real_setup(ctx))[1], - ) +def _fresh_state(): from iqmapper.state import SessionState - from iqmapper.ui.builder import MapperUIBuilder - state = SessionState() - state.active_backend = object() - state.active_backend_name = "ibm_old" - state.active_chip = "stub_chip" - state.active_service = None - state.available_backends = [] - state.props_warning = None - state.initial_props = None - state.active_ansatz = "lucj" - state.active_vendor = "IBM" - state.active_coords = [] - state.custom_colors = [] - state.cal_history_dates = ["_seed_"] - - builder = MapperUIBuilder(state) - builder.build() - - # The handle survives construction (the regression). - assert getattr(builder, '_time_api', None) is not None - - # And the switch wiring received a hook that actually drives it. - hook = getattr(captured['ctx'], 'refresh_time_panel', None) - assert callable(hook) - - state.active_backend_name = 'ibm_new' - hook() - assert 'ibm_new' in builder._time_api._b.lbl_header.value - - -def test_missing_hook_is_a_noop(monkeypatch): - """Callers that never build a time panel omit the ctx key entirely.""" - handler, state, _ = _switch_ctx( - monkeypatch, - load_device_graph=lambda **kw: None, - refresh_time_panel=None, - ) - - handler({'new': 'ibm_new'}) # must not raise - - assert state.active_backend_name == 'ibm_new' + 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 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')) + + 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 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')) + + 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_evaluation.py b/tests/test_evaluation.py new file mode 100644 index 0000000..54c5158 --- /dev/null +++ b/tests/test_evaluation.py @@ -0,0 +1,511 @@ +"""Tests for the offline engine-comparison harness. + +Everything runs against a temporary cache directory holding synthetic +calibrations. No network, no real cache, no QPU. +""" +import json +import os + +import numpy as np +import pytest + +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): + """Two rails plus rungs: wide enough for norb=4 with a bridge.""" + edges = [] + for i in range(n_rungs - 1): + edges.append((i, i + 1)) # rail A + edges.append((n_rungs + i, n_rungs + i + 1)) # rail B + for i in range(n_rungs): + edges.append((i, 2 * n_rungs + i)) # A -> rung + edges.append((2 * n_rungs + i, n_rungs + i)) # rung -> B + return edges + + +def _write_cache(tmp_path, backend, stamps, n_rungs=8): + """Write index + calibration files the way data._save_calibration does.""" + from iqmapper import data as _data + + old = _data._CACHE_DIR + _data._CACHE_DIR = str(tmp_path) + try: + # _load_calibration deletes any snapshot missing a key from the + # canonical option lists, so write the full set, not just the two the + # engines read. + from iqmapper.constants import GATE_PROP_OPTIONS, QUBIT_PROP_OPTIONS + + edges = _ladder_edges(n_rungs) + n_q = 3 * n_rungs + for i, stamp in enumerate(stamps): + rng = np.random.default_rng(i) + qubit_props = {pk: np.full(n_q, 0.001) + for _label, pk in QUBIT_PROP_OPTIONS} + qubit_props['readout_error'] = 0.01 + 0.01 * rng.random(n_q) + gate_props = {pk: np.full(len(edges), 0.001) + for _label, pk in GATE_PROP_OPTIONS} + gate_props['cz_error'] = 0.005 + 0.01 * rng.random(len(edges)) + _data._save_calibration(backend, stamp, qubit_props, gate_props) + return edges + finally: + _data._CACHE_DIR = old + + +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 ────────────────────────────────────────────────── + +def test_compare_engines_returns_rows_for_each_date_and_norb(tmp_path): + backend = 'ibm_fixture' + stamps = ['2026-09-01T00:00:00Z', '2026-09-02T00:00:00Z'] + edges = _write_cache(tmp_path, backend, stamps) + + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, coupling=edges, + beam_width=50) + + assert not report.errors, report.errors + assert report.rows, 'no comparison rows produced' + assert {r.date for r in report.rows} == set(stamps) + assert {r.norb for r in report.rows} == {4} + for row in report.rows: + assert row.vf2_lqs is not None and row.guided_lqs is not None + assert row.delta is not None + assert row.vf2_time >= 0 and row.guided_time >= 0 + assert row.vf2_scaffolds > 0 and row.guided_scaffolds > 0 + + +def test_report_renders_markdown_with_a_summary(tmp_path): + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, coupling=edges, + beam_width=50) + + text = report.to_markdown() + assert text.startswith('# Engine comparison - ibm_fixture') + assert 'guided >= VF2 in' in text + assert '| date | norb | k |' in text + assert text.count('\n|') >= 2 + len(report.rows) + + +def test_missing_coupling_is_reported_not_guessed(tmp_path): + """The cache has no topology; inventing one would produce fake numbers.""" + backend = 'ibm_fixture' + _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z']) + + report = ev.compare_engines(backend, norbs=(4,), cache_dir=tmp_path, + session_dir=str(tmp_path / 'no_sessions')) + assert report.rows == [] + assert report.errors and 'No coupling map' in report.errors[0] + assert 'coupling=' in report.errors[0], 'the error must say how to fix it' + + +def test_coupling_is_recovered_from_a_saved_session(tmp_path): + 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) + + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, + session_dir=str(session_dir), beam_width=50) + assert not report.errors, report.errors + assert report.rows + + +def test_coupling_from_sessions_ignores_other_backends(tmp_path): + session_dir = tmp_path / 'sessions' + _write_session(str(session_dir), 'someone_else', [(0, 1)], 2) + assert ev.coupling_from_sessions('ibm_fixture', + str(session_dir)) is None + assert ev.coupling_from_sessions('someone_else', + str(session_dir)) == [(0, 1)] + + +def test_engine_failures_are_recorded_not_raised(tmp_path): + """A norb too large for the device must be a row-less error, not a crash.""" + backend = 'ibm_fixture' + edges = _write_cache(tmp_path, backend, ['2026-09-01T00:00:00Z'], + n_rungs=4) + report = ev.compare_engines(backend, norbs=(64,), cache_dir=tmp_path, + coupling=edges, min_bridges=1) + assert report.rows == [] + assert report.errors + assert any('norb=64' in e for e in report.errors) + + +def test_limit_caps_the_number_of_calibrations(tmp_path): + backend = 'ibm_fixture' + stamps = [f'2026-09-0{i}T00:00:00Z' for i in range(1, 5)] + edges = _write_cache(tmp_path, backend, stamps) + report = ev.compare_engines(backend, norbs=(4,), top_n=2, min_bridges=1, + cache_dir=tmp_path, coupling=edges, + beam_width=50, limit=2) + assert len({r.date for r in report.rows}) <= 2 + + +def test_summary_handles_an_empty_report(): + report = ev.Report('nothing', []) + assert report.summary() == 'No comparable cases.' + assert 'nothing' in report.to_markdown() + + +def test_cached_props_reads_arrays_and_penalises_gaps(): + props = ev._CachedProps( + {'readout_error': [0.01, 0.02]}, + {'cz_error': [0.03]}, + [(0, 1)]) + assert props.readout_error(0) == pytest.approx(0.01) + assert props.gate_error('cz', (1, 0)) == pytest.approx(0.03), \ + 'edge lookup must be direction-agnostic' + assert np.isnan(props.readout_error(99)) + assert np.isnan(props.gate_error('cz', (0, 99))) + + +def test_cli_runs_and_writes_a_report(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) + out_dir = tmp_path / 'out' + + 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-dir', str(session_dir), + '--out-dir', str(out_dir)]) + + assert code == 0 + printed = capsys.readouterr().out + assert '# Engine comparison' in printed + 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 + + +# ── 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 diff --git a/tests/test_export_layout_io.py b/tests/test_export_layout_io.py index 33ad6d1..964eedd 100644 --- a/tests/test_export_layout_io.py +++ b/tests/test_export_layout_io.py @@ -59,14 +59,14 @@ 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. 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_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 new file mode 100644 index 0000000..f63ff5b --- /dev/null +++ b/tests/test_floor_batch_ui.py @@ -0,0 +1,342 @@ +"""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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + 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" + 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() + 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 + 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("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() + 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("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 + 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("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("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 + 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 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}]) + # 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("iqmapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: props[backend.name])) + seen = {} + 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()) + assert not (seen['ibm_b'].get('exclude_qubits') or set()) + + +# ── the single-count search is untouched by the floor ──────────────── + +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)) + b.lucj_ancilla_dd.value = 2 # exact count (not sweep) + b.btn_lucj_run.click() + assert len(single) == 1 + # The single-count engine takes no floor exclude set. + assert 'exclude_qubits' not in single[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 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': [ + _batch_result_row('ibm_hi', 0.61, 2), + _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() + + # 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(' metrics['ibm_b'] 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 new file mode 100644 index 0000000..775f6c3 --- /dev/null +++ b/tests/test_guided_search.py @@ -0,0 +1,452 @@ +"""Tests for the calibration-guided beam search. + +The engine is a heuristic, so the tests are about the things that must hold +regardless: every layout is a valid embedding of the LUCJ template, the scores +agree with the frozen engine to the last bit, the search is deterministic, and +the output dict is indistinguishable from `sweep_ancilla_layouts`'s apart from +the additive keys. +""" +import math +from types import SimpleNamespace + +import pytest +import rustworkx + +from iqmapper import guided_search as gs +from iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.guided_search import guided_sweep + +from test_ancilla_sweep import FakeProps, make_backend + + +# ── helpers ───────────────────────────────────────────────────────── + +def _adjacency(backend): + from iqmapper.auto_lucj import _make_backend_cmap_pygraph + graph = _make_backend_cmap_pygraph(backend=backend) + return {q: frozenset(graph.neighbors(q)) for q in graph.node_indices()} + + +def _engine_for(backend, props, norb): + """A `_GuidedEngine` wired to a backend the way `guided_sweep` wires it.""" + import numpy as np + from iqmapper.ancilla_sweep import (_UNCALIBRATED_PENALTY, + _safe_gate_error, _safe_readout) + from iqmapper.auto_lucj import (_get_two_q_gate_name, + _make_backend_cmap_pygraph) + graph = _make_backend_cmap_pygraph(backend=backend) + gate_name = _get_two_q_gate_name(backend) + nodes = list(graph.node_indices()) + readout = np.full(max(nodes) + 1, _UNCALIBRATED_PENALTY, dtype=float) + for q in nodes: + readout[q] = _safe_readout(props, q) + edge_err = {frozenset((u, v)): _safe_gate_error(props, gate_name, u, v) + for u, v in graph.edge_list()} + engine = gs._GuidedEngine(norb, graph, readout, edge_err) + return engine, norb + + +def _all_entries(result): + for k in sorted(result['strata'], reverse=True): + for entry in result['strata'][k]: + yield k, entry + + +def _entry_layout(entry): + return list(entry['layout']) + list(entry['ancillas']) + + +# ── 1. validity ───────────────────────────────────────────────────── + +def test_every_produced_layout_is_a_valid_template_embedding(): + """Injective, and every template edge lands on a coupling edge.""" + backend, props = make_backend(), FakeProps() + adjacency = _adjacency(backend) + for norb in (4, 6, 8): + res = guided_sweep(norb, backend, props, min_bridges=1, top_n=3, + circuit_score_fn=lambda e: e['product_score']) + assert res['strata'], f'no strata for norb={norb}' + for k, entry in _all_entries(res): + layout = _entry_layout(entry) + assert gs.validate_layout(layout, norb, k, adjacency), ( + f'invalid embedding at norb={norb} k={k}: {layout}') + assert entry['bridge_slots'] == gs.bridge_slots_for(k), ( + 'prefix contract violated: bridge_slots must be ' + '(0, 4, ..., 4*(k-1))') + + +def test_guided_layouts_are_contained_in_the_vf2_enumeration(): + """On a fixture VF2 can fully enumerate, guided finds nothing exotic. + + VF2 must be given a top_n large enough that its slice is not binding: + at norb=4 its k=1 pool holds ~564 layouts, so a top_n of 50 would compare + guided's picks against VF2's shortlist rather than its enumeration. + """ + backend, props = make_backend(), FakeProps() + norb = 4 + vf2 = sweep_ancilla_layouts(norb, backend, props, min_bridges=1, + top_n=5000) + guided = guided_sweep(norb, backend, props, min_bridges=1, top_n=50) + + for k in guided['strata']: + vf2_keys = {(frozenset(e['layout']), frozenset(e['ancillas'])) + for e in vf2['strata'].get(k, [])} + for entry in guided['strata'][k]: + key = (frozenset(entry['layout']), frozenset(entry['ancillas'])) + assert key in vf2_keys, ( + f'guided produced a k={k} layout VF2 never enumerated: {key}') + + +def test_validate_layout_rejects_the_obvious_breakages(): + adjacency = {0: frozenset({1}), 1: frozenset({0, 2}), 2: frozenset({1})} + assert gs.validate_layout([0, 1, 2], 1, 0, adjacency) is False # wrong len + # duplicate qubit -> not injective + assert gs.validate_layout([0, 1, 0, 1], 2, 0, adjacency) is False + # None slot + assert gs.validate_layout([0, 1, None, 2], 2, 0, adjacency) is False + + +def test_template_edges_match_the_frozen_construction(): + """Chain paths plus two edges per bridge, bridges at slots 0, 4, 8...""" + edges = gs.template_edges(norb=8, k=2) + for j in range(7): + assert (j, j + 1) in edges + assert (8 + j, 8 + j + 1) in edges + assert (0, 16) in edges and (16, 8) in edges # bridge 0 at slot 0 + assert (4, 17) in edges and (17, 12) in edges # bridge 1 at slot 4 + assert gs.max_bridges_for(8) == 2 + assert gs.max_bridges_for(9) == 3 + assert gs.bridge_slots_for(3) == (0, 4, 8) + + +# ── 2. score parity with the frozen engine ────────────────────────── + +def test_score_parity_with_the_frozen_sweep(): + """A layout both engines found must carry identical scores.""" + backend, props = make_backend(), FakeProps() + norb = 6 + vf2 = sweep_ancilla_layouts(norb, backend, props, min_bridges=1, top_n=50) + guided = guided_sweep(norb, backend, props, min_bridges=1, top_n=50) + + compared = 0 + for k in guided['strata']: + vf2_by_key = {(frozenset(e['layout']), frozenset(e['ancillas'])): e + for e in vf2['strata'].get(k, [])} + for entry in guided['strata'][k]: + key = (frozenset(entry['layout']), frozenset(entry['ancillas'])) + twin = vf2_by_key.get(key) + if twin is None: + continue + compared += 1 + assert entry['product_score'] == pytest.approx( + twin['product_score'], abs=1e-12), (k, key) + assert entry['additive_score'] == pytest.approx( + twin['additive_score'], abs=1e-12), (k, key) + assert compared > 0, 'no shared layouts to compare' + + +# ── 3. determinism and beam monotonicity ──────────────────────────── + +def test_same_inputs_give_an_identical_result(): + backend, props = make_backend(), FakeProps() + a = guided_sweep(6, backend, props, min_bridges=1, top_n=3, seed=0) + b = guided_sweep(6, backend, props, min_bridges=1, top_n=3, seed=0) + for k in a['strata']: + assert [e['layout'] for e in a['strata'][k]] == \ + [e['layout'] for e in b['strata'][k]] + assert [e['product_score'] for e in a['strata'][k]] == \ + [e['product_score'] for e in b['strata'][k]] + + +def test_a_wider_beam_finds_a_superset_of_completed_layouts(): + """Widening the beam must not lose a completed layout. + + Asserted on the beam itself rather than on `strata`: the strata are a + top_n slice, so a wider beam can legitimately push a narrow run's pick off + the shortlist by finding better ones. The monotonicity that matters is + that the wider search still REACHED it. + """ + backend, props = make_backend(), FakeProps() + engine, norb = _engine_for(backend, props, norb=6) + k = 2 + + 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)} + + assert narrow, 'the narrow beam completed nothing' + assert narrow <= wide, ( + f'widening the beam dropped {len(narrow - wide)} completed layout(s)') + assert len(wide) > len(narrow), 'a wider beam should reach more layouts' + + +def test_a_too_narrow_beam_dead_ends_loudly(): + """Beam search is incomplete: a narrow beam can finish with nothing. + + On the fixture at norb=6, k=2 the beam completes nothing below width ~40 — + every state it kept ran out of legal extensions. `guided_sweep` must raise + rather than return an empty result that looks like 'no layout exists on + this device', because the two mean very different things to a user. + """ + backend, props = make_backend(), FakeProps() + engine, _norb = _engine_for(backend, props, norb=6) + assert engine.run_beam(2, 5) == [], 'fixture assumption changed' + + with pytest.raises(RuntimeError, match='no complete zigzag embedding'): + guided_sweep(6, backend, props, min_bridges=2, top_n=3, beam_width=5) + + +# ── 4. the fixture optimum ────────────────────────────────────────── + +def test_guided_finds_the_same_optimum_as_vf2_at_every_k(): + """The fixture has a GOOD and a BAD block; guided must pick GOOD. + + On this fixture VF2 enumerates exhaustively, so its best IS the optimum — + which makes this a real check on the heuristic, not a tautology. + """ + backend, props = make_backend(), FakeProps() + for norb in (4, 6, 8): + vf2 = sweep_ancilla_layouts(norb, backend, props, min_bridges=1, + top_n=3) + guided = guided_sweep(norb, backend, props, min_bridges=1, top_n=3) + assert set(guided['strata']) == set(vf2['strata']) + for k in vf2['strata']: + best_vf2 = vf2['strata'][k][0]['product_score'] + best_guided = guided['strata'][k][0]['product_score'] + assert best_guided == pytest.approx(best_vf2, abs=1e-12), ( + f'norb={norb} k={k}: guided {best_guided} vs VF2 {best_vf2}') + + +def test_guided_picks_the_good_block(): + from test_ancilla_sweep import GOOD_QUBITS + backend, props = make_backend(), FakeProps() + guided = guided_sweep(6, backend, props, min_bridges=1, top_n=1) + for k, entry in _all_entries(guided): + used = set(_entry_layout(entry)) + assert used <= set(GOOD_QUBITS), ( + f'k={k} winner strayed into the BAD block: {sorted(used)}') + + +# ── 5. refinement ─────────────────────────────────────────────────── + +def _twin_bridge_backend(): + """A minimal graph with TWO candidate bridges for the same chain pair. + + alpha = 0-1, beta = 2-3, and both 4 and 5 are adjacent to 0 and 2. That + gives the bridge-replacement move a real alternative to find, which the + ladder fixture does not (there the bridge is forced). + """ + graph = rustworkx.PyDiGraph() + for _ in range(6): + graph.add_node(None) + + def _add(u, v): + graph.add_edge(u, v, None) + graph.add_edge(v, u, None) + + _add(0, 1) # alpha chain + _add(2, 3) # beta chain + for bridge in (4, 5): # two interchangeable bridges + _add(0, bridge) + _add(bridge, 2) + return SimpleNamespace(coupling_map=SimpleNamespace(graph=graph), + operation_names=['cz', 'sx', 'rz', 'x']) + + +class _TunableProps: + def __init__(self, readout=None, gate=None, default_r=0.01, + default_e=0.01): + self._r = dict(readout or {}) + self._g = {frozenset(k): v for k, v in (gate or {}).items()} + self._dr, self._dg = default_r, default_e + + def readout_error(self, q): + return self._r.get(int(q), self._dr) + + def gate_error(self, _name, edge): + return self._g.get(frozenset((int(edge[0]), int(edge[1]))), self._dg) + + +def _refine_engine(backend, props, norb): + engine, _ = _engine_for(backend, props, norb) + return engine + + +def test_refinement_takes_a_strictly_better_bridge(): + """Bridge 5 is better than bridge 4; refinement must swap and flag it.""" + backend = _twin_bridge_backend() + props = _TunableProps(readout={4: 0.20, 5: 0.001}) + adjacency = _adjacency(backend) + engine = _refine_engine(backend, props, norb=2) + + entry = gs._entry_from_state(engine, [0, 1], [2, 3], [4], 1) + assert gs.validate_layout(_entry_layout(entry), 2, 1, adjacency) + assert entry['ancillas'] == [4] + + def _score(e): + return float(e['product_score']) # bridge 5 scores higher + + refined, changed = gs.refine_entry(engine, entry, 1, _score) + + assert changed is True, 'refinement ignored a strictly better bridge' + assert refined['ancillas'] == [5], ( + f"expected the good bridge, got {refined['ancillas']}") + assert refined['lqs_circuit'] > entry['product_score'] + assert gs.validate_layout(_entry_layout(refined), 2, 1, adjacency), ( + 'refinement produced an invalid embedding') + + +def test_refinement_leaves_an_already_optimal_entry_alone(): + backend = _twin_bridge_backend() + props = _TunableProps(readout={4: 0.001, 5: 0.20}) + engine = _refine_engine(backend, props, norb=2) + entry = gs._entry_from_state(engine, [0, 1], [2, 3], [4], 1) + + refined, changed = gs.refine_entry(engine, entry, 1, + lambda e: float(e['product_score'])) + assert changed is False, 'refinement moved off the optimum' + assert refined is entry + + +def test_refinement_respects_max_iter(): + """A scorer that always improves must still terminate.""" + backend = _twin_bridge_backend() + props = _TunableProps() + engine = _refine_engine(backend, props, norb=2) + entry = gs._entry_from_state(engine, [0, 1], [2, 3], [4], 1) + + calls = [] + + def _always_better(_e): + calls.append(1) + return 0.1 * len(calls) # strictly increasing forever + + refined, changed = gs.refine_entry(engine, entry, 1, _always_better, + max_iter=3) + assert changed is True + # Bounded: 3 iterations, each scanning a neighbourhood of a handful of + # moves. Without the ceiling this scorer would loop forever. + assert len(calls) <= 3 * 20 + 1, ( + f'max_iter did not bound the search ({len(calls)} scorer calls)') + + +def test_a_raising_scorer_never_breaks_refinement(): + backend = _twin_bridge_backend() + engine = _refine_engine(backend, _TunableProps(), norb=2) + entry = gs._entry_from_state(engine, [0, 1], [2, 3], [4], 1) + + def _boom(_e): + raise RuntimeError('scorer exploded') + + refined, changed = gs.refine_entry(engine, entry, 1, _boom) + assert changed is False and refined is entry + + +# ── 6. no explosion at low k ──────────────────────────────────────── + +def test_low_k_does_not_explode_on_heavy_hex(): + """The failure mode this engine exists to fix, asserted structurally. + + 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). + """ + graph_rx = rustworkx.generators.heavy_hex_graph(7) + directed = rustworkx.PyDiGraph() + for _ in range(graph_rx.num_nodes()): + directed.add_node(None) + for u, v in graph_rx.edge_list(): + directed.add_edge(u, v, None) + directed.add_edge(v, u, None) + backend = SimpleNamespace(coupling_map=SimpleNamespace(graph=directed), + operation_names=['cz', 'sx', 'rz', 'x']) + props = _TunableProps() + + norb, beam_width = 6, 50 + res = guided_sweep(norb, backend, props, min_bridges=1, top_n=3, + beam_width=beam_width) + + max_degree = max(len(graph_rx.neighbors(n)) + for n in graph_rx.node_indices()) + # Per growth step: beam_width states x (deg choices for alpha) x (deg for + # beta). Summed over the norb-1 steps, and over the strata we run. + ceiling = beam_width * norb * (max_degree ** 2) * (res['k_max_effective'] + 1) + assert res['expansions'] <= ceiling, ( + f"expansions {res['expansions']} exceeded the structural bound " + f"{ceiling}") + assert res['vf2_truncated'] is False, 'the beam must never report a cap' + assert res['mapping_cap'] is None + + +# ── 7. output contract ────────────────────────────────────────────── + +def test_result_dict_is_a_superset_of_the_sweep_contract(): + backend, props = make_backend(), FakeProps() + scorer = (lambda e: e['product_score']) + vf2 = sweep_ancilla_layouts(6, backend, props, min_bridges=1, top_n=3, + circuit_score_fn=scorer) + guided = guided_sweep(6, backend, props, min_bridges=1, top_n=3, + circuit_score_fn=scorer) + + # Keys that describe the VF2 ENUMERATION have no guided counterpart: + # the beam is bounded by construction and has no mapping cap to make + # diverse. Everything a downstream consumer reads is still shared. + vf2_only = {'reservoir', 'reservoir_notices'} + assert (set(vf2) - vf2_only) <= set(guided), ( + f'guided is missing sweep keys: {set(vf2) - vf2_only - set(guided)}') + assert guided['engine'] == 'guided' + assert set(guided['strata']) == set(vf2['strata']) + assert set(guided['per_stratum']) == set(vf2['per_stratum']) + for k in vf2['per_stratum']: + assert set(guided['per_stratum'][k]) == set(vf2['per_stratum'][k]) + + for k in vf2['strata']: + if not vf2['strata'][k] or not guided['strata'][k]: + continue + vf2_fields = set(vf2['strata'][k][0]) + for entry in guided['strata'][k]: + missing = vf2_fields - set(entry) + assert not missing, f'k={k}: entry missing {missing}' + + +def test_min_bridges_is_validated_like_the_frozen_engine(): + backend, props = make_backend(), FakeProps() + with pytest.raises(ValueError, match='min_bridges'): + guided_sweep(4, backend, props, min_bridges=99) + + +def test_qubit_weight_hook_shifts_the_ranking(): + """The stability/T1 hook must actually influence what the beam keeps.""" + backend, props = make_backend(), FakeProps() + from test_ancilla_sweep import GOOD_QUBITS + good = set(GOOD_QUBITS) + + plain = guided_sweep(4, backend, props, min_bridges=1, top_n=1) + # Punish the GOOD block hard; the winner should leave it. + penalised = guided_sweep( + 4, backend, props, min_bridges=1, top_n=1, + qubit_weight=lambda q: 0.01 if q in good else 1.0) + + plain_used = set(_entry_layout(plain['strata'][1][0])) + pen_used = set(_entry_layout(penalised['strata'][1][0])) + assert plain_used <= good + assert not pen_used <= good, 'qubit_weight did not affect the search' + + +def test_excluded_qubits_never_appear(): + backend, props = make_backend(), FakeProps() + excluded = {0, 1, 2, 3} + res = guided_sweep(6, backend, props, min_bridges=1, top_n=3, + exclude_qubits=excluded) + assert res['excluded_qubits'] == sorted(excluded) + for _k, entry in _all_entries(res): + assert not (set(_entry_layout(entry)) & excluded) + + +def test_log_floor_keeps_a_dead_element_comparable(): + """log(0) must not poison a partial state into -inf.""" + assert gs._safe_log(0.0) == gs._LOG_FLOOR + assert gs._safe_log(-1.0) == gs._LOG_FLOOR + assert gs._safe_log(1.0) == pytest.approx(0.0) + assert gs._safe_log(0.5) == pytest.approx(math.log(0.5)) 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("', '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 new file mode 100644 index 0000000..0105c3e --- /dev/null +++ b/tests/test_scan_ui.py @@ -0,0 +1,464 @@ +"""Headless tests for the multi-QPU scan UI. + +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 + + + +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, + 'per_stratum': {2: {'n_direct': 1, 'n_derived': 0, 'truncated': False}, + 1: {'n_direct': 1, 'n_derived': 1, 'truncated': False}}} + + +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(): + 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 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("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 one of _targets → no ref row + state.active_chip = "stub_chip" + 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() + 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, sweeps=None, props=None, targets=None): + """Drive _scan_backends: canned per-target sweep + stub props factory.""" + 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), + '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): + from ipywidgets import Dropdown + 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): + b = _build(monkeypatch, marshal=lambda cb: cb()) + _patch_scan(monkeypatch) + b.btn_scan_qpus.click() + + children = b.scan_results_box.children + # 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 + + +# ── 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) + + b.btn_scan_qpus.click() + 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 + + +# ── 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, sweeps={ + 'ibm_b': _sweep(0.60, 0.50), 'ibm_a': _sweep(0.40, 0.30), + 'ibm_c': RuntimeError('boom ')}) + b.btn_scan_qpus.click() + + # 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 ──────────────────────── + +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, 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. + 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] # the QPU's best (k=2) candidate + + +# ── sweep mode greys the score checkbox ──────────────────────────────── + +def test_m1_score_checkbox_toggle(monkeypatch): + b = _build(monkeypatch) + assert b.lucj_ancilla_dd.value == -1 + assert b.lucj_chk_score.disabled is True + b.lucj_ancilla_dd.value = 2 + assert b.lucj_chk_score.disabled is False + b.lucj_ancilla_dd.value = -1 + assert b.lucj_chk_score.disabled is True + + +# ── circuit-LQS annotation (success → number, failure → template) ─────── + +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 not any('(template)' in lbl for lbl in _labels(b)) + + +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 any('(template)' in lbl for lbl in _labels(b)) + + +# ── 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() + 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 ────────────── + +def test_scan_fetch_failure_error_row(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)) + + 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("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 + assert 'live · 09:30' in _detail_by_name(b, 'ibm_b') # ibm_b completed + + +# ── stability filter still reads the cache for HISTORY ──────────────── + +def test_stability_history_reads_cache(monkeypatch): + 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 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("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("iqmapper.stability_filter.sweep_with_stability", + lambda *a, **k: {**_sweep(0.6, 0.5), 'stability': {'available': True}}) + monkeypatch.setattr("iqmapper.props_shim.make_scan_get_props", + lambda state: (lambda backend: _StubProps(0.6, 'live · 09:30'))) + + b.btn_scan_qpus.click() + assert loads # cache loader used for HISTORY + + +# ── 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()) + calls = [] + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", + lambda *a, **k: _targets()) + 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 + 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 = False # non-default diversity + + 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', '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 + # 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'] is None + and scan_kw['diversity_threshold'] is None) + + +# ── 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( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: swept.append(bk.name) or _sweep(0.6, 0.5)) + 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("iqmapper.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 + # The active backend is never re-swept and is not listed as a row. + assert 'stub' not in [lbl.split(' —')[0] for lbl in _labels(b)] # not a row + + +# ── scan honors the hybrid checkbox ───────────────────────────────────── + +def test_scan_honors_hybrid_checkbox(monkeypatch): + b = _build(monkeypatch, marshal=lambda cb: cb()) + calls = [] + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda norb, bk, pr, **kw: calls.append(kw) or _sweep(0.6, 0.5)) + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", + lambda *a, **k: _targets()) + monkeypatch.setattr("iqmapper.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(w.value for w in _walk(b.scan_results_box) + if isinstance(w, HTML)) + + +def _patch_one_target(monkeypatch, sweep, props_obj): + monkeypatch.setattr("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': 'ibm_a', 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: sweep) + monkeypatch.setattr("iqmapper.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() + 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): + 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() + # 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): + 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() + 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..fc1c2e0 --- /dev/null +++ b/tests/test_scan_ui_pass.py @@ -0,0 +1,238 @@ +"""Scan results: the selector label and the detail quote one metric (max +lqs_circuit, never max product_score), no comparison table, loud notices +header. +""" +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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr(au, 'marshal_to_main', marshal) + 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 + 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("iqmapper.qpu_scan.list_scan_targets", lambda *a, **k: [ + {'name': name, 'family': 'Heron', 'eligible': True, 'reason': None}]) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: sweep) + monkeypatch.setattr("iqmapper.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 + + +# ── 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' + + +# ── 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 + + +# ── 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) + + +# ── 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, report=None: + 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] + + +# ── 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_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' + diff --git a/tests/test_scoring_core.py b/tests/test_scoring_core.py new file mode 100644 index 0000000..7bc0b69 --- /dev/null +++ b/tests/test_scoring_core.py @@ -0,0 +1,86 @@ +"""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 iqmapper.export.scoring import ( + estimate_circuit_fidelity, estimate_fidelity_core, +) +from iqmapper.props_shim import CachedPropsShim + + +# ── pinned values on a fixed four-qubit chain ─────────────────────────── + +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 + + +# ── 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 + + +# ── 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_search_ui.py b/tests/test_search_ui.py new file mode 100644 index 0000000..2ae8255 --- /dev/null +++ b/tests/test_search_ui.py @@ -0,0 +1,164 @@ +"""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 'Reference: 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_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) + 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_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 '✅ 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 ────────────────────────────────────────────────────────── + +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_shuffle_search.py b/tests/test_shuffle_search.py new file mode 100644 index 0000000..89b9d67 --- /dev/null +++ b/tests/test_shuffle_search.py @@ -0,0 +1,147 @@ +"""Shuffled VF2 search order kills the geographic-prefix truncation bias. + +These tests pin ``diverse_cap=False`` so they exercise the SHUFFLE alone. +The diverse reservoir attacks the same bias by a different route and, when +enabled, frees the natural order from block A on its own — see +iqmapper/reservoir.py and tests/test_reservoir.py. + +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 iqmapper.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, + # Isolate the mechanism under test. The + # diverse reservoir (engine #17) also breaks + # the geographic-prefix bias — it keeps + # offering past the cap and swaps block-A + # near-duplicates for block-B candidates — + # so with it ON the "natural order is + # trapped" premise no longer holds. That is + # the reservoir working, not the shuffle + # failing. + diverse_cap=False) + + +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']) + + +# ── 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 + + +# ── 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) + + +# ── 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] + + +# ── 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_stability.py b/tests/test_stability.py index fe35d11..16f7201 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -1,6 +1,6 @@ """Unit tests for iqmapper.stability.analyze_property_stability. -The seven cases covered: +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_stability_filter.py b/tests/test_stability_filter.py new file mode 100644 index 0000000..44f9f96 --- /dev/null +++ b/tests/test_stability_filter.py @@ -0,0 +1,266 @@ +"""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 = +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 iqmapper.ancilla_sweep import sweep_ancilla_layouts +from iqmapper.stability_filter import ( + compute_qubit_volatility, select_excluded, select_quality_floor, + 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 + + +# ── 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 + + +# ── 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 + + +# ── filtered sweep never uses excluded qubits (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) + + +# ── 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'])) + + +# ── 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'] + + +# ── 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()) + + +# ── 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']) + + +# ── 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 new file mode 100644 index 0000000..579eb13 --- /dev/null +++ b/tests/test_stability_ui.py @@ -0,0 +1,281 @@ +"""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 + + +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 _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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', spawn) + monkeypatch.setattr(au, 'marshal_to_main', marshal) + 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" + 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 = [] + 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 + + +# ── 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 + + +# ── 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("iqmapper.stability_filter.sweep_with_stability", fake_sws) + plain = [] + monkeypatch.setattr("iqmapper.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 + + +# ── the three banner states ───────────────────────────────────────────── + +def test_banner_states(monkeypatch): + b = _build(monkeypatch, history=True) + holder = {} + monkeypatch.setattr("iqmapper.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 + + +# ── scan rows carry stability badges ──────────────────────────────────── + +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 + + 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 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: + ({'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("iqmapper.stability_filter.sweep_with_stability", + lambda *a, **k: filt) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned_res(None)) + monkeypatch.setattr("iqmapper.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() + 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 ─────────────────────────────── + +def test_filter_off_uses_plain_sweep(monkeypatch): + b = _build(monkeypatch, history=True) + + plain = [] + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: plain.append(1) or _canned_res(None)) + sws = [] + 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 + b.btn_lucj_run.click() + assert plain == [1] # plain sweep used + assert sws == [] # filter engine untouched + assert b.lbl_lucj_stability.value == "" # no banner + + +# ── banner counts N volatile + M outlier from the metadata ────────────── + +def test_banner_counts_volatile_and_outlier(monkeypatch): + b = _build(monkeypatch, history=True) + monkeypatch.setattr( + "iqmapper.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( + "iqmapper.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 + + +# ── _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("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 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 []) + + 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("iqmapper.stability_filter.sweep_with_stability", + lambda *a, **k: filt) + monkeypatch.setattr("iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _canned_res(None)) + monkeypatch.setattr("iqmapper.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() + # (a) isolation: ibm_c's raise became an error row, loop not killed. + assert 'cache read exploded' in _detail_by_name(b, 'ibm_c') + # (b) both badge paths: cached → filtered, 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 diff --git a/tests/test_subpanel_persistence.py b/tests/test_subpanel_persistence.py new file mode 100644 index 0000000..6815494 --- /dev/null +++ b/tests/test_subpanel_persistence.py @@ -0,0 +1,239 @@ +"""SUBPANEL SELECTION MUST SURVIVE REBUILDS. + +Every structural refresh rebuilds a nav view from scratch, minting a fresh Tab +whose selected_index defaults to 0. Generate Multi-Circuit must not bounce the +user from the Multi subpanel back to Single mid-operation. These tests pin that +the Auto / I/O / Error subtabs keep their selection across rebuilds. +""" + +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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + 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" + 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() + b.chk_fast_multi.value = True # the stubbed engine is the sequential one + return b, state + + +# ── the user's exact sequence — Generate Multi stays on Multi ─────────────── + +def test_multi_generate_keeps_multi_subpanel(monkeypatch): + b, state = _build(monkeypatch) + 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 + 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 'circuits 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 + + +# ── 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 + + +# ── 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 # Export subpanel (index 1) + b._update_view() # a refresh while on I/O + 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): + 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 + + +# ── the Tab widget instance is UNCHANGED after Generate (no rebuild) ───────── + +def test_multi_generate_no_rebuild(monkeypatch): + b, state = _build(monkeypatch) + 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] + + 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 'circuits placed' in b.lbl_lucj_multi.value # results rendered + + +# ── the targeted widgets ARE refreshed (no rebuild ≠ no update) ────────────── + +def test_multi_generate_targeted_widgets_refreshed(monkeypatch): + b, state = _build(monkeypatch) + import iqmapper.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 [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] + assert 'Add Ancilla C1' in anc_labels and 'Add Ancilla C2' in anc_labels + assert len(b.manual_tabs.children) == 2 + + +# ── a checkbox toggle STILL rebuilds legitimately ──────────────────────────── + +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 + diff --git a/tests/test_sweep_notices.py b/tests/test_sweep_notices.py new file mode 100644 index 0000000..aa0d1c0 --- /dev/null +++ b/tests/test_sweep_notices.py @@ -0,0 +1,216 @@ +"""NOTICE CAPTURE FOR ALL SWEEP PATHS. + +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 +restored in finally — proven on the error path). +""" +import logging +from types import SimpleNamespace + +import numpy as np + +_QLOG = 'iqmapper' + + +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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + 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" + 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() + 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 + + +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 iqmapper.ui.lucj_panel import _ScanNoticeCapture + return [h for h in logging.getLogger(_QLOG).handlers + if isinstance(h, _ScanNoticeCapture)] + + +# ── 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("iqmapper.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) + + +# ── 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("iqmapper.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 + + +# ── the scan path is covered in test_scan_notices.py ──────────────────────── + + +# ── 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("iqmapper.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("iqmapper.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("circuit 2 search truncated") + lg.warning("circuit 2 search truncated") + return _multi_result() + monkeypatch.setattr("iqmapper.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 'circuit 2 search truncated ×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 new file mode 100644 index 0000000..da20209 --- /dev/null +++ b/tests/test_sweep_ui.py @@ -0,0 +1,323 @@ +"""Headless tests for the Auto-tab ancilla-sweep UI wiring (Component 1b+2). + +Builds the real MapperUIBuilder with the data layer stubbed (deterministic +8-qubit line device, offline) and monkeypatches the engine entry points so +NO real VF2 runs in the UI tests. Exercises: sweep-mode dropdown population + +label format, legacy-mode routing, apply-on-select (chains + kept ancillas), +the truncation banner, and engine-ValueError surfacing. +""" +import numpy as np +import pytest + + +def _fake_device_data(state, vendor, chip, date, prefetched_props=None): + """Deterministic 8-qubit line device (enough qubits for a k=3 candidate).""" + n = 8 + x = list(range(n)) + y = [0.0] * n + edges = [(i, i + 1) for i in range(n - 1)] + qids = [str(i) for i in range(n)] + readout = np.array([0.01 * (i + 1) for i in range(n)]) + gate = np.array([0.001 * (i + 1) for i in range(len(edges))]) + return x, y, edges, qids, readout, gate + + +@pytest.fixture +def builder(monkeypatch): + 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 + 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() # opaque; engine is monkeypatched + state.active_ansatz = "lucj" + state.active_vendor = "IBM" + state.active_coords = [] + state.custom_colors = [] + state.cal_history_dates = ["_seed_"] # skip the bg auto-load thread + + b = MapperUIBuilder(state) + b.build() + b.chk_guided_search.value = False # stubbed exhaustive engine only + return b + + +def _labels(dd): + return [opt[0] if isinstance(opt, tuple) else opt for opt in dd.options] + + +def _fake_sweep_result(vf2_truncated=False): + """Crafted stratified result: k_max=3, strata 3/2/1, one entry each. + product_score chosen so LQS renders as 20.0 / 30.0 / 40.0%.""" + def entry(anc, prod, add, src): + 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': add, + # 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 { + 'strata': { + 3: [entry([4, 5, 6], 0.20, 1.0, 'vf2')], + 2: [entry([4, 5], 0.30, 0.8, 'derived')], + 1: [entry([4], 0.40, 0.5, 'derived')], + }, + 'k_max_effective': 3, 'min_bridges': 1, + 'vf2_truncated': vf2_truncated, + 'n_raw_embeddings': 214, 'n_candidates_scored': 1891, + # 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, + } + + +# ── label/status formatters prefer circuit-level LQS ───────────────── + +def test_formatters_use_lqs_circuit(): + 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) + 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%' + + +# ── sweep mode default → stratified dropdown, exact label format ──────── + +def test_sweep_mode_populates_stratified_dropdown(builder, monkeypatch): + calls = [] + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: (calls.append((a, k)) or _fake_sweep_result())) + + b = builder + assert b.lucj_ancilla_dd.value == -1 # 'Auto' is the default + b.btn_lucj_run.click() + + assert len(calls) == 1 # sweep path taken + assert _labels(b.dd_lucj_layout) == [ + "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] + + +# ── 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, + } + + +# ── 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("iqmapper.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("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. + 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("iqmapper.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 + + +# ── legacy mode → single-search path, sweep NOT called ────────────────── + +def test_legacy_mode_skips_sweep(builder, monkeypatch): + sweep_calls, legacy_calls = [], [] + monkeypatch.setattr( + "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( + "iqmapper.auto_lucj.get_all_zigzag_layouts", fake_legacy) + + b = builder + b.lucj_ancilla_dd.value = 2 # exact count → legacy + b.btn_lucj_run.click() + + assert sweep_calls == [] # sweep NOT called + assert len(legacy_calls) == 1 # legacy called + # requested_bridges passed through as the exact count. + assert legacy_calls[0][1]['requested_bridges'] == 2 + + +# ── apply a k=2 derived entry → chains + its 2 ancillas placed ────────── + +def test_apply_derived_candidate_places_chains_and_ancillas(builder, monkeypatch): + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _fake_sweep_result()) + + b = builder + b.btn_lucj_run.click() # applies flat[0] (k=3) + + # Select the k=2 derived entry (flat index 1). + b.dd_lucj_layout.value = 1 + + d = b.state.layouts_data[0] + assert d['alpha'] == ['0', '1'] + assert d['beta'] == ['2', '3'] + assert d['ancilla'] == ['4', '5'] # exactly its 2 kept bridges + # Consistent role lengths (the metadata downstream derives from). + assert (len(d['alpha']), len(d['beta']), len(d['ancilla'])) == (2, 2, 2) + assert d['other'] == [] and d['qubits'] == [] + # Every placed qubit is styled. + for q in ['0', '1', '2', '3', '4', '5']: + assert q in d['styles'] + + +# ── truncation banner visibility ──────────────────────────────────────── + +def test_truncation_banner(builder, monkeypatch): + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", + lambda *a, **k: _fake_sweep_result(vf2_truncated=True)) + b = builder + b.btn_lucj_run.click() + # 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). + monkeypatch.setattr( + "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 == "" + + +# ── engine ValueError surfaces as a friendly status, no traceback ─────── + +def test_min_bridges_validation_surfaces_as_status(builder, monkeypatch): + def boom(*a, **k): + raise ValueError("min_bridges=99 out of range; must satisfy " + "1 <= min_bridges <= k_max_effective (3).") + monkeypatch.setattr( + "iqmapper.ancilla_sweep.sweep_ancilla_layouts", boom) + + b = builder + b.lucj_min_ancilla.value = 99 + b.btn_lucj_run.click() # must NOT raise + + assert "Error" in b.lbl_lucj_status.value + 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 + + +# ── the deep-search checkbox wires hybrid= ─────────────────────────────── + +def test_deep_search_checkbox_wires_hybrid(builder, monkeypatch): + calls = [] + monkeypatch.setattr( + "iqmapper.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 + + +# ── a region-diversity pick carries no "alt region" suffix ────────────── + +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], + '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("iqmapper.ancilla_sweep.sweep_ancilla_layouts", _fake) + b = builder + b.btn_lucj_run.click() + labels = _labels(b.dd_lucj_layout) + 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_temporal_anchoring.py b/tests/test_temporal_anchoring.py new file mode 100644 index 0000000..cc7bbaa --- /dev/null +++ b/tests/test_temporal_anchoring.py @@ -0,0 +1,224 @@ +"""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 + 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 iqmapper.stability_filter import ( + compute_qubit_volatility, sweep_with_stability, +) + + +# ── 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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + 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" + 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 + + +# ── 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( + "iqmapper.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] + + +# ── 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 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("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("iqmapper.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 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("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("iqmapper.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 diff --git a/tests/test_time_status.py b/tests/test_time_status.py index 6779978..b843b5b 100644 --- a/tests/test_time_status.py +++ b/tests/test_time_status.py @@ -13,9 +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 reader under test is ``describe_current_view``; earlier notes called it -``describe_current_time`` (same signature, same branches). """ from types import SimpleNamespace diff --git a/tests/test_ui_cleanup.py b/tests/test_ui_cleanup.py new file mode 100644 index 0000000..45bea14 --- /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 + + +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 iqmapper.async_util as au + monkeypatch.setattr(au, 'default_spawn_bg', _sync_spawn) + monkeypatch.setattr(au, 'marshal_to_main', lambda cb: cb()) + 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" + 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() + b.chk_guided_search.value = False # stubbed exhaustive engine only + return b + + +# ── local block renders ABOVE the scan block ──────────────────────────── + +def test_local_block_above_scan(monkeypatch): + b = _build(monkeypatch) + 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) + 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) + + +# ── clear resets everything and re-arms the button ────────────────────── + +def test_clear_scan_results(monkeypatch): + b = _build(monkeypatch) + 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(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 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(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 + + +# ── 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(): + 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], + spawn_bg=_sync_spawn, # deterministic one-click auto-connect + ) + return ctx, state + + +def test_staged_banner_then_cleared_on_connect(): + from iqmapper.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 + + +# ── label disambiguation in the detail + dropdown ─────────────────────── + +def test_label_disambiguation(monkeypatch): + b = _build(monkeypatch) + 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() + + # 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