analitics

Pages

Saturday, December 5, 2026

News : JetBrains Subscription Prices Will Increase on February 1, 2027

On February 1, 2027, subscription prices for our IDEs and .NET tools, dotUltimate, and the All Products Pack will increase. Here is some information about what is changing, why, and how you can keep your current price for longer.
Why we’re raising prices
Our costs keep going up. The rising cost of running our business, including expenses associated with the infrastructure and services our products depend on, along with inflation, makes our current prices hard to sustain. The increase also helps us continue to invest in our products – improving performance, building new features, and expanding support for more of the technologies and workflows you use.

Python 3.9.25 : Terminal interface for IBM Quantum hardware on Oracle ARM64.

What it does:
1. Connects to IBM Quantum Platform using API Key + CRN (stored in ibm_quantum_config.json, chmod 600)
2. Fetches live calibration data from all operational QPUs:
  • Single-qubit: SX gate error, readout error, T1/T2, frequency, anharmonicity
  • Two-qubit: CZ gate error per qubit pair (your screenshot: q131-q138: 0.2256%, etc.)
  • Computes a score = weighted sum of median errors + queue depth
3. Displays in 5 panels:
  • Top-left: Backend table (11 metrics × all backends)
  • Top-center: Circuit parameters (qubits, layers, optimization level, shots)
  • Top-right: Live activity log
  • Bottom-left (65% height): Full backend detail — medians, what each metric measures, sample counts, value ranges, per-pair CZ errors
  • Bottom-right (65% height): Extended log / job output
4. Actions (status bar buttons + keys):
  • Refresh QPU / r — reload calibration
  • Pick Best / b — auto-select lowest-score backend
  • Transpile / p — build complex circuit (H + RY/RZ layers + CX ring), transpile to ISA at optimization level 0-3 via generate_preset_pass_manager
  • Run Circuit — submit ISA circuit via SamplerV2 (consumes RUs)
  • Stop Job / s — cancel running job (job.cancel())
5. Logs everything to ibm_quantum_tui.log with timestamps.
Your screenshot shows: 156-qubit backend (ibm_fez?) with CZ errors per coupling pair — median of 2 calibration samples each. This lets you see which qubit links are highest fidelity for circuit mapping.
Let's see the bash script:
#!/bin/bash
# IBM Quantum TUI Project - Initialization Script
# Usage: source init.sh

cd ~/ibm_quantum_tui
source .venv/bin/activate
echo "IBM Quantum TUI environment activated"
echo "Python: $(python --version)"
echo "Qiskit: $(python -c 'import qiskit; print(qiskit.__version__)')"
echo "Textual: $(python -c 'import textual; print(textual.__version__)')"
Let's see the python script for the IBM Quantum hardware with TUI:
import asyncio
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any

from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical
from textual.widgets import Button, DataTable, Footer, Header, Input, Label, RichLog, Select


CONFIG_PATH = Path(__file__).resolve().parent / "ibm_quantum_config.json"
LOG_PATH = Path(__file__).resolve().parent / "ibm_quantum_tui.log"


def _median(values: list[float]) -> float | None:
    if not values:
        return None
    ordered = sorted(values)
    mid = len(ordered) // 2
    if len(ordered) % 2 == 1:
        return ordered[mid]
    return (ordered[mid - 1] + ordered[mid]) / 2.0


