{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "510d7b12",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Orbit by Quantum Elements\n",
        "description: Load the Orbit function by Quantum Elements, choose a function size, and compare raw and Orbit-enhanced Bernstein-Vazirani circuits.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore MEM, Bernstein, Vazirani, bitstring, transpiler, transpilation, decoupling, mid-circuit, vCPU, alap */}\n",
        "\n",
        "# Get started with Orbit by Quantum Elements\n",
        "\n",
        "*See the [overview](/docs/functions/quantum-elements-orbit) and the [API reference](/docs/functions/quantum-elements-orbit/api-reference)*\n",
        "\n",
        "<Admonition type=\"note\" title=\"Note\">\n",
        "  IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "86fcdc03",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "38e15b38",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Authenticate using your [IBM Quantum Platform API key](http://quantum.cloud.ibm.com/), and select the Orbit function as follows. This snippet assumes you've already [saved your account](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client) to your local environment.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "6a4e3d93",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[QiskitFunction(quantum-elements/orbit-dev),\n",
              " QiskitFunction(quantum-elements/orbit)]"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "from qiskit import QuantumCircuit\n",
        "\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "# Verify that you have access to the function.\n",
        "catalog.list()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "15114161",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Orbit version: 0.3.23\n"
          ]
        }
      ],
      "source": [
        "# Load the function.\n",
        "orbit = catalog.load(\"quantum-elements/orbit\")\n",
        "print(\"Orbit version:\", orbit.version)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b4c79e2b",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size — `S`, `M`, or `L`. If the specified size is too small, the job is rejected. If it is  larger\n",
        "than needed, it runs on a bigger compute profile than the work requires. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for how sizes work in general.\n",
        "\n",
        "The size comes from your circuit **after it is mapped onto the backend you target**:\n",
        "the number of qubits that carry an operation, and the two-qubit-gate depth. Mapping\n",
        "can add both, so a circuit is sized as it will run, not as you wrote it.\n",
        "\n",
        "| Size | Smallest size for active qubits and two-qubit-gate depth | Compute profile | vCPU | RAM    |\n",
        "| ---- | -------------------------------------------------------- | --------------- | ---- | ------ |\n",
        "| `S`  | both at most 40                                          | `8x32`          | 8    | 32 GB  |\n",
        "| `M`  | both at most 100                                         | `16x128`        | 16   | 128 GB |\n",
        "| `L`  | either above 100                                         | `48x768`        | 48   | 768 GB |\n",
        "\n",
        "A circuit must fit **both** bounds of a size, so 30 qubits at a two-qubit-gate depth of\n",
        "120 is `L`, not `S`. These are the same bounds for every circuit function, so a size\n",
        "means the same difficulty of circuit whichever one you call.\n",
        "\n",
        "The default is `M`, used when a job does not request a size.\n",
        "\n",
        "Users can also read the mapping off the function itself with `function.sizes_map`, and\n",
        "the size used when a job does not ask for one with `function.default_size`.\n",
        "\n",
        "Orbit checks the size against the backend the job runs on. If you omit `backend_name`,\n",
        "Orbit picks the least busy backend, so pass `backend_name` explicitly when you size a job\n",
        "in advance.\n",
        "\n",
        "Each circuit is measured twice: as you submit it, and as a copy with its delays removed,\n",
        "laid out with Sabre and routed. The job is checked against the smaller of the two sizes.\n",
        "So a circuit you have already scheduled (for example with `scheduling_method=\"alap\"`),\n",
        "which carries a delay on every idle qubit of the device, is sized by the qubits it uses\n",
        "rather than by the width of the device, and a chain of qubits is not sized by SWAPs that a\n",
        "better layout avoids. The calculator below runs the same calculation as Orbit, so it\n",
        "returns the size your job is checked against.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "de2b9c04",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Run this on your own circuits. It reads them and does nothing else; no job is submitted\n",
        "and nothing is reserved, so you can call it as often as you like while you tune a\n",
        "circuit down to a smaller size.\n",
        "\n",
        "It needs the backend as well as the circuits, because the size depends on the\n",
        "coupling map they are mapped onto. It requires only Qiskit.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ccee4415",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Calculate the function size a circuit needs, before submitting it.\n",
        "#\n",
        "# Call ``calculate_function_size(pubs, backend)``: it returns \"S\", \"M\" or \"L\" and submits\n",
        "# nothing. Pass the whole list of PUBs. A job runs at one size, and the heaviest PUB\n",
        "# determines the size. The circuit is measured after being mapped onto the ``backend``, since mapping\n",
        "# can add both qubits and depth.\n",
        "#\n",
        "# This is the calculation Orbit runs on every job. Each circuit is measured twice, as given\n",
        "# and as a copy with its delays removed, laid out with Sabre and routed, and is sized as\n",
        "# the smaller of the two. The copy keeps a scheduled circuit from being sized by the idle\n",
        "# qubits its delays cover, and a chain from picking up SWAPs a better layout avoids.\n",
        "\n",
        "from collections.abc import Iterable\n",
        "from typing import Any, Literal\n",
        "\n",
        "from qiskit.circuit import Barrier, Delay\n",
        "from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary\n",
        "from qiskit.transpiler import PassManager, generate_preset_pass_manager\n",
        "from qiskit.transpiler.passes import (\n",
        "    ApplyLayout,\n",
        "    BarrierBeforeFinalMeasurements,\n",
        "    BasisTranslator,\n",
        "    EnlargeWithAncilla,\n",
        "    FilterOpNodes,\n",
        "    FullAncillaAllocation,\n",
        "    HighLevelSynthesis,\n",
        "    SabreSwap,\n",
        "    TrivialLayout,\n",
        "    UnitarySynthesis,\n",
        ")\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "_ORDER = {\"S\": 0, \"M\": 1, \"L\": 2}\n",
        "\n",
        "# Limits are provided by IBM\n",
        "_SMALL_QUBITS, _SMALL_DEPTH_2Q = 40, 40\n",
        "_MEDIUM_QUBITS, _MEDIUM_DEPTH_2Q = 100, 100\n",
        "\n",
        "# Any fixed value works; what matters is that it does not change between calls.\n",
        "_SEED_TRANSPILER = 42\n",
        "\n",
        "# Added by BarrierBeforeFinalMeasurements so routing cannot move gates past a measurement,\n",
        "# then removed again once routing is done.\n",
        "_PROTECTION_BARRIER = \"qiskit.transpiler.internal.routing.protection.barrier\"\n",
        "\n",
        "\n",
        "def calculate_function_size(\n",
        "    circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any\n",
        ") -> Size:\n",
        "    \"\"\"Return the size (\"S\", \"M\" or \"L\") required to run the function.\"\"\"\n",
        "    circuits = pub_circuits(circuit)\n",
        "    if not circuits:\n",
        "        raise ValueError(\n",
        "            \"No circuit to size: pass a QuantumCircuit or a non-empty list of PUBs.\"\n",
        "        )\n",
        "    prepare = generate_preset_pass_manager(\n",
        "        optimization_level=0,\n",
        "        target=backend.target,\n",
        "        layout_method=\"sabre\",\n",
        "        seed_transpiler=_SEED_TRANSPILER,\n",
        "    )\n",
        "    return max(\n",
        "        (_smaller_size(qc, backend, prepare, **kwargs) for qc in circuits),\n",
        "        key=_ORDER.__getitem__,\n",
        "    )\n",
        "\n",
        "\n",
        "def _smaller_size(\n",
        "    circuit: QuantumCircuit, backend, prepare: PassManager, **kwargs: Any\n",
        ") -> Size:\n",
        "    \"\"\"Return the smaller size of ``circuit`` and of its copy without delays, laid out with Sabre.\n",
        "\n",
        "    Level 0 runs no optimization stage, so the copy keeps every gate of the circuit.\n",
        "    \"\"\"\n",
        "    size = _calculate_circuit_size(circuit, backend, **kwargs)\n",
        "    if size == \"S\":\n",
        "        return size\n",
        "    prepared = prepare.run(without_delays(circuit))\n",
        "    return min(\n",
        "        size,\n",
        "        _calculate_circuit_size(prepared, backend, **kwargs),\n",
        "        key=_ORDER.__getitem__,\n",
        "    )\n",
        "\n",
        "\n",
        "def without_delays(circuit: QuantumCircuit) -> QuantumCircuit:\n",
        "    \"\"\"Return a copy of ``circuit`` with every top-level ``delay`` removed.\"\"\"\n",
        "    stripped = circuit.copy_empty_like()\n",
        "    for instruction in circuit.data:\n",
        "        if not isinstance(instruction.operation, Delay):\n",
        "            stripped.append(instruction)\n",
        "    return stripped\n",
        "\n",
        "\n",
        "def _calculate_circuit_size(\n",
        "    circuit: QuantumCircuit, backend, **kwargs: Any\n",
        ") -> Size:\n",
        "    \"\"\"Return the size required to run a single circuit.\"\"\"\n",
        "    metrics = _measure(circuit, backend, **kwargs)\n",
        "    if _is_small(metrics):\n",
        "        return \"S\"\n",
        "    if _is_medium(metrics):\n",
        "        return \"M\"\n",
        "    return \"L\"\n",
        "\n",
        "\n",
        "def pub_circuits(problem: Any) -> list[QuantumCircuit]:\n",
        "    \"\"\"Return the circuits in ``problem``: one circuit, or one per PUB in a list.\"\"\"\n",
        "    if isinstance(problem, QuantumCircuit):\n",
        "        return [problem]\n",
        "    circuits: list[QuantumCircuit] = []\n",
        "    for index, pub in enumerate(problem):\n",
        "        if isinstance(pub, QuantumCircuit):\n",
        "            circuit = pub\n",
        "        elif isinstance(getattr(pub, \"circuit\", None), QuantumCircuit):\n",
        "            circuit = pub.circuit\n",
        "        elif (\n",
        "            isinstance(pub, (tuple, list))\n",
        "            and pub\n",
        "            and isinstance(pub[0], QuantumCircuit)\n",
        "        ):\n",
        "            circuit = pub[0]\n",
        "        else:\n",
        "            raise ValueError(f\"PUB #{index} has no QuantumCircuit to size.\")\n",
        "        circuits.append(circuit)\n",
        "    return circuits\n",
        "\n",
        "\n",
        "def _pass_manager(target) -> PassManager:\n",
        "    \"\"\"Return the pass manager used to map a circuit onto ``target``.\n",
        "\n",
        "    Fixed and seeded, so the same circuit always gives the same size.\n",
        "    \"\"\"\n",
        "    basis = list(target.operation_names)\n",
        "    library = SessionEquivalenceLibrary\n",
        "    return PassManager(\n",
        "        [\n",
        "            UnitarySynthesis(\n",
        "                basis, approximation_degree=1.0, min_qubits=3, target=target\n",
        "            ),\n",
        "            HighLevelSynthesis(\n",
        "                target=target,\n",
        "                equivalence_library=library,\n",
        "                basis_gates=basis,\n",
        "                min_qubits=3,\n",
        "            ),\n",
        "            BasisTranslator(library, basis, target=target, min_qubits=3),\n",
        "            TrivialLayout(target),\n",
        "            FullAncillaAllocation(target),\n",
        "            EnlargeWithAncilla(),\n",
        "            ApplyLayout(),\n",
        "            BarrierBeforeFinalMeasurements(label=_PROTECTION_BARRIER),\n",
        "            SabreSwap(\n",
        "                target, heuristic=\"basic\", seed=_SEED_TRANSPILER, trials=5\n",
        "            ),\n",
        "            FilterOpNodes(lambda node: node.label != _PROTECTION_BARRIER),\n",
        "            UnitarySynthesis(basis, approximation_degree=1.0, target=target),\n",
        "            HighLevelSynthesis(\n",
        "                target=target,\n",
        "                equivalence_library=library,\n",
        "                basis_gates=basis,\n",
        "                use_qubit_indices=True,\n",
        "            ),\n",
        "            BasisTranslator(library, basis, target=target),\n",
        "        ]\n",
        "    )\n",
        "\n",
        "\n",
        "def _count(isa: QuantumCircuit) -> dict:\n",
        "    \"\"\"Return the active qubits and two-qubit-gate depth of a mapped circuit.\"\"\"\n",
        "    active = {\n",
        "        q\n",
        "        for instr in isa.data\n",
        "        if not isinstance(instr.operation, Barrier)\n",
        "        for q in instr.qubits\n",
        "    }\n",
        "    return {\n",
        "        \"num_qubits\": len(active),\n",
        "        \"depth_2q\": isa.depth(\n",
        "            filter_function=lambda instr: len(instr.qubits) == 2\n",
        "            and not isinstance(instr.operation, Barrier)\n",
        "        ),\n",
        "    }\n",
        "\n",
        "\n",
        "def _measure(circuit: QuantumCircuit, backend, **kwargs: Any) -> dict:\n",
        "    \"\"\"Map ``circuit`` onto ``backend`` and return its metrics.\"\"\"\n",
        "    return _count(_pass_manager(backend.target).run(circuit))\n",
        "\n",
        "\n",
        "def _is_small(metrics: dict) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'S'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_qubits\"] <= _SMALL_QUBITS\n",
        "        and metrics[\"depth_2q\"] <= _SMALL_DEPTH_2Q\n",
        "    )\n",
        "\n",
        "\n",
        "def _is_medium(metrics: dict) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'M'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_qubits\"] <= _MEDIUM_QUBITS\n",
        "        and metrics[\"depth_2q\"] <= _MEDIUM_DEPTH_2Q\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "963bf238",
      "metadata": {},
      "source": [
        "Pass the **whole** list of PUBs, not one at a time. A job runs at a single size, so\n",
        "the heaviest PUB determines the size. One deep circuit among many shallow ones makes the\n",
        "whole job `L`. Split the batch into separate jobs to keep the cheap ones\n",
        "cheap. The [example](#example) below calculates the size of its PUBs and passes it to\n",
        "`orbit.run` as `function_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0883fb8c",
      "metadata": {},
      "source": [
        "If the size is too small the job fails with error `4600` and the message names the\n",
        "size to use instead. If it is larger than needed, the job runs normally and records a\n",
        "`4601` advisory event. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) to learn more.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "46a39ed8",
      "metadata": {},
      "source": [
        "## Example\n",
        "\n",
        "The following example builds a Bernstein-Vazirani circuit and submits it to Orbit two ways in one job: raw execution and Orbit defaults.\n",
        "\n",
        "Use this pattern when you want a direct raw-versus-Orbit comparison.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3f62f8d4",
      "metadata": {},
      "source": [
        "### Scaling Bernstein-Vazirani to larger sizes\n",
        "\n",
        "Orbit can help preserve Bernstein-Vazirani success probability as the hidden-bitstring width grows. The representative scaling runs below compare raw execution with Orbit configurations on IBM Quantum hardware. On `ibm_miami`, raw success probability falls below 10% by a hidden-bitstring width of 9 (10 total qubits), while Orbit remains near 80–90%. On `ibm_kingston`, Orbit maintains non-trivial success probability at widths approaching 60, including approximately 15% at the largest size shown. Exact results depend on the backend calibration, circuit, and execution settings.\n",
        "\n",
        "![Bernstein-Vazirani success probability on ibm\\_miami: Orbit with and without measurement error mitigation maintains higher success probability than raw execution as hidden-bitstring width increases.](https://quantum.cloud.ibm.com/docs/images/guides/quantum-elements-orbit/bv-fidelity-raw-orbit-mem.avif)\n",
        "\n",
        "![Bernstein-Vazirani success probability on ibm\\_kingston: box plots compare raw execution with Orbit across increasing hidden-bitstring widths, with Orbit results shown through width 60.](https://quantum.cloud.ibm.com/docs/images/guides/quantum-elements-orbit/bv-hidden-bitstring-success-boxplot.avif)\n",
        "\n",
        "To preserve QPU time, this tutorial does not rerun a size sweep. Instead, the executable example below reports shot counts for one fixed hidden-bitstring width, `N = 50` (51 total qubits in this circuit), comparing raw execution with Orbit defaults in a single job.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8708dcb1",
      "metadata": {},
      "source": [
        "### Build a Bernstein-Vazirani circuit\n",
        "\n",
        "Choose the hidden bitstring and construct the logical circuit. The extra qubit is the oracle target, while the input qubits are measured.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "3366889b",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "OrderedDict([('h', 102),\n",
              "             ('cx', 50),\n",
              "             ('measure', 50),\n",
              "             ('x', 1),\n",
              "             ('barrier', 1)])"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "def create_bv_circuit(hidden_bitstring: str) -> QuantumCircuit:\n",
        "    width = len(hidden_bitstring)\n",
        "    circuit = QuantumCircuit(width + 1, width)\n",
        "\n",
        "    circuit.x(width)\n",
        "    circuit.h(range(width + 1))\n",
        "\n",
        "    for input_qubit, bit in enumerate(reversed(hidden_bitstring)):\n",
        "        if bit == \"1\":\n",
        "            circuit.cx(input_qubit, width)\n",
        "\n",
        "    circuit.barrier()\n",
        "    circuit.h(range(width + 1))\n",
        "    circuit.measure(range(width), range(width))\n",
        "    return circuit\n",
        "\n",
        "\n",
        "circuit_width = 50\n",
        "hidden_bitstring = \"1\" * circuit_width\n",
        "shots = 4096\n",
        "\n",
        "bv_circuit = create_bv_circuit(hidden_bitstring)\n",
        "bv_circuit.count_ops()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a047bbc5",
      "metadata": {},
      "source": [
        "### Prepare the Orbit workload\n",
        "\n",
        "Create one Sampler PUB, then duplicate it for the two comparison modes. Orbit receives the logical circuit and maps it to the selected backend during execution.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "2c6a4b83",
      "metadata": {},
      "outputs": [],
      "source": [
        "base_pub = (bv_circuit, None, shots)\n",
        "comparison_labels = [\"raw\", \"orbit\"]\n",
        "pubs = [base_pub] * len(comparison_labels)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6387676f",
      "metadata": {},
      "source": [
        "### Calculate the function size\n",
        "\n",
        "Calculate the size of the PUBs on the backend you run on. The 50-qubit circuit needs\n",
        "routing on the heavy-hex coupling map, which takes its two-qubit gate depth above 100,\n",
        "so this job needs `L`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b2d94bf8",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "L\n"
          ]
        }
      ],
      "source": [
        "from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "backend_name = \"ibm_kingston\"\n",
        "backend = QiskitRuntimeService().backend(backend_name)\n",
        "\n",
        "size = calculate_function_size(pubs, backend)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "94ae3ab1",
      "metadata": {},
      "source": [
        "### Run raw and Orbit defaults\n",
        "\n",
        "`pub_options` assigns the first PUB to raw mode, which skips Orbit optimization, DD, and MEM, and assigns the second PUB to Orbit defaults, which include optimized transpilation, automated dynamical decoupling (DD) insertion, and measurement error mitigation (MEM).\n",
        "\n",
        "The job runs at the size calculated above. Without `function_size`, it would run at `M`, which is too small for these PUBs, so it would fail with error `4600`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "c1a340ad",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "2c427a80-4190-404c-b98a-6bbeb53fafcd\n",
            "QUEUED\n"
          ]
        }
      ],
      "source": [
        "job = orbit.run(\n",
        "    primitive=\"sampler\",\n",
        "    pubs=pubs,\n",
        "    backend_name=backend_name,\n",
        "    function_size=size,\n",
        "    options={\n",
        "        \"pub_options\": [\n",
        "            {\"mode\": \"raw\"},\n",
        "            {\"mode\": \"orbit\"},\n",
        "        ],\n",
        "        \"save_backend_info\": True,\n",
        "    },\n",
        ")\n",
        "\n",
        "# Check the job ID and status\n",
        "print(job.job_id)\n",
        "print(job.status())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d74599be",
      "metadata": {},
      "source": [
        "Retrieve the result and compare the raw and Orbit-enhanced circuits using counts. For Sampler results, `get_counts()` on the returned classical register provides the output histogram. When MEM succeeds for the Orbit PUB, this histogram is already MEM-corrected; the unmitigated counts remain available in the Orbit metadata under `measurementErrorMitigation[\"rawCounts\"]`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "dbab207b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'hidden_bitstring': '11111111111111111111111111111111111111111111111111', 'correct_counts': {'raw': 0, 'orbit': 370}, 'shots': 4096}\n"
          ]
        }
      ],
      "source": [
        "def extract_counts(pub_result) -> dict[str, int]:\n",
        "    data = getattr(pub_result, \"data\", None)\n",
        "    if data is None:\n",
        "        raise TypeError(\"pub_result.data is missing\")\n",
        "\n",
        "    for name in dir(data):\n",
        "        if name.startswith(\"_\"):\n",
        "            continue\n",
        "        register = getattr(data, name)\n",
        "        get_counts = getattr(register, \"get_counts\", None)\n",
        "        if callable(get_counts):\n",
        "            counts = get_counts()\n",
        "            if counts:\n",
        "                return counts\n",
        "\n",
        "    raise TypeError(\n",
        "        \"No classical register with get_counts() found in pub_result.data\"\n",
        "    )\n",
        "\n",
        "\n",
        "result = job.result()\n",
        "if len(result) != len(comparison_labels):\n",
        "    raise RuntimeError(\n",
        "        f\"Expected {len(comparison_labels)} PUB results, received {len(result)}.\"\n",
        "    )\n",
        "\n",
        "comparison_counts = {\n",
        "    label: extract_counts(pub_result)\n",
        "    for label, pub_result in zip(comparison_labels, result, strict=True)\n",
        "}\n",
        "correct_counts = {\n",
        "    label: counts.get(hidden_bitstring, 0)\n",
        "    for label, counts in comparison_counts.items()\n",
        "}\n",
        "\n",
        "print(\n",
        "    {\n",
        "        \"hidden_bitstring\": hidden_bitstring,\n",
        "        \"correct_counts\": correct_counts,\n",
        "        \"shots\": shots,\n",
        "    }\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a753eaad",
      "metadata": {},
      "source": [
        "Make a visual comparison of the raw and Orbit-enhanced circuits.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "7656f768",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/quantum-elements-orbit/extracted-outputs/7656f768-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "labels = list(correct_counts)\n",
        "values = list(correct_counts.values())\n",
        "fig, ax = plt.subplots(figsize=(7, 4))\n",
        "bars = ax.bar(labels, values, width=0.55)\n",
        "ax.bar_label(bars, labels=[f\"{value:g}\" for value in values], padding=3)\n",
        "ax.set_xlabel(\"Circuit execution mode\")\n",
        "ax.set_ylabel(\"Correct hidden-bitstring count\")\n",
        "ax.set_title(f\"{circuit_width}-qubit Bernstein-Vazirani on {backend_name}\")\n",
        "ax.set_ylim(0, max(1, 1.15 * max(values)))\n",
        "ax.grid(axis=\"y\", alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f2f1a5dd",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Try a different backend, qubit number, or another hidden bitstring.\n",
        "  * Try the [quantum Fourier transform tutorial](/docs/tutorials/quantum-elements-orbit-qft-with-dynamic-circuits) to learn how to define orbit-enabled custom DD strategies and apply DD to dynamic circuits with mid-circuit measurements and feedforward operations.\n",
        "  * Visit the [API reference](/docs/functions/quantum-elements-orbit/api-reference) for a detailed description of all Orbit options.\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}