{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "008d2ceb-f6fa-42f6-a7df-6bd604775278",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with the Sampler primitive\n",
        "description: How to use the Sampler primitive in Qiskit Runtime.\n",
        "---\n",
        "\n",
        "# Get started with the Sampler primitive\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",
        "<details>\n",
        "  <summary><b>Package versions</b></summary>\n",
        "\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.0\n",
        "  qiskit-ibm-runtime~=0.43.1\n",
        "  ```\n",
        "</details>\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": 7,
      "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": 8,
      "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": 9,
      "id": "062bd89b-b13e-46d0-96b6-6c84b2131415",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Circuit ops (ISA): OrderedDict([('sx', 3089), ('rz', 3036), ('cz', 1092), ('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": 10,
      "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": 11,
      "id": "e52e6a96-dc23-4f76-8152-b54514a99dfb",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job ID: d5k96rsjt3vs73ds5tig\n",
            ">>> 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": 12,
      "id": "4543fac5-abdc-4440-a1a2-d32aabe135d6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "First ten results for the 'meas' output register: ['0101001101010000011001110001011000010010001100001000100110011111011110000010110001101000110011101010000100011011000110101111000', '0100111000000100110001100100000101111000111001101000110111101110110010010100001101001111001010011101010000010011000110000010001', '0101111101111111010011010101000000110100000010000010011101100011100011001100000100100001000101000000100001010101010011001101100', '1100110101111111001110010000010100101010101010001000001100100110011111010000000010001000110111010000010101100000100000110111001', '0010000001111001111010100100010111101000101000100000101100001000011100000100011010110110100011100110001001110110111101010011000', '0101110000001000100100010010100100111000010100000000010010000000010110010010000110000001110110010100000111001110100100111101100', '0100011111101001000111110011011101101101110101110001010111011101111110011101001000000001110000011110000101010000001010000100000', '0001010101011000110100000100111111100001011000111110000011000111001101010000010001001100000110000000100000110101010010101110010', '0100011010001110011110000110100101100100101001001111010100100101010100010000000010100000101010110010000000001000010101011111110', '0000011000000111000001000101111111110110101100110000001100010010011101011100001010000100011010001010001101000000000000010001001']\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
}