def extract_calibration_metrics(backend: Any) -> dict[str, Any]:
    status = backend.status()
    props = backend.properties()

    cz_errors: list[float] = []
    cz_qubit_pairs: list[tuple[int, int]] = []
    sx_errors: list[float] = []
    readout_errors: list[float] = []
    t1_us: list[float] = []
    t2_us: list[float] = []
    qubit_freqs: list[float] = []
    anharmonicities: list[float] = []

    if props is not None:
        for q in range(backend.num_qubits):
            try:
                ro = props.readout_error(q)
                if ro is not None:
                    readout_errors.append(float(ro))
                t1 = props.t1(q)
                if t1 is not None:
                    t1_us.append(float(t1) * 1e6)
                t2 = props.t2(q)
                if t2 is not None:
                    t2_us.append(float(t2) * 1e6)
                freq = props.frequency(q)
                if freq is not None:
                    qubit_freqs.append(float(freq) / 1e9)
                anharm = props.anharmonicity(q)
                if anharm is not None:
                    anharmonicities.append(float(anharm) / 1e9)
            except Exception:
                continue

        for gate in props.gates:
            if gate.gate == "cz":
                qubits = tuple(sorted(gate.qubits))
                for param in gate.parameters:
                    if param.name == "gate_error" and param.value is not None:
                        cz_errors.append(float(param.value))
                        cz_qubit_pairs.append(qubits)
            if gate.gate == "sx":
                for param in gate.parameters:
                    if param.name == "gate_error" and param.value is not None:
                        sx_errors.append(float(param.value))

    med_cz = _median(cz_errors)
    med_sx = _median(sx_errors)
    med_ro = _median(readout_errors)
    med_t1 = _median(t1_us)
    med_t2 = _median(t2_us)
    med_freq = _median(qubit_freqs)
    med_anharm = _median(anharmonicities)

    cz_penalty = (med_cz * 1000.0) if med_cz is not None else 50.0
    sx_penalty = (med_sx * 500.0) if med_sx is not None else 5.0
    ro_penalty = (med_ro * 100.0) if med_ro is not None else 10.0
    queue_penalty = float(status.pending_jobs) * 0.05
    score = cz_penalty + sx_penalty + ro_penalty + queue_penalty

    return {
        "backend": backend,
        "name": backend.name,
        "qubits": backend.num_qubits,
        "operational": bool(status.operational),
        "pending_jobs": int(status.pending_jobs),
        "med_cz": med_cz,
        "med_sx": med_sx,
        "med_ro": med_ro,
        "med_t1": med_t1,
        "med_t2": med_t2,
        "med_freq": med_freq,
        "med_anharm": med_anharm,
        "score": score,
        "cz_errors": cz_errors,
        "cz_qubit_pairs": cz_qubit_pairs,
        "sx_errors": sx_errors,
        "readout_errors": readout_errors,
        "t1_us": t1_us,
        "t2_us": t2_us,
        "qubit_freqs": qubit_freqs,
        "anharmonicities": anharmonicities,
    }


def build_complex_circuit(num_qubits: int, layers: int) -> QuantumCircuit:
    qc = QuantumCircuit(num_qubits)

    for q in range(num_qubits):
        qc.h(q)

    for layer in range(layers):
        for q in range(num_qubits):
            angle_y = 0.35 * (layer + 1) * (q + 1) / num_qubits
            angle_z = 0.21 * (layer + 1)
            qc.ry(angle_y, q)
            qc.rz(angle_z, q)

        for q in range(num_qubits - 1):
            qc.cx(q, q + 1)
        if num_qubits > 2:
            qc.cx(num_qubits - 1, 0)

    qc.measure_all()
    return qc


