{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "dde95705-gs",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Q-CTRL Performance Management\n",
        "description: Load the Q-CTRL Performance Management function and run Estimator and Sampler workloads with automated error suppression.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore fontsize */}\n",
        "\n",
        "# Get started with Q-CTRL Performance Management\n",
        "\n",
        "*See the [overview](/docs/functions/q-ctrl-performance-management) and the [API reference](/docs/functions/q-ctrl-performance-management/api-reference)*\n",
        "\n",
        "<Admonition type=\"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": "ace2ed13",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<Accordion>\n",
        "  <AccordionItem title=\"Package versions\">\n",
        "    The code on this page was developed using the following requirements.\n",
        "    We recommend using these versions or newer.\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.3.1\n",
        "    qiskit-ibm-runtime~=0.45.1\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "870af0fe",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Fire Opal Performance Management uses Qiskit v`2.0.0`, which is the recommended version. Supported versions are Qiskit >=v`2.0.0`.\n",
        "Authenticate using your [IBM Quantum Platform API key](http://quantum.cloud.ibm.com/), and select the quantum 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": 3,
      "id": "11af8fb4",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "736255e4-1c1f-42a7-bf76-1487878c9e76",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Access function\n",
        "perf_mgmt = catalog.load(\"q-ctrl/performance-management\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d4657810",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"Does this function support all IBM backends?\">\n",
        "  If you want to use a backend that this function does not currently support, [reach out to Q-CTRL](https://form.typeform.com/to/iuujEAEI?typeform-source=q-ctrl.com) to add support.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "57dcac9e",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size: `S`, `M`, or `L`. If the size is too small, the job is rejected. If it is larger than needed, the job 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",
        "Pass the size to `perf_mgmt.run()` with the `function_size` argument. The same sizing rules apply to both Sampler and Estimator.\n",
        "\n",
        "For Performance Management, the size depends on the number of active physical qubits and the two-qubit gate depth after the circuit is mapped and routed to the selected backend. The sizing calculation uses mapping and routing equivalent to Qiskit's `optimization_level=0`.\n",
        "\n",
        "Active qubits are the physical qubits used by circuit operations, excluding barriers. The two-qubit gate depth counts only two-qubit operations, also excluding barriers. Routing can increase both values, so the required size depends on the selected backend as well as the input circuit.\n",
        "\n",
        "| Size | Active qubits | Two-qubit gate depth | Rule                                                                                   |\n",
        "| ---- | ------------- | -------------------- | -------------------------------------------------------------------------------------- |\n",
        "| `S`  | ≤ 40          | ≤ 40                 | Both metrics must satisfy the Small limits.                                            |\n",
        "| `M`  | ≤ 100         | ≤ 100                | At least one metric exceeds its Small limit, but both remain within the Medium limits. |\n",
        "| `L`  | > 100         | > 100                | Either active qubits or two-qubit gate depth exceeds its Medium limit.                 |\n",
        "\n",
        "If you submit multiple PUBs, select the largest size required by any circuit in the workload. For example, a mapped circuit with 30 active qubits and a two-qubit gate depth of 60 requires `\"M\"`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "54410f23",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Use the following helper to calculate the size for your PUB tuples. No job is submitted. It maps and routes each circuit to the selected backend with `optimization_level=0`, then checks the active qubits and two-qubit gate depth, excluding barriers. For multiple PUBs, it returns the largest required size.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "4a34c595",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Size calculator for a circuit function.\n",
        "#\n",
        "# Input:  ``calculate_function_size(circuit, backend, **kwargs)`` -- the circuit and the backend it\n",
        "#         will run on are both required, and the other function inputs arrive as\n",
        "#         ``**kwargs``. The backend is needed because the size depends on its coupling map,\n",
        "#         so pass it by keyword through ``validate_size``:\n",
        "#         ``validate_size(\"S\", circuit, backend=backend)``. A list of PUBs is accepted in\n",
        "#         place of a single circuit, and is sized as the largest of its PUBs.\n",
        "# Output: ``\"S\"``, ``\"M\"`` or ``\"L\"``, from the number of active qubits and the\n",
        "#         two-qubit-gate depth after mapping the circuit onto ``backend``.\n",
        "#\n",
        "# Call ``validate_size`` **once** per job, on everything the job will submit -- the\n",
        "# whole PUB list, not one PUB at a time. A job runs at a single size, so it has to be sized\n",
        "# for its heaviest PUB; calling per PUB would also emit one oversize event per PUB.\n",
        "#\n",
        "# The mapping is done by ``_pass_manager``, which spells out the passes rather than calling\n",
        "# ``generate_preset_pass_manager(optimization_level=0)``, so that a future change to the\n",
        "# preset recipe cannot silently move every vendor's calculates.\n",
        "#\n",
        "# Routing is seeded, because routing is stochastic and ``validate_size``\n",
        "# re-calculates: with an unseeded pass manager the same circuit can be sized differently on\n",
        "# consecutive calls, so a job could be rejected on a size an identical earlier call accepted.\n",
        "#\n",
        "# ``QuantumCircuit.depth(filter_function)`` counts only the instructions for which\n",
        "# ``filter_function`` returns True, so a two-qubit filter gives the two-qubit-gate depth.\n",
        "# https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit#depth\n",
        "#\n",
        "# Depends only on Qiskit and ``qiskit-serverless``, so the same file runs in your image and\n",
        "# in a user's notebook.\n",
        "\n",
        "from collections.abc import Iterable\n",
        "from typing import Any, Literal\n",
        "\n",
        "from qiskit import QuantumCircuit\n",
        "from qiskit.circuit import Barrier\n",
        "from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary\n",
        "from qiskit.transpiler import PassManager\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",
        "from qiskit_serverless import (\n",
        "    ServerlessError,\n",
        "    get_function_size,\n",
        "    get_logger,\n",
        "    send_error,\n",
        ")\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "_ORDER = {\"S\": 0, \"M\": 1, \"L\": 2}\n",
        "\n",
        "# Error codes assigned by IBM; see the IBM Quantum error registry.\n",
        "SIZE_TOO_SMALL_ERROR_CODE = \"4600\"\n",
        "SIZE_TOO_LARGE_ERROR_CODE = \"4601\"\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",
        "\n",
        "    ``circuit`` is either one ``QuantumCircuit`` or a list of PUBs. For a list, every PUB\n",
        "    circuit is sized on its own and the largest size wins: the job runs on one size, so it\n",
        "    has to be the size the heaviest PUB needs.\n",
        "    \"\"\"\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",
        "    return max(\n",
        "        (_calculate_circuit_size(qc, backend, **kwargs) for qc in circuits),\n",
        "        key=_ORDER.__getitem__,\n",
        "    )\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 of PUBs.\n",
        "\n",
        "    A PUB may be a bare circuit, a tuple/list whose first item is the circuit, or a coerced\n",
        "    ``SamplerPub`` / ``EstimatorPub`` (which carries a ``.circuit`` attribute).\n",
        "    \"\"\"\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",
        "    This spells out the passes that ``generate_preset_pass_manager(optimization_level=0)``\n",
        "    assembles today, so that a future change to the level-0 recipe cannot silently move\n",
        "    every vendor's size calculates. It is the pass list that is pinned, not the passes: a\n",
        "    new Qiskit release can still change what ``SabreSwap`` or ``BasisTranslator`` does.\n",
        "\n",
        "    Stages, mirroring the preset: unroll anything wider than two qubits, lay the circuit\n",
        "    out trivially and pad it to the backend width, route it, then translate to the\n",
        "    backend basis. Level 0 runs no optimization stage.\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 number of active qubits and the two-qubit-gate depth of a mapped circuit.\n",
        "\n",
        "    ``isa.num_qubits`` would be the width of the whole backend, so only the qubits that\n",
        "    carry an operation are counted.\n",
        "    \"\"\"\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:  # pylint: disable=unused-argument\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",
        "    )\n",
        "\n",
        "\n",
        "def validate_size(\n",
        "    circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any\n",
        ") -> None:\n",
        "    \"\"\"Call once at the start of your function, on everything the job will submit.\n",
        "\n",
        "    Compare the size the job was given with the calculated size and log both. Raise if\n",
        "    the given size is smaller than the calculation; report a non-fatal event and continue\n",
        "    if it is larger. Pass the whole PUB list rather than calling this per PUB: the job\n",
        "    runs at one size, and a per-PUB call would emit one oversize event per PUB.\"\"\"\n",
        "    logger = get_logger()\n",
        "    provided = get_function_size()\n",
        "    if not provided:\n",
        "        # Empty on non-Fleets (Ray) jobs, where sizes do not apply.\n",
        "        logger.warning(\n",
        "            \"No function size was given to this job; skipping the size check.\"\n",
        "        )\n",
        "        return\n",
        "    provided = provided.upper()\n",
        "    expected = calculate_function_size(circuit, backend, **kwargs)\n",
        "    logger.info(\n",
        "        \"Function size given: '%s'; calculated size: '%s'.\",\n",
        "        provided,\n",
        "        expected,\n",
        "    )\n",
        "    if _ORDER[provided] < _ORDER[expected]:\n",
        "        logger.error(\n",
        "            \"Size '%s' is too small; the calculated size is '%s'.\",\n",
        "            provided,\n",
        "            expected,\n",
        "        )\n",
        "        raise ServerlessError(\n",
        "            code=SIZE_TOO_SMALL_ERROR_CODE,\n",
        "            message=f\"Size '{provided}' is too small for this problem; expected '{expected}' or larger.\",\n",
        "        )\n",
        "    if _ORDER[provided] > _ORDER[expected]:\n",
        "        logger.warning(\n",
        "            \"Size '%s' is larger than this problem needs; the calculated size is '%s'.\",\n",
        "            provided,\n",
        "            expected,\n",
        "        )\n",
        "        send_error(\n",
        "            code=SIZE_TOO_LARGE_ERROR_CODE,\n",
        "            message=\"The specified function size is larger than this job requires.\",\n",
        "            exception=\"FunctionSizeTooLarge\",\n",
        "            args={\n",
        "                \"provided_size\": provided,\n",
        "                \"calculated_size\": expected,\n",
        "                \"solution\": (\n",
        "                    \"No action is required and the job completed normally. To reduce \"\n",
        "                    \"cost, use a smaller function size for jobs of this kind.\"\n",
        "                ),\n",
        "            },\n",
        "        )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "qctrl-pm-sizes-outro",
      "metadata": {},
      "source": [
        "If the size is too small, the job fails with error `4600`, and the message names the size to use instead. If it is larger than needed, the job runs normally and records a `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": "2947b5c3",
      "metadata": {},
      "source": [
        "## Estimator primitive\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "df2788d5",
      "metadata": {},
      "source": [
        "### Estimator example\n",
        "\n",
        "Use Fire Opal Performance Management's Estimator primitive to determine the expectation value of a single circuit-observable pair.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "82932760",
      "metadata": {},
      "source": [
        "In addition to the `qiskit-ibm-catalog` and `qiskit` packages, you will also use the `numpy` package to run this example. You can install this package by uncommenting the following cell if you are running this example in a notebook using the IPython kernel.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "70bb93ef",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install numpy"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "02b2a79a",
      "metadata": {},
      "source": [
        "**1. Create the circuit**\n",
        "\n",
        "As an example, generate a random Hermitian operator and an observable to input to the Performance Management function.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "32037218",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from qiskit.circuit.library import iqp\n",
        "from qiskit.quantum_info import random_hermitian, SparsePauliOp\n",
        "\n",
        "n_qubits = 37\n",
        "\n",
        "# Generate a random circuit\n",
        "mat = np.real(random_hermitian(n_qubits, seed=1234))\n",
        "circuit = iqp(mat)\n",
        "circuit.measure_all()\n",
        "\n",
        "# Define observables as a string\n",
        "observable = SparsePauliOp(\"Z\" * n_qubits)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "476fae6a",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Create PUB tuple\n",
        "estimator_pubs = [(circuit, observable)]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "09e64cd7",
      "metadata": {},
      "source": [
        "**2. Run the circuit**\n",
        "\n",
        "Calculate the function size for `estimator_pubs` on the selected backend, then pass the returned value to `perf_mgmt.run` through `function_size`. For the sizing rules, see [Function sizes](#function-sizes). You can also specify the number of shots.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "979809bc",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Workload size: M\n"
          ]
        }
      ],
      "source": [
        "backend = catalog.least_busy()\n",
        "estimator_size = calculate_function_size(estimator_pubs, backend)\n",
        "print(f\"Workload size: {estimator_size}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "26952e1f",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Run the circuit using Estimator\n",
        "qctrl_estimator_job = perf_mgmt.run(\n",
        "    primitive=\"estimator\",\n",
        "    pubs=estimator_pubs,\n",
        "    backend_name=backend.name,\n",
        "    function_size=estimator_size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c07af9d0",
      "metadata": {},
      "source": [
        "Check your quantum function workload's status:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "2b309861",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'DONE'"
            ]
          },
          "execution_count": 11,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "qctrl_estimator_job.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "23556c8e",
      "metadata": {},
      "source": [
        "**3. Retrieve the result**\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "8be67088",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Retrieve the counts from the result list\n",
        "result = qctrl_estimator_job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7375fcad",
      "metadata": {},
      "source": [
        "The results have the same format as an [Estimator result](/docs/ibm-quantum-compute/estimator-input-output):\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "ef85a036",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The result of the submitted job had 1 PUB and has a value:\n",
            " PubResult(data=DataBin(evs=np.ndarray(<shape=(1,), dtype=float64>), stds=np.ndarray(<shape=(1,), dtype=float64>)), metadata={'precision': None})\n",
            "\n",
            "The associated PubResult of this job has the following DataBins:\n",
            "DataBin(evs=np.ndarray(<shape=(1,), dtype=float64>), stds=np.ndarray(<shape=(1,), dtype=float64>))\n",
            "\n",
            "And this DataBin has attributes: dict_keys(['evs', 'stds'])\n",
            "The expectation values measured from this PUB are:\n",
            "[0.00252317]\n"
          ]
        }
      ],
      "source": [
        "import numpy\n",
        "\n",
        "result_str = str(result)\n",
        "\n",
        "with numpy.printoptions(threshold=200):\n",
        "    print(\n",
        "        f\"The result of the submitted job had {len(result)} PUB \"\n",
        "        f\"and has a value:\\n {result[0]}\\n\"\n",
        "    )\n",
        "\n",
        "print(\"The associated PubResult of this job has the following DataBins:\")\n",
        "print(f\"{result[0].data}\\n\")\n",
        "\n",
        "print(f\"And this DataBin has attributes: {result[0].data.keys()}\")\n",
        "\n",
        "print(\"The expectation values measured from this PUB are:\")\n",
        "print(f\"{result[0].data.evs}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a78ce8bd",
      "metadata": {},
      "source": [
        "## Sampler primitive\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b1300f06",
      "metadata": {},
      "source": [
        "### Sampler example\n",
        "\n",
        "Use Fire Opal Performance Management's Sampler primitive to run a Bernstein–Vazirani circuit. This algorithm, used to find a hidden string from the outputs of a black box function, is a common benchmarking algorithm because there is a single correct answer.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "144e48f3",
      "metadata": {},
      "source": [
        "**1. Create the circuit**\n",
        "\n",
        "Define the correct answer to the algorithm, the hidden bitstring, and the Bernstein–Vazirani circuit. You can adjust the width of the circuit by simply changing the `circuit_width`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "id": "2cd807b1",
      "metadata": {},
      "outputs": [],
      "source": [
        "import qiskit\n",
        "\n",
        "circuit_width = 14\n",
        "hidden_bitstring = \"1\" * circuit_width\n",
        "\n",
        "# Create circuit, reserving one qubit for BV oracle\n",
        "bv_circuit = qiskit.QuantumCircuit(circuit_width + 1, circuit_width)\n",
        "bv_circuit.x(circuit_width)\n",
        "bv_circuit.h(range(circuit_width + 1))\n",
        "for input_qubit, bit in enumerate(reversed(hidden_bitstring)):\n",
        "    if bit == \"1\":\n",
        "        bv_circuit.cx(input_qubit, circuit_width)\n",
        "bv_circuit.barrier()\n",
        "bv_circuit.h(range(circuit_width + 1))\n",
        "bv_circuit.barrier()\n",
        "for input_qubit in range(circuit_width):\n",
        "    bv_circuit.measure(input_qubit, input_qubit)\n",
        "\n",
        "# Create PUB tuple\n",
        "sampler_pubs = [(bv_circuit,)]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "85d3c00b",
      "metadata": {},
      "source": [
        "**2. Run the circuit**\n",
        "\n",
        "Calculate the function size for `sampler_pubs` on the selected backend, then pass the returned value to `perf_mgmt.run` through `function_size`. You can also specify the number of shots.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "12943c24",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Workload size: M\n"
          ]
        }
      ],
      "source": [
        "# Calculate the workload size for the selected backend\n",
        "sampler_size = calculate_function_size(sampler_pubs, backend)\n",
        "print(f\"Workload size: {sampler_size}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2595df84",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Run the circuit using Sampler\n",
        "qctrl_sampler_job = perf_mgmt.run(\n",
        "    primitive=\"sampler\",\n",
        "    pubs=sampler_pubs,\n",
        "    backend_name=backend.name,\n",
        "    function_size=sampler_size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3c49fbba",
      "metadata": {},
      "source": [
        "Check your quantum function workload's [status](/docs/ibm-quantum-platform/functions-get-started#check-job-status) or return [results](/docs/ibm-quantum-platform/functions-get-started#retrieve-results) as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 36,
      "id": "b7acbb7f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "d35c9efc-1542-461d-ae19-5485cab3fd80\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "'DONE'"
            ]
          },
          "execution_count": 36,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Print the ID so you can use it later, if necessary\n",
        "print(qctrl_sampler_job.job_id)\n",
        "\n",
        "qctrl_sampler_job.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "35921605",
      "metadata": {},
      "source": [
        "**3. Retrieve the result**\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 37,
      "id": "2d4f5f7d",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Retrieve the job results\n",
        "sampler_result = qctrl_sampler_job.result()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 38,
      "id": "7a359d99",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Counts for the meas output register (limited to 30 results):\n",
            "  11111111111111: 2715\n",
            "  11111101111111: 134\n",
            "  11111111110111: 102\n",
            "  11111011111111: 73\n",
            "  11111111111110: 66\n",
            "  00000000000111: 60\n",
            "  11111111111101: 59\n",
            "  11111110111111: 50\n",
            "  11110111111111: 48\n",
            "  11111111101111: 47\n",
            "  11111111011111: 34\n",
            "  11011111111111: 30\n",
            "  10111111111111: 27\n",
            "  00111111111111: 24\n",
            "  00011111111111: 23\n",
            "  01111111111111: 22\n",
            "  00000000010111: 20\n",
            "  00000001110111: 19\n",
            "  00000000000001: 18\n",
            "  11111110011111: 18\n",
            "  00000011111111: 16\n",
            "  11101111111111: 15\n",
            "  00000001111111: 14\n",
            "  00001011111111: 11\n",
            "  00000000111111: 11\n",
            "  00001111111111: 10\n",
            "  00000000000010: 9\n",
            "  00000000001111: 9\n",
            "  00000000000011: 8\n",
            "  01011111111111: 8\n",
            "  00000011110111: 8\n",
            "  10011111111111: 7\n",
            "  00000000011111: 7\n",
            "  00000000000000: 7\n",
            "  11111110000111: 6\n",
            "  11111011110111: 5\n",
            "  11111001111111: 5\n",
            "  01111011111111: 5\n",
            "  00000010000111: 5\n",
            "  11111111010111: 4\n",
            "  00000111111111: 4\n",
            "  00111101111111: 4\n",
            "  11111110010111: 4\n",
            "  11010111111111: 4\n",
            "  11111110110111: 4\n",
            "  01111111111101: 3\n",
            "  11110011111111: 3\n",
            "  11111110101111: 3\n",
            "  00000000000101: 3\n",
            "  11111101110111: 3\n",
            "  ... (195 more items)\n"
          ]
        }
      ],
      "source": [
        "# Get results for the first (and only) PUB\n",
        "pub_result = sampler_result[0]\n",
        "counts = pub_result.data.c.get_counts()\n",
        "\n",
        "print(\"Counts for the meas output register (limited to 30 results):\")\n",
        "for i, (bitstring, count) in enumerate(counts.items()):\n",
        "    if i >= 50:\n",
        "        print(f\"  ... ({len(counts) - 30} more items)\")\n",
        "        break\n",
        "    print(f\"  {bitstring}: {count}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d920922e",
      "metadata": {},
      "source": [
        "**3. Plot the top bitstrings**\n",
        "\n",
        "Plot the bitstring with the highest counts to see if the hidden bitstring was the mode.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 39,
      "id": "cefa2234",
      "metadata": {},
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "\n",
        "def plot_top_bitstrings(counts_dict, hidden_bitstring=None):\n",
        "    # Sort and take the top 100 bitstrings\n",
        "    top_100 = sorted(counts_dict.items(), key=lambda x: x[1], reverse=True)[\n",
        "        :100\n",
        "    ]\n",
        "    if not top_100:\n",
        "        print(\"No bitstrings found in the input dictionary.\")\n",
        "        return\n",
        "\n",
        "    # Unzip the bitstrings and their counts\n",
        "    bitstrings, counts = zip(*top_100)\n",
        "\n",
        "    # Assign colors: purple if the bitstring matches hidden_bitstring,\n",
        "    # otherwise gray\n",
        "    colors = [\n",
        "        \"#680CE9\" if bit == hidden_bitstring else \"gray\" for bit in bitstrings\n",
        "    ]\n",
        "\n",
        "    # Create the bar plot\n",
        "    plt.figure(figsize=(15, 8))\n",
        "    plt.bar(\n",
        "        range(len(bitstrings)), counts, tick_label=bitstrings, color=colors\n",
        "    )\n",
        "\n",
        "    # Rotate the bitstrings for better readability\n",
        "    plt.xticks(rotation=90, fontsize=8)\n",
        "    plt.xlabel(\"Bitstrings\")\n",
        "    plt.ylabel(\"Counts\")\n",
        "    plt.title(\"Top 100 Bitstrings by Counts\")\n",
        "\n",
        "    # Show the plot\n",
        "    plt.tight_layout()\n",
        "    plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1d9d3b69",
      "metadata": {},
      "source": [
        "The hidden bitstring is highlighted in purple, and it should be the bitstring with the highest number of counts.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 40,
      "id": "8106d906",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/functions/q-ctrl-performance-management/get-started/extracted-outputs/8106d906-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "plot_top_bitstrings(counts, hidden_bitstring)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "management-gs-next-steps",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Tune your workloads with [advanced techniques for Q-CTRL Performance Management](/docs/functions/q-ctrl-performance-management/performance-tuning).\n",
        "  * Visit the [API reference](/docs/functions/q-ctrl-performance-management/api-reference) for this quantum function.\n",
        "  * Try the [Transverse-Field Ising Model with Q-CTRL's Performance Management](/docs/tutorials/transverse-field-ising-model) tutorial.\n",
        "  * Try the [Quantum Phase Estimation with Q-CTRL's quantum functions](/docs/tutorials/quantum-phase-estimation-qctrl) tutorial.\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Review [Mundada P. S., et al. (2023). Experimental Benchmarking of an Automated Deterministic Error-Suppression Workflow for Quantum Algorithms. Physical Review Applied, 20, 2](https://quantum-journal.org/papers/q-2023-07-25-1067/).\n",
        "  * Review [Kanno, S., et al. (2025). Tensor-based quantum phase difference estimation for large-scale demonstration. arXiv preprint arXiv:2408.04946](https://arxiv.org/abs/2408.04946).\n",
        "  * Review [SoftBank Corp, Demonstration Experiment of a Communication Service Fault Diagnosis System Using Quantum Machine Learning (blog), 30 August, 2024](https://www.softbank.jp/en/corp/technology/research/topics/102/).\n",
        "  * Review [Yamauchi, H., et al. (2024). Parametrized Energy-Efficient Quantum Kernels for Network Service Fault Diagnosis. arXiv preprint arXiv:2405.09724v1](https://arxiv.org/abs/2405.09724v1).\n",
        "  * Review [Yamauchi, H., et al. (2025). Quantum spectroscopy of topological dynamics via a supersymmetric Hamiltonian. arXiv preprint arXiv:2511.23169v1](https://arxiv.org/abs/2511.23169v1).\n",
        "  * Review [Wang, Y., et al. (2025).  Δ-Motif: Subgraph Isomorphism at Scale via Data-Centric Parallelism. arXiv preprint arXiv:2508.21287](https://arxiv.org/abs/2508.21287).\n",
        "  * Review [Paterakis, N. G., et al. (2025).  Quantum Computing in the Computational Landscape of Power Electronics: Vision and Reality. arXiv preprint arXiv:2507.02577](https://arxiv.org/abs/2507.02577).\n",
        "  * Review [Gharibyan, H., et al. (2023).  Hierarchical Learning for Quantum ML: Novel Training Technique for Large-Scale Variational Quantum Circuits. arXiv preprint arXiv:2311.12929](https://arxiv.org/abs/2311.12929).\n",
        "  * Review the [Mitsubishi Chemical Corp case study](https://q-ctrl.com/case-study/unlocking-new-performance-capability-in-quantum-chemistry).\n",
        "  * Review the [Redacted bank case study](https://q-ctrl.com/case-study/reducing-quantum-compute-costs-2-500x-with-fire-opal).\n",
        "  * Review the [BlueQubit case study](https://q-ctrl.com/case-study/enabling-data-loading-for-quantum-machine-learning-with-fire-opal).\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
}