{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "008d2ceb-f6fa-42f6-a7df-6bd604775278",
      "metadata": {},
      "source": [
        "---\n",
        "title: Sampler quickstart\n",
        "description: How to use the Sampler primitive in Qiskit Runtime.\n",
        "---\n",
        "\n",
        "# Sampler quickstart\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b7e96291-0925-4d7f-81a8-a7738549477c",
      "metadata": {},
      "source": [
        "The Sampler's core task is sampling the output register from the execution of one or more quantum circuits. [Dynamic circuits](/docs/guides/execute-dynamic-circuits) and parameterized circuits are accepted as input (if parametrized circuits are submitted, the parameter values must also be provided). Sampler also supports built-in dynamical decoupling and twirling for [error suppression](/docs/guides/error-mitigation-and-suppression-techniques).\n",
        "\n",
        "The steps in this topic describe how to set up Sampler, explore the options you can use to configure it, and invoke it in a program.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "818a2b3d-3950-4a28-8e37-39959c56484b",
      "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.4.0\n",
        "    qiskit-ibm-runtime~=0.46.1\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "64e2e09f-8528-4088-897b-1529b451ab1e",
      "metadata": {},
      "source": [
        "## Steps to use the Sampler primitive\n",
        "\n",
        "### 1. Initialize the account\n",
        "\n",
        "Because Qiskit Runtime is a managed service, you first need to initialize your account. You can then select the QPU you want to use to calculate the expectation value.\n",
        "\n",
        "Follow the steps in the [Set up your IBM Cloud account](/docs/guides/cloud-setup) topic if you don't already have an account set up.\n",
        "\n",
        "<Admonition type=\"note\" title=\"Fractional gates\">\n",
        "  To use the newly supported [fractional gates](/docs/guides/fractional-gates), set `use_fractional_gates=True` when requesting a backend from a `QiskitRuntimeService` instance. For example:\n",
        "\n",
        "  ```python\n",
        "  service = QiskitRuntimeService()\n",
        "  fractional_gate_backend = service.least_busy(use_fractional_gates=True)\n",
        "  ```\n",
        "\n",
        "  This is an experimental feature and might change in the future.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "b40504d7-aee5-4b30-98b1-265e70bece8d",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=127\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73374fbc-d3b6-4d2d-84c6-edf85b43ea25",
      "metadata": {},
      "source": [
        "### 2. Create a circuit\n",
        "\n",
        "You need at least one circuit as the input to the Sampler primitive.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "dfe23a34-2ea9-48af-bd1d-c7e3185aa80c",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from qiskit.circuit.library import efficient_su2\n",
        "\n",
        "circuit = efficient_su2(127, entanglement=\"linear\")\n",
        "circuit.measure_all()\n",
        "# The circuit is parametrized, so we will define the parameter values for execution\n",
        "param_values = np.random.rand(circuit.num_parameters)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6cf08ef6-34d3-42e6-8cb3-391b60217289",
      "metadata": {},
      "source": [
        "The circuit and observable need to be transformed to only use instructions supported by the QPU (referred to as *instruction set architecture (ISA)* circuits). Use the transpiler to do this.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "062bd89b-b13e-46d0-96b6-6c84b2131415",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Circuit ops (ISA): OrderedDict([('rz', 3036), ('sx', 1769), ('cz', 378), ('measure', 127), ('barrier', 1)])\n"
          ]
        }
      ],
      "source": [
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "isa_circuit = pm.run(circuit)\n",
        "print(f\">>> Circuit ops (ISA): {isa_circuit.count_ops()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "cf0f2c0a-8574-45c6-a43b-1a99eac81279",
      "metadata": {},
      "source": [
        "### 3. Initialize the Qiskit Runtime Sampler\n",
        "\n",
        "When you initialize Sampler, use the `mode` parameter to specify the mode you want it to run in.  Possible values are `batch`, `session`, or `backend` objects for batch, session, and job execution mode, respectively. For more information, see [Introduction to Qiskit Runtime execution modes.](execution-modes) Note that Open Plan users cannot submit session jobs.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "a2b80dca-dff8-49f9-8154-e2cb0b768507",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_runtime import SamplerV2 as Sampler\n",
        "\n",
        "sampler = Sampler(mode=backend)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f35972bf-17d3-40be-852b-9e56615c7c3c",
      "metadata": {},
      "source": [
        "### 4. Invoke Sampler and get results\n",
        "\n",
        "Next, invoke the `run()` method to generate the output. The circuit and optional parameter value sets are input as *primitive unified bloc* (PUB) tuples.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "e52e6a96-dc23-4f76-8152-b54514a99dfb",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job ID: d82863mgbeec73alf9sg\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job Status: QUEUED\n"
          ]
        }
      ],
      "source": [
        "job = sampler.run([(isa_circuit, param_values)])\n",
        "print(f\">>> Job ID: {job.job_id()}\")\n",
        "print(f\">>> Job Status: {job.status()}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "4543fac5-abdc-4440-a1a2-d32aabe135d6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "First ten results for the 'meas' output register: ['1100110011001011111111111010000010001010100100011000001011001101000110011000110100100100101010111001110100100000000011111100000', '0101001001010000100111000110110001001101010110110000110111101110001100000001000001111111101110000000010011111100100110001101000', '0111111110011011000011110111010111101100110010001010010001100000000100000000001010101010111010110000001100100001010110000101000', '0000110011001100110011101100000111011001110100001100001100110111010100101010001010000011000111001010101111110110100110001010000', '0011110011100001100110111001000011011111011110111100000110001000111011101101000110011011101011001110110000010010001100100011001', '1010001000010101011100101010101001101000100010011011100110010111010001110111110010100010111010011010110011001101100110010000010', '0001110010001011001100010000000001001101001110101100110011101111100100100110110010101000011010101000101011101011010100000101010', '1110100100001100110010000010011010111000001010110010111111011010010100110011100101110011101111100001010011100110011000101001001', '1101011100110101011001010100011001110100001011110101101110111011011001100110001011000010001100100011000000110101011100111111000', '1101000110000000101010000000110000011000000000010110011001001000001110101110010111011010101100011000100100110000000000000011001']\n"
          ]
        }
      ],
      "source": [
        "result = job.result()\n",
        "\n",
        "# Get results for the first (and only) PUB\n",
        "pub_result = result[0]\n",
        "print(\n",
        "    f\"First ten results for the 'meas' output register: {pub_result.data.meas.get_bitstrings()[:10]}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d38dd409-e0d8-4749-bb22-58ae9a53d26a",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Learn how to [test locally](local-testing-mode) before running on quantum computers.\n",
        "  * Review detailed [examples](sampler-examples).\n",
        "  * Practice with primitives by working through the [Cost function lesson](/learning/courses/variational-algorithm-design/cost-functions) in IBM Quantum Learning.\n",
        "  * Learn how to transpile locally in the [Transpile](transpile/) section.\n",
        "  * Try the [Compare transpiler settings](/docs/guides/circuit-transpilation-settings#compare-transpiler-settings) guide.\n",
        "  * Learn how to [use the primitive options](/docs/guides/runtime-options-overview).\n",
        "  * View the API for [Sampler](/docs/api/qiskit-ibm-runtime/options-sampler-options) options.\n",
        "  * Read [Migrate to V2 primitives](/docs/guides/v2-primitives).\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": 4
}