class IBMQuantumTUI(App):
    TITLE = "IBM Quantum Open - Oracle ARM64 TUI"
    BINDINGS = [
        ("q", "quit", "Quit"),
        ("r", "refresh", "Refresh"),
        ("b", "pick_best", "Pick Best"),
        ("p", "prepare_circuit", "Prepare"),
        ("s", "stop_job", "Stop Job"),
    ]

    CSS = """
    Screen {
        layout: vertical;
    }
    #status_bar {
        height: 3;
        border: solid $accent;
        padding: 0 1;
        margin: 0 1 1 1;
    }
    .status_row {
        height: 1;
        margin: 0;
    }
    .status_label {
        width: 14;
        content-align: right middle;
        text-style: bold;
    }
    .status_value {
        width: 1fr;
        content-align: left middle;
    }
    #main_area {
        height: 35%;
        margin: 0 1;
    }
    #backends_panel {
        width: 2fr;
        border: solid $primary;
        padding: 0 1;
        margin-right: 1;
    }
    #prep_panel {
        width: 1fr;
        border: solid $secondary;
        padding: 0 1;
        margin-right: 1;
    }
    #log_panel_right {
        width: 1fr;
        border: solid $success;
        padding: 0 1;
    }
    #backends_table {
        height: 1fr;
    }
    #log_box_right {
        height: 1fr;
    }
    #bottom_area {
        height: 65%;
        margin: 0 1;
        border: solid $warning;
    }
    #bottom_split {
        height: 1fr;
    }
    #detail_panel_bottom {
        width: 1fr;
        border-right: solid $surface;
        padding: 0 1;
    }
    #log_panel_bottom {
        width: 1fr;
        padding: 0 1;
    }
    #detail_box {
        height: 1fr;
    }
    #log_box_bottom {
        height: 1fr;
    }
    .btn_row {
        height: 3;
        margin: 1 0;
    }
    """

    def __init__(self) -> None:
        super().__init__()
        self.service: QiskitRuntimeService | None = None
        self.backends_info: dict[str, dict[str, Any]] = {}
        self.selected_backend_name: str | None = None
        self.prepared_isa_circuit: QuantumCircuit | None = None
        self.running_job = None
        self.job_future = None

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)

        # Compact status bar with action buttons
        with Container(id="status_bar"):
            with Horizontal(classes="status_row"):
                yield Label("Status:", classes="status_label")
                yield Label("Disconnected", id="conn_status", classes="status_value")
                yield Label("Backend:", classes="status_label")
                yield Label("None", id="backend_status", classes="status_value")
            with Horizontal(classes="status_row"):
                yield Label("Config:", classes="status_label")
                yield Label("Loading...", id="config_status", classes="status_value")
                yield Button("Reconfigure", id="btn_reconfig", variant="default")
                yield Button("Refresh QPU", id="btn_refresh", variant="primary")
                yield Button("Pick Best", id="btn_best", variant="warning")
                yield Button("Transpile", id="btn_prepare", variant="success")
                yield Button("Run Circuit", id="btn_run", variant="primary")
                yield Button("Stop Job", id="btn_stop", variant="error", disabled=True)

        with Horizontal(id="main_area"):
            with Vertical(id="backends_panel"):
                yield Label("QPU Backends & Calibration Metrics")
                yield DataTable(id="backends_table", cursor_type="row")

            with Vertical(id="prep_panel"):
                yield Label("Circuit Parameters (0 RUs for transpile)")
                with Horizontal(classes="status_row"):
                    yield Label("Qubits:", classes="status_label")
                    yield Input(id="qubits_input", value="6")
                with Horizontal(classes="status_row"):
                    yield Label("Layers:", classes="status_label")
                    yield Input(id="layers_input", value="2")
                with Horizontal(classes="status_row"):
                    yield Label("Optimization:", classes="status_label")
                    yield Select(
                        options=[("Level 0", 0), ("Level 1", 1), ("Level 2", 2), ("Level 3", 3)],
                        value=3,
                        id="opt_select",
                    )
                with Horizontal(classes="status_row"):
                    yield Label("Shots:", classes="status_label")
                    yield Input(id="shots_input", value="1024")

            with Vertical(id="log_panel_right"):
                yield Label("Activity Log (Live)")
                yield RichLog(id="log_box_right", highlight=False, markup=False, wrap=True)

        # Bottom area (65%) - split: Detail panel (left) + Extended Log (right)
        with Horizontal(id="bottom_area"):
            with Vertical(id="detail_panel_bottom"):
                yield Label("Backend Detail & Calibration")
                yield RichLog(id="detail_box", highlight=False, markup=False, wrap=True)

            with Vertical(id="log_panel_bottom"):
                yield Label("Extended Log / Job Output")
                yield RichLog(id="log_box_bottom", highlight=False, markup=False, wrap=True)

        yield Footer()

    def on_mount(self) -> None:
        table = self.query_one("#backends_table", DataTable)
        table.add_columns(
            "Backend", "Qubits", "Queue", "CZ %", "SX %", "RO %",
            "T1 µs", "T2 µs", "Freq GHz", "Anharm GHz", "Score"
        )
        self._load_saved_config()

    def _log(self, message: str) -> None:
        timestamp = datetime.now().strftime("%H:%M:%S")
        formatted = f"[{timestamp}] {message}"
        # Write to both log panels
        for log_id in ("#log_box_right", "#log_box_bottom"):
            try:
                log_widget = self.query_one(log_id, RichLog)
                log_widget.write(formatted)
            except Exception:
                pass
        try:
            with LOG_PATH.open("a", encoding="utf-8") as f:
                f.write(formatted + "\n")
        except Exception:
            pass

    def _load_saved_config(self) -> None:
        if not CONFIG_PATH.exists():
            self.query_one("#config_status", Label).update("Missing - click Reconfigure")
            self._log("[INIT] No config file. Click Reconfigure to enter credentials.")
            return
        try:
            data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
            api_key = data.get("api_key", "")
            crn = data.get("crn", "")
            if api_key and crn:
                masked_key = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 12 else "***"
                self.query_one("#config_status", Label).update(f"Loaded ({masked_key})")
                self._log(f"[INIT] Config loaded from {CONFIG_PATH.name}.")
                asyncio.create_task(self._connect_and_load_async(api_key, crn))
            else:
                self.query_one("#config_status", Label).update("Incomplete - click Reconfigure")
                self._log("[INIT] Config incomplete. Click Reconfigure.")
        except Exception as exc:
            self.query_one("#config_status", Label).update(f"Error: {exc}")
            self._log(f"[ERROR] Failed to read config: {exc}")

    def _save_config(self, api_key: str, crn: str) -> None:
        try:
            payload = {"api_key": api_key, "crn": crn}
            CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8")
            os.chmod(CONFIG_PATH, 0o600)
        except Exception as exc:
            self._log(f"[WARNING] Error saving config: {exc}")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        button_id = event.button.id
        if button_id == "btn_reconfig":
            self._show_config_dialog()
        elif button_id == "btn_refresh":
            if self.service is None:
                self._show_config_dialog()
            else:
                asyncio.create_task(self._refresh_backends_async())
        elif button_id == "btn_best":
            self.action_pick_best()
        elif button_id == "btn_prepare":
            self.action_prepare_circuit()
        elif button_id == "btn_run":
            self.action_run_circuit()
        elif button_id == "btn_stop":
            self.action_stop_job()

    def _show_config_dialog(self) -> None:
        self._log("[CONFIG] Edit ~/ibm_quantum_tui/ibm_quantum_config.json:")
        self._log('  {"api_key": "YOUR_KEY", "crn": "YOUR_CRN"}')
        self._log("  Then click Refresh QPU to reload.")

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        table = self.query_one("#backends_table", DataTable)
        row_values = table.get_row(event.row_key)
        if row_values:
            self.selected_backend_name = str(row_values[0])
            self.query_one("#backend_status", Label).update(self.selected_backend_name)
            self._log(f"[SELECTION] Active backend: {self.selected_backend_name}")
            self._show_backend_details(self.selected_backend_name)

    def _show_backend_details(self, name: str) -> None:
        info = self.backends_info.get(name)
        if not info:
            return
        detail = self.query_one("#detail_box", RichLog)
        detail.clear()

        # Header
        detail.write(f"=== {name} ===")
        detail.write(f"Qubits: {info['qubits']} | Operational: {'Yes' if info['operational'] else 'No'}")
        detail.write(f"Queue: {info['pending_jobs']} | Score: {info['score']:.2f} (lower=better)")
        detail.write("")

        # Median calibration metrics
        detail.write("--- Median Calibration Metrics ---")
        cz = f"{info['med_cz']*100:.4f}%" if info['med_cz'] else "N/A"
        sx = f"{info['med_sx']*100:.4f}%" if info['med_sx'] else "N/A"
        ro = f"{info['med_ro']*100:.4f}%" if info['med_ro'] else "N/A"
        t1 = f"{info['med_t1']:.1f} µs" if info['med_t1'] else "N/A"
        t2 = f"{info['med_t2']:.1f} µs" if info['med_t2'] else "N/A"
        freq = f"{info['med_freq']:.3f} GHz" if info['med_freq'] else "N/A"
        anharm = f"{info['med_anharm']:.3f} GHz" if info['med_anharm'] else "N/A"
        detail.write(f"CZ Error:     {cz}")
        detail.write(f"SX Error:     {sx}")
        detail.write(f"Readout Err:  {ro}")
        detail.write(f"T1 (relax):   {t1}")
        detail.write(f"T2 (coher):   {t2}")
        detail.write(f"Freq:         {freq}")
        detail.write(f"Anharm:       {anharm}")
        detail.write("")

        # What each metric measures
        detail.write("--- What Metrics Measure ---")
        detail.write("CZ Error    : Two-qubit entangling gate infidelity")
        detail.write("SX Error    : Single-qubit sqrt(X) gate infidelity")
        detail.write("Readout Err : Measurement assignment error rate")
        detail.write("T1          : Energy relaxation time |1> -> |0>")
        detail.write("T2          : Phase coherence time (dephasing)")
        detail.write("Frequency   : Qubit transition frequency (GHz)")
        detail.write("Anharmonicity: |0>->|1> vs |1>->|2> spacing (GHz)")
        detail.write("")

        # Sample counts & ranges
        detail.write("--- Calibration Sample Counts ---")
        detail.write(f"CZ gates    : {len(info['cz_errors'])} samples")
        detail.write(f"SX gates    : {len(info['sx_errors'])} samples")
        detail.write(f"Readout     : {len(info['readout_errors'])} samples")
        detail.write(f"T1          : {len(info['t1_us'])} samples")
        detail.write(f"T2          : {len(info['t2_us'])} samples")
        detail.write(f"Frequency   : {len(info['qubit_freqs'])} samples")
        detail.write(f"Anharm      : {len(info['anharmonicities'])} samples")
        detail.write("")

        # Ranges if available
        def _range(vals: list[float], scale: float = 1.0, unit: str = "") -> str:
            if not vals:
                return "N/A"
            vmin = min(vals) * scale
            vmax = max(vals) * scale
            return f"{vmin:.4f} - {vmax:.4f} {unit}"

        detail.write("--- Value Ranges ---")
        detail.write(f"CZ Error    : {_range(info['cz_errors'], 100, ' %')}")
        detail.write(f"SX Error    : {_range(info['sx_errors'], 100, ' %')}")
        detail.write(f"Readout Err : {_range(info['readout_errors'], 100, ' %')}")
        detail.write(f"T1          : {_range(info['t1_us'], 1.0, ' µs')}")
        detail.write(f"T2          : {_range(info['t2_us'], 1.0, ' µs')}")
        detail.write(f"Frequency   : {_range(info['qubit_freqs'], 1.0, ' GHz')}")
        detail.write(f"Anharm      : {_range(info['anharmonicities'], 1.0, ' GHz')}")

        # Per-qubit-pair CZ errors (2-qubit gate errors)
        if info.get('cz_qubit_pairs') and info.get('cz_errors'):
            detail.write("")
            detail.write("--- 2-Qubit CZ Errors by Qubit Pair ---")
            # Group by qubit pair (in case multiple calibrations per pair)
            pair_errors: dict[tuple[int, int], list[float]] = {}
            for pair, err in zip(info['cz_qubit_pairs'], info['cz_errors']):
                if pair not in pair_errors:
                    pair_errors[pair] = []
                pair_errors[pair].append(err)
            
            for pair in sorted(pair_errors.keys()):
                errs = pair_errors[pair]
                if len(errs) == 1:
                    detail.write(f"  q{pair[0]}-q{pair[1]}: {errs[0]*100:.4f}%")
                else:
                    med = _median(errs)
                    detail.write(f"  q{pair[0]}-q{pair[1]}: {med*100:.4f}% (median of {len(errs)} samples)")
            detail.write(f"  Total unique pairs: {len(pair_errors)} | Total CZ calibrations: {len(info['cz_errors'])}")

    def action_connect_ibm(self) -> None:
        self._show_config_dialog()

    async def _connect_and_load_async(self, api_key: str, crn: str) -> None:
        self.query_one("#conn_status", Label).update("Connecting...")
        self._log("[CONNECT] Contacting IBM Quantum Platform...")
        try:
            service = await asyncio.to_thread(self._init_service_blocking, api_key, crn)
            self.service = service
            self.query_one("#conn_status", Label).update("Connected")
            self._log("[OK] Connected to IBM Quantum Platform.")
            await self._refresh_backends_async()
        except Exception as exc:
            self.query_one("#conn_status", Label).update(f"Failed: {exc}")
            self._log(f"[CONNECT ERROR] {exc}")

    @staticmethod
    def _init_service_blocking(api_key: str, crn: str) -> QiskitRuntimeService:
        QiskitRuntimeService.save_account(
            channel="ibm_quantum_platform",
            token=api_key,
            instance=crn,
            overwrite=True,
        )
        return QiskitRuntimeService(channel="ibm_quantum_platform", instance=crn)

    async def _refresh_backends_async(self) -> None:
        if self.service is None:
            self._log("[INFO] Not connected. Configure credentials first.")
            return
        self.query_one("#conn_status", Label).update("Loading...")
        self._log("[CALIBRATION] Fetching QPU status and calibration data...")
        try:
            metrics_list = await asyncio.to_thread(self._fetch_all_metrics_blocking, self.service)
            table = self.query_one("#backends_table", DataTable)
            table.clear()
            self.backends_info.clear()

            for item in metrics_list:
                self.backends_info[item["name"]] = item
                cz = f"{item['med_cz']*100:.3f}%" if item["med_cz"] else "N/A"
                sx = f"{item['med_sx']*100:.3f}%" if item["med_sx"] else "N/A"
                ro = f"{item['med_ro']*100:.3f}%" if item["med_ro"] else "N/A"
                t1 = f"{item['med_t1']:.1f}" if item["med_t1"] else "N/A"
                t2 = f"{item['med_t2']:.1f}" if item["med_t2"] else "N/A"
                freq = f"{item['med_freq']:.3f}" if item["med_freq"] else "N/A"
                anharm = f"{item['med_anharm']:.3f}" if item["med_anharm"] else "N/A"
                table.add_row(
                    item["name"],
                    str(item["qubits"]),
                    str(item["pending_jobs"]),
                    cz, sx, ro, t1, t2, freq, anharm,
                    f"{item['score']:.2f}",
                )

            if metrics_list and self.selected_backend_name not in self.backends_info:
                self.selected_backend_name = metrics_list[0]["name"]
                self.query_one("#backend_status", Label).update(self.selected_backend_name)
                self._show_backend_details(self.selected_backend_name)

            self.query_one("#conn_status", Label).update("Connected")
            self._log(f"[INSTANCES] Loaded {len(metrics_list)} QPU backends.")
        except Exception as exc:
            self.query_one("#conn_status", Label).update("Error")
            self._log(f"[CALIBRATION ERROR] {exc}")

    @staticmethod
    def _fetch_all_metrics_blocking(service: QiskitRuntimeService) -> list[dict[str, Any]]:
        backends = service.backends(operational=True, simulator=False)
        return [extract_calibration_metrics(b) for b in backends]

    def action_pick_best(self) -> None:
        if not self.backends_info:
            self._log("[INFO] Load backends first (Refresh QPU).")
            return
        best = min(self.backends_info.values(), key=lambda x: x["score"])
        self.selected_backend_name = best["name"]
        self.query_one("#backend_status", Label).update(best["name"])
        cz = f"{best['med_cz']*100:.3f}%" if best["med_cz"] else "N/A"
        self._log(f"[OPTIMAL] {best['name']} | Queue: {best['pending_jobs']} | CZ: {cz} | Score: {best['score']:.2f}")
        self._show_backend_details(best["name"])

    def action_prepare_circuit(self) -> None:
        if not self.selected_backend_name or self.selected_backend_name not in self.backends_info:
            self._log("[VALIDATION] Select a backend first (click table row or Pick Best).")
            return

        try:
            num_qubits = int(self.query_one("#qubits_input", Input).value.strip())
            layers = int(self.query_one("#layers_input", Input).value.strip())
            opt_level = int(self.query_one("#opt_select", Select).value)
            if num_qubits < 2 or num_qubits > 32 or layers < 1 or layers > 12:
                raise ValueError("Range: qubits 2..32, layers 1..12.")
        except Exception as exc:
            self._log(f"[INVALID PARAMS] {exc}")
            return

        backend_obj = self.backends_info[self.selected_backend_name]["backend"]
        asyncio.create_task(self._prepare_circuit_async(backend_obj, num_qubits, layers, opt_level))

    async def _prepare_circuit_async(
        self, backend_obj: Any, num_qubits: int, layers: int, opt_level: int
    ) -> None:
        self._log(f"[TRANSPILE] {num_qubits}q/{layers}L on {backend_obj.name} (opt={opt_level})...")
        try:
            qc, isa_circuit, physical_qubits = await asyncio.to_thread(
                self._transpile_blocking, backend_obj, num_qubits, layers, opt_level
            )
            self.prepared_isa_circuit = isa_circuit
            ops = dict(isa_circuit.count_ops())
            cz_count = ops.get("cz", 0)

            self._log(f"[LOGICAL] Depth: {qc.depth()} | Ops: {dict(qc.count_ops())}")
            self._log(f"[ISA] {backend_obj.name} | Depth: {isa_circuit.depth()} | CZ: {cz_count} | Native: {ops}")
            if physical_qubits:
                self._log(f"[LAYOUT] Physical qubits: {sorted(physical_qubits)}")
            self._log("[STATUS] Transpiled. Ready to run (consumes RUs).")
        except Exception as exc:
            self._log(f"[TRANSPILE ERROR] {exc}")

    def action_run_circuit(self) -> None:
        if self.prepared_isa_circuit is None:
            self._log("[VALIDATION] Transpile a circuit first (Transpile button).")
            return
        if not self.selected_backend_name or self.service is None:
            self._log("[VALIDATION] No backend selected or not connected.")
            return

        try:
            shots = int(self.query_one("#shots_input", Input).value.strip())
            if shots < 1 or shots > 100000:
                raise ValueError("Shots range: 1..100000")
        except Exception as exc:
            self._log(f"[INVALID SHOTS] {exc}")
            return

        backend_obj = self.backends_info[self.selected_backend_name]["backend"]
        self.query_one("#btn_stop", Button).disabled = False
        self.query_one("#btn_run", Button).disabled = True
        self._log(f"[RUN] Submitting to {backend_obj.name} with {shots} shots...")
        asyncio.create_task(self._run_circuit_async(backend_obj, shots))

    async def _run_circuit_async(self, backend_obj: Any, shots: int) -> None:
        try:
            sampler = await asyncio.to_thread(SamplerV2, mode=backend_obj)
            job = await asyncio.to_thread(sampler.run, [self.prepared_isa_circuit], shots=shots)
            self.running_job = job
            self._log(f"[JOB] Submitted: {job.job_id()} | Status: {job.status()}")
            self._log("[WAIT] Waiting for completion (Stop Job to cancel)...")

            result = await asyncio.to_thread(job.result)
            self._log(f"[DONE] Job completed: {job.job_id()}")
            counts = result[0].data.meas.get_counts()
            self._log(f"[RESULTS] Counts: {dict(list(counts.items())[:10])}...")
            if len(counts) > 10:
                self._log(f"  ... and {len(counts) - 10} more outcomes")
        except Exception as exc:
            self._log(f"[JOB ERROR] {exc}")
        finally:
            self.running_job = None
            self.query_one("#btn_stop", Button).disabled = True
            self.query_one("#btn_run", Button).disabled = False

    def action_stop_job(self) -> None:
        if self.running_job is not None:
            self._log(f"[STOP] Cancelling job {self.running_job.job_id()}...")
            try:
                self.running_job.cancel()
                self._log("[STOP] Cancellation requested.")
            except Exception as exc:
                self._log(f"[STOP ERROR] {exc}")
        else:
            self._log("[STOP] No running job to cancel.")

    @staticmethod
    def _transpile_blocking(
        backend_obj: Any, num_qubits: int, layers: int, opt_level: int
    ) -> tuple[QuantumCircuit, QuantumCircuit, list[int]]:
        qc = build_complex_circuit(num_qubits, layers)
        pass_manager = generate_preset_pass_manager(
            optimization_level=opt_level,
            backend=backend_obj,
        )
        isa_circuit = pass_manager.run(qc)

        physical_qubits: list[int] = []
        if isa_circuit.layout and isa_circuit.layout.initial_layout:
            v2p = isa_circuit.layout.initial_layout.get_virtual_bits()
            physical_qubits = [
                int(phys)
                for virt, phys in v2p.items()
                if getattr(virt, "_register", None) and virt._register.name == "q"
            ]
        return qc, isa_circuit, physical_qubits


if __name__ == "__main__":
    IBMQuantumTUI().run()
This is the result: