{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "1fd07edc-2356-49d3-bf35-6e4e1256b61b",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"Entradas y salidas del sampler\"\n",
        "description: \"Comprender el formato de entrada y salida de las primitivas de Sampler\"\n",
        "---\n",
        "\n",
        "<span id=\"sampler-inputs-and-outputs\" />\n",
        "\n",
        "# Entradas y salidas del sampler\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fcd633c9-366b-440f-8997-7c60692e5a4d",
      "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=\"Versiones del paquete\">\n",
        "    El código de esta página se ha desarrollado teniendo en cuenta los siguientes requisitos.\n",
        "    Recomendamos utilizar estas versiones o posteriores.\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.5.0\n",
        "    qiskit-ibm-runtime~=0.47.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "672f7038-64e7-42cc-9936-c30a03596791",
      "metadata": {},
      "source": [
        "Esta página ofrece una descripción general de las entradas y salidas de la primitiva « Qiskit Runtime Sampler», que ejecuta cargas de trabajo en recursos de computación de IBM Quantum®. Sampler te permite definir de forma eficiente cargas de trabajo vectorizadas mediante el uso de una estructura de datos conocida como [**« PUB » ()**](/docs/guides/primitive-input-output#pubs). Se utilizan como entradas para el [`run()`](/docs/api/qiskit-ibm-runtime/sampler-v2#run) método de la primitiva Sampler, que ejecuta la carga de trabajo definida como un trabajo. A continuación, una vez finalizado el trabajo, los resultados se devuelven en un formato que depende tanto de los PUB utilizados como de las opciones de ejecución especificadas en la primitiva.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0115445a-d695-4806-8a9a-6bcd2451e418",
      "metadata": {},
      "source": [
        "<span id=\"inputs\" />\n",
        "\n",
        "## Entradas\n",
        "\n",
        "Cada archivo « PUB » tiene el siguiente formato:\n",
        "\n",
        "(`<single circuit>`, `<one or more optional parameter value>`, `<optional shots>`),\n",
        "\n",
        "Puede haber varios `parameter values` elementos, y cada uno de ellos puede ser una matriz o un único parámetro, dependiendo del circuito elegido. Además, la entrada debe contener medidas.\n",
        "\n",
        "En el caso de la primitiva «Sampler», un « PUB » puede contener como máximo tres valores:\n",
        "\n",
        "* Un único \\*circuito \\*`QuantumCircuit`, que puede contener uno o más [`Parameter`](/docs/api/qiskit/qiskit.circuit.Parameter) objetos\n",
        "  Nota: Estos circuitos también deben incluir instrucciones de medición para cada uno de los qubits que se vayan a muestrear.\n",
        "* Un conjunto de valores de parámetros para vincular el circuito a $\\theta_k$ (solo es necesario si se utilizan `Parameter` objetos que deban vincularse en tiempo de ejecución)\n",
        "* (Opcionalmente) un número de disparos para medir el circuito\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f2314472-55e7-4f31-824e-31b18179e18d",
      "metadata": {},
      "source": [
        "***\n",
        "\n",
        "El siguiente código muestra un conjunto de entradas vectorizadas para la `Sampler` primitiva y las ejecuta en un backend de IBM® como un único `RuntimeJobV2 ` objeto.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "21687f88-51fc-4139-91b0-3fb4542716ca",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit.circuit import (\n",
        "    Parameter,\n",
        "    QuantumCircuit,\n",
        "    ClassicalRegister,\n",
        "    QuantumRegister,\n",
        ")\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit.primitives.containers import BitArray\n",
        "\n",
        "from qiskit_ibm_runtime import (\n",
        "    QiskitRuntimeService,\n",
        "    SamplerV2 as Sampler,\n",
        ")\n",
        "\n",
        "import numpy as np\n",
        "\n",
        "# Instantiate runtime service and get\n",
        "# the least busy backend\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(operational=True, simulator=False)\n",
        "\n",
        "# Define a circuit with two parameters.\n",
        "circuit = QuantumCircuit(2)\n",
        "circuit.h(0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.ry(Parameter(\"a\"), 0)\n",
        "circuit.rz(Parameter(\"b\"), 0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.h(0)\n",
        "circuit.measure_all()\n",
        "\n",
        "# Transpile the circuit\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "transpiled_circuit = pm.run(circuit)\n",
        "layout = transpiled_circuit.layout\n",
        "\n",
        "# Now define a sweep over parameter values, the last axis of dimension 2 is\n",
        "# for the two parameters \"a\" and \"b\"\n",
        "params = np.vstack(\n",
        "    [\n",
        "        np.linspace(-np.pi, np.pi, 100),\n",
        "        np.linspace(-4 * np.pi, 4 * np.pi, 100),\n",
        "    ]\n",
        ").T\n",
        "\n",
        "sampler_pub = (transpiled_circuit, params)\n",
        "\n",
        "# Instantiate the new Sampler object, then run the transpiled circuit\n",
        "# using the set of parameters and observables.\n",
        "sampler = Sampler(mode=backend)\n",
        "job = sampler.run([sampler_pub])\n",
        "result = job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9f1a6c43-a00c-421f-b11d-62d3237f1ccb",
      "metadata": {},
      "source": [
        "<span id=\"outputs\" />\n",
        "\n",
        "## Resultados\n",
        "\n",
        "Una vez que se envían uno o varios PUB a una QPU para su ejecución y un trabajo se completa con éxito, los datos se devuelven como un objeto [`PrimitiveResult`](/docs/api/qiskit/qiskit.primitives.PrimitiveResult) contenedor al que se accede llamando al `RuntimeJobV2.result()` método. El objeto `PrimitiveResult` contiene una lista iterable de [`SamplerPubResult`](/docs/api/qiskit/qiskit.primitives.SamplerPubResult) objetos que recogen los resultados de la ejecución de cada `PUB`. Estos datos son muestras de la salida del circuito.\n",
        "\n",
        "Cada elemento de esta lista corresponde a un objeto `PUB` enviado al método de la `run()` primitiva (por ejemplo, un trabajo enviado con 20 PUB devolverá un `PrimitiveResult` objeto que contiene una lista de 20 `SamplerPubResult` objetos, uno correspondiente a cada objeto `PUB`).\n",
        "\n",
        "Cada `SamplerPubResult` objeto posee un atributo `data` y un `metadata` atributo.\n",
        "\n",
        "* El `data` atributo es un campo personalizado [`DataBin`](/docs/api/qiskit/qiskit.primitives.DataBin) que contiene los valores de medición reales, las desviaciones estándar, etc. Los contenedores de datos son objetos similares a diccionarios que contienen uno `BitArray` por `ClassicalRegister` cada elemento del circuito.\n",
        "* La `BitArray` clase es un contenedor de datos de tomas ordenados. Almacena las cadenas de bits muestreadas como bytes en una matriz bidimensional. El eje situado más a la izquierda de esta matriz recorre las tomas ordenadas, mientras que el eje situado más a la derecha recorre los bytes.\n",
        "* El `metadata` atributo contiene información sobre las opciones de ejecución utilizadas (que se explican más adelante en la sección [«Metadatos del resultado»](#result-metadata) de esta página).\n",
        "\n",
        "A continuación se muestra un esquema visual de la estructura `PrimitiveResult` de datos:\n",
        "\n",
        "```\n",
        "    └── PrimitiveResult\n",
        "        ├── SamplerPubResult[0]\n",
        "        │   ├── metadata\n",
        "        │   └── data  ## In the form of a DataBin object\n",
        "        │       ├── NAME_OF_CLASSICAL_REGISTER\n",
        "        │       │   └── BitArray of count data (default is 'meas')\n",
        "        |       |\n",
        "        │       └── NAME_OF_ANOTHER_CLASSICAL_REGISTER\n",
        "        │           └── BitArray of count data (exists only if more than one\n",
        "        |                 ClassicalRegister was specified in the circuit)\n",
        "        ├── SamplerPubResult[1]\n",
        "        |   ├── metadata\n",
        "        |   └── data  ## In the form of a DataBin object\n",
        "        |       └── NAME_OF_CLASSICAL_REGISTER\n",
        "        |           └── BitArray of count data for second pub\n",
        "        ├── ...\n",
        "        ├── ...\n",
        "        └── ...\n",
        "```\n",
        "\n",
        "En pocas palabras, una tarea devuelve un [`PrimitiveResult`](/docs/api/qiskit/qiskit.primitives.PrimitiveResult) objeto y contiene una lista de uno o más [`SamplerPubResult`](/docs/api/qiskit/qiskit.primitives.SamplerPubResult) objetos. A continuación, estos `SamplerPubResult` objetos almacenan los datos de medición de cada « PUB » que se haya enviado al trabajo.\n",
        "\n",
        "Como primer ejemplo, veamos el siguiente circuito de diez qubits:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "e42b2fd8-0790-4a38-9082-f2334440e411",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Databin: DataBin(meas=BitArray(<shape=(), num_shots=4096, num_bits=10>))\n",
            "\n",
            "BitArray: BitArray(<shape=(), num_shots=4096, num_bits=10>)\n",
            "\n",
            "The shape of register `meas` is (4096, 2).\n",
            "\n",
            "The bytes in register `alpha`, shot by shot:\n",
            "[[  0   0]\n",
            " [  0   0]\n",
            " [  3 255]\n",
            " ...\n",
            " [  0   0]\n",
            " [  3 255]\n",
            " [  3 239]]\n",
            "\n"
          ]
        }
      ],
      "source": [
        "# generate a ten-qubit GHZ circuit\n",
        "circuit = QuantumCircuit(10)\n",
        "circuit.h(0)\n",
        "circuit.cx(range(0, 9), range(1, 10))\n",
        "\n",
        "# append measurements with the `measure_all` method\n",
        "circuit.measure_all()\n",
        "\n",
        "# transpile the circuit\n",
        "transpiled_circuit = pm.run(circuit)\n",
        "\n",
        "# run the Sampler job and retrieve the results\n",
        "sampler = Sampler(mode=backend)\n",
        "job = sampler.run([transpiled_circuit])\n",
        "result = job.result()\n",
        "\n",
        "# the data bin contains one BitArray\n",
        "data = result[0].data\n",
        "print(f\"Databin: {data}\\n\")\n",
        "\n",
        "# to access the BitArray, use the key \"meas\", which is the default name of\n",
        "# the classical register when this is added by the `measure_all` method\n",
        "array = data.meas\n",
        "print(f\"BitArray: {array}\\n\")\n",
        "print(f\"The shape of register `meas` is {data.meas.array.shape}.\\n\")\n",
        "print(f\"The bytes in register `alpha`, shot by shot:\\n{data.meas.array}\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5926adf1-c7db-425a-a5cf-cb97eb5fa389",
      "metadata": {},
      "source": [
        "A veces puede resultar conveniente convertir los datos del formato de bytes en cadenas `BitArray` de bits. El `get_count` método devuelve un diccionario que asocia cadenas de bits con el número de veces que han aparecido.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "b4eb01c9-d438-46ca-9057-4e91b7656748",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Counts: {'0000000000': 1817, '1111111111': 1652, '0011111111': 19, '0000011111': 6, '0010000111': 1, '0001011111': 2, '1111111100': 12, '1111110111': 24, '0010000000': 49, '0001111111': 42, '0000110000': 2, '1111101111': 34, '1111001111': 1, '1111000000': 14, '1011111111': 27, '0000001111': 14, '1000000000': 41, '0000000111': 10, '1111111011': 11, '1111111000': 15, '0000111111': 25, '0000000011': 9, '1111111110': 31, '1111100000': 8, '1100000000': 8, '0100000000': 12, '0111111111': 34, '1110000000': 54, '0000010000': 3, '1111111101': 20, '0111101011': 1, '0000001011': 1, '0001000000': 4, '0000000001': 12, '1010000000': 1, '1101111000': 1, '1011011111': 1, '0010000001': 1, '1111110000': 3, '1110111111': 8, '0000001000': 5, '0011000000': 1, '0010111111': 1, '0000100000': 5, '0001111100': 1, '1111011111': 14, '1111100111': 1, '0000001110': 3, '0001111011': 1, '0001110000': 2, '0000111110': 1, '0000101111': 1, '1101111111': 4, '1011110111': 1, '0000000100': 3, '0111111011': 1, '0110111111': 1, '1100111111': 1, '1100000001': 1, '1001111111': 2, '0011101111': 1, '1111101101': 1, '1111111010': 1, '0110000000': 3, '1110011111': 1, '0000001101': 1, '0001110111': 1, '1111101000': 1, '1000000001': 1, '1000111111': 1, '0001100000': 1, '1011101111': 1, '0111110111': 1, '0000000010': 1}\n"
          ]
        }
      ],
      "source": [
        "# optionally, convert away from the native BitArray format to a dictionary format\n",
        "counts = data.meas.get_counts()\n",
        "print(f\"Counts: {counts}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e186d055-09e7-421c-8d70-0d27e7d0edaa",
      "metadata": {},
      "source": [
        "Cuando un circuito contiene más de un registro clásico, los resultados se almacenan en diferentes `BitArray` objetos. El siguiente ejemplo modifica el fragmento anterior dividiendo el registro clásico en dos registros distintos:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "e81d87ce-2fd6-4498-a9a5-f3432209fccd",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "BitArray for register 'alpha': BitArray(<shape=(), num_shots=4096, num_bits=1>)\n",
            "BitArray for register 'beta': BitArray(<shape=(), num_shots=4096, num_bits=9>)\n"
          ]
        }
      ],
      "source": [
        "# generate a ten-qubit GHZ circuit with two classical registers\n",
        "circuit = QuantumCircuit(\n",
        "    qreg := QuantumRegister(10),\n",
        "    alpha := ClassicalRegister(1, \"alpha\"),\n",
        "    beta := ClassicalRegister(9, \"beta\"),\n",
        ")\n",
        "circuit.h(0)\n",
        "circuit.cx(range(0, 9), range(1, 10))\n",
        "\n",
        "# append measurements with the `measure_all` method\n",
        "circuit.measure([0], alpha)\n",
        "circuit.measure(range(1, 10), beta)\n",
        "\n",
        "# transpile the circuit\n",
        "transpiled_circuit = pm.run(circuit)\n",
        "\n",
        "# run the Sampler job and retrieve the results\n",
        "sampler = Sampler(mode=backend)\n",
        "job = sampler.run([transpiled_circuit])\n",
        "result = job.result()\n",
        "\n",
        "# the data bin contains two BitArrays, one per register, and can be accessed\n",
        "# as attributes using the registers' names\n",
        "data = result[0].data\n",
        "print(f\"BitArray for register 'alpha': {data.alpha}\")\n",
        "print(f\"BitArray for register 'beta': {data.beta}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d93dd9f5-cc43-41b0-b350-f545a14d1f38",
      "metadata": {},
      "source": [
        "<span id=\"use-bitarray-objects-for-performant-post-processing\" />\n",
        "\n",
        "### Utiliza `BitArray` objetos para un posprocesamiento eficaz\n",
        "\n",
        "Dado que las matrices suelen ofrecer un mejor rendimiento que los diccionarios, es recomendable realizar cualquier procesamiento posterior directamente sobre los `BitArray` objetos, en lugar de sobre los diccionarios de recuentos. La `BitArray` clase ofrece una serie de métodos para realizar algunas operaciones habituales de posprocesamiento:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "6465d11b-9e5b-4078-a1be-75229297093a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The shape of register `alpha` is (4096, 1).\n",
            "The bytes in register `alpha`, shot by shot:\n",
            "[[1]\n",
            " [1]\n",
            " [1]\n",
            " ...\n",
            " [1]\n",
            " [1]\n",
            " [0]]\n",
            "\n",
            "The shape of register `beta` is (4096, 2).\n",
            "The bytes in register `beta`, shot by shot:\n",
            "[[  1 255]\n",
            " [  1 255]\n",
            " [  1 254]\n",
            " ...\n",
            " [  1 255]\n",
            " [  1 255]\n",
            " [  0   0]]\n",
            "\n",
            "The shape of `beta` after post-selection is (0, 2).\n",
            "The bytes in `beta` after post-selection:\n",
            "[]\n",
            "The shape of `beta` after bit-wise slicing is (4096, 1).\n",
            "The bytes in `beta` after bit-wise slicing:\n",
            "[[7]\n",
            " [7]\n",
            " [6]\n",
            " ...\n",
            " [7]\n",
            " [7]\n",
            " [0]]\n",
            "\n",
            "The shape of `beta` after shot-wise slicing is (5, 2).\n",
            "The bytes in `beta` after shot-wise slicing:\n",
            "[[  1 255]\n",
            " [  1 255]\n",
            " [  1 254]\n",
            " [  1 255]\n",
            " [  1 240]]\n",
            "\n",
            "Exp. val. for observable `SparsePauliOp(['ZZZZZZZZZ'],\n",
            "              coeffs=[1.+0.j])` is: 0.07568359375\n",
            "Exp. val. for observable `SparsePauliOp(['IIIIIIIIZ'],\n",
            "              coeffs=[1.+0.j])` is: 0.0322265625\n",
            "\n",
            "The shape of the merged results is (4096, 2).\n",
            "The bytes of the merged results:\n",
            "[[  3 255]\n",
            " [  3 255]\n",
            " [  3 253]\n",
            " ...\n",
            " [  3 255]\n",
            " [  3 255]\n",
            " [  0   0]]\n",
            "\n"
          ]
        }
      ],
      "source": [
        "print(f\"The shape of register `alpha` is {data.alpha.array.shape}.\")\n",
        "print(f\"The bytes in register `alpha`, shot by shot:\\n{data.alpha.array}\\n\")\n",
        "\n",
        "print(f\"The shape of register `beta` is {data.beta.array.shape}.\")\n",
        "print(f\"The bytes in register `beta`, shot by shot:\\n{data.beta.array}\\n\")\n",
        "\n",
        "# post-select the bitstrings of `beta` based on having sampled \"1\" in `alpha`\n",
        "mask = data.alpha.array == \"0b1\"\n",
        "ps_beta = data.beta[mask[:, 0]]\n",
        "print(f\"The shape of `beta` after post-selection is {ps_beta.array.shape}.\")\n",
        "print(f\"The bytes in `beta` after post-selection:\\n{ps_beta.array}\")\n",
        "\n",
        "# get a slice of `beta` to retrieve the first three bits\n",
        "beta_sl_bits = data.beta.slice_bits([0, 1, 2])\n",
        "print(\n",
        "    f\"The shape of `beta` after bit-wise slicing is {beta_sl_bits.array.shape}.\"\n",
        ")\n",
        "print(f\"The bytes in `beta` after bit-wise slicing:\\n{beta_sl_bits.array}\\n\")\n",
        "\n",
        "# get a slice of `beta` to retrieve the bytes of the first five shots\n",
        "beta_sl_shots = data.beta.slice_shots([0, 1, 2, 3, 4])\n",
        "print(\n",
        "    f\"The shape of `beta` after shot-wise slicing is {beta_sl_shots.array.shape}.\"\n",
        ")\n",
        "print(\n",
        "    f\"The bytes in `beta` after shot-wise slicing:\\n{beta_sl_shots.array}\\n\"\n",
        ")\n",
        "\n",
        "# calculate the expectation value of diagonal operators on `beta`\n",
        "ops = [SparsePauliOp(\"ZZZZZZZZZ\"), SparsePauliOp(\"IIIIIIIIZ\")]\n",
        "exp_vals = data.beta.expectation_values(ops)\n",
        "for o, e in zip(ops, exp_vals):\n",
        "    print(f\"Exp. val. for observable `{o}` is: {e}\")\n",
        "\n",
        "# concatenate the bitstrings in `alpha` and `beta` to \"merge\" the results of the two\n",
        "# registers\n",
        "merged_results = BitArray.concatenate_bits([data.alpha, data.beta])\n",
        "print(f\"\\nThe shape of the merged results is {merged_results.array.shape}.\")\n",
        "print(f\"The bytes of the merged results:\\n{merged_results.array}\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b3765ba4-ffaa-4f51-a657-1fdfb588b849",
      "metadata": {},
      "source": [
        "<span id=\"result-metadata\" />\n",
        "\n",
        "## Metadatos del resultado\n",
        "\n",
        "Además de los resultados de la ejecución, tanto el objeto `PrimitiveResult` como `SamplerPubResult` el contienen un atributo de metadatos sobre el trabajo que se envió. Los metadatos que contienen información sobre todos los PUB enviados (como las distintas [opciones de tiempo de ejecución](/docs/api/qiskit-ibm-runtime/options) disponibles) se encuentran en el `PrimitiveResult.metatada`, mientras que los metadatos específicos de cada PUB se encuentran en `SamplerPubResult.metadata`.\n",
        "\n",
        "Los metadatos de los resultados del Sampler también incluyen información sobre la duración de la ejecución, denominada [*«intervalo*](#execution-spans) de ejecución».\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  En el campo de metadatos, las implementaciones de primitivas pueden devolver cualquier información sobre la ejecución que les resulte relevante, y no hay pares clave-valor garantizados por la primitiva base. Por lo tanto, los metadatos devueltos pueden variar según la implementación de la primitiva.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "9a40d177-917b-484a-a809-44554efcee28",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The metadata of the PrimitiveResult is:\n",
            "'execution' : {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-07-15 08:42:24', stop='2026-07-15 08:42:26', size=4096>)])},\n",
            "'version' : 2,\n",
            "\n",
            "The metadata of the PubResult result is:\n",
            "'circuit_metadata' : {},\n"
          ]
        }
      ],
      "source": [
        "# Print out the results metadata\n",
        "print(\"The metadata of the PrimitiveResult is:\")\n",
        "for key, val in result.metadata.items():\n",
        "    print(f\"'{key}' : {val},\")\n",
        "\n",
        "print(\"\\nThe metadata of the PubResult result is:\")\n",
        "for key, val in result[0].metadata.items():\n",
        "    print(f\"'{key}' : {val},\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "403dd006-33ec-4bd6-ad45-857535857077",
      "metadata": {},
      "source": [
        "<span id=\"execution-spans\" />\n",
        "\n",
        "<span id=\"view-execution-spans\" />\n",
        "\n",
        "### Ver intervalos de ejecución\n",
        "\n",
        "Los resultados de [`SamplerV2`](/docs/api/qiskit-ibm-runtime/sampler-v2) los trabajos ejecutados en Qiskit Runtime incluyen información sobre los tiempos de ejecución en sus metadatos.\n",
        "Esta información temporal puede utilizarse para establecer los límites superior e inferior de las marcas de tiempo en las que se ejecutaron determinadas operaciones en la QPU.\n",
        "Las tomas se agrupan en [`ExecutionSpan`](/docs/api/qiskit-ibm-runtime/execution-span-execution-span) objetos, cada uno de los cuales indica una hora de inicio, una hora de finalización y una especificación de las tomas que se recopilaron en ese intervalo.\n",
        "\n",
        "Un intervalo de ejecución especifica qué datos se ejecutaron durante su ventana mediante un [`ExecutionSpan.mask`](/docs/api/qiskit-ibm-runtime/execution-span-execution-span#mask) método. Este método, dado cualquier índice [de bloque unificado primitivo ( PUB )](/docs/guides/primitive-input-output#pubs), devuelve una máscara booleana que es `True` para todas las tomas ejecutadas durante su ventana. Los PUB se indexan según el orden en que se pasaron a la llamada de ejecución del Sampler. Si, por ejemplo, una máscara de « PUB » tiene la forma `(2, 3)` y se ha ejecutado con cuatro disparos, entonces la forma de la máscara es `(2, 3, 4)`. Consulte la página de la API [de execution\\_span](/docs/api/qiskit-ibm-runtime/execution-span) para obtener más información.\n",
        "\n",
        "Para consultar la información sobre el intervalo de ejecución, revisa los metadatos del resultado devuelto por `SamplerV2`, que se presenta en forma de un `ExecutionSpans` objeto. Este objeto es un contenedor similar a una lista que contiene instancias de subclases de `ExecutionSpan`, como `SliceSpan`.\n",
        "\n",
        "Ejemplo:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "480e553c-2e53-40ca-bafd-e350f173cbcc",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ExecutionSpans([DoubleSliceSpan(<start='2026-07-15 08:43:57', stop='2026-07-15 08:43:58', size=24>)])\n"
          ]
        }
      ],
      "source": [
        "# Define two circuits, each with one parameter with two parameters.\n",
        "circuit = QuantumCircuit(2)\n",
        "circuit.h(0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.ry(Parameter(\"a\"), 0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.h(0)\n",
        "circuit.measure_all()\n",
        "\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "transpiled_circuit = pm.run(circuit)\n",
        "\n",
        "params = np.random.uniform(size=(2, 3)).T\n",
        "\n",
        "sampler_pub = (transpiled_circuit, params)\n",
        "\n",
        "# Instantiate the new Estimator object, then run the transpiled circuit\n",
        "# using the set of parameters and observables.\n",
        "\n",
        "job = sampler.run([sampler_pub], shots=4)\n",
        "\n",
        "result = job.result()\n",
        "spans = job.result().metadata[\"execution\"][\"execution_spans\"]\n",
        "print(spans)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "092fedcc-c4ac-4841-9846-f77b9ec90d2e",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit.primitives import BitArray\n",
        "\n",
        "# Get the mask of the 1st PUB for the 0th span.\n",
        "mask = spans[0].mask(0)\n",
        "\n",
        "# Decide whether the 0th shot of parameter set (1, 2) occurred in this span.\n",
        "in_this_span = mask[2, 1, 0]\n",
        "\n",
        "# Create a new bit array containing only the PUB-1 data collected during this span.\n",
        "bits = result[0].data.meas\n",
        "filtered_data = BitArray(bits.array[mask], bits.num_bits)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2ba13f59-c804-4e3b-85c9-90f26cb68e92",
      "metadata": {},
      "source": [
        "Los intervalos de ejecución se pueden filtrar para incluir información relativa a PUB específicos, seleccionados por sus índices:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "53dec6a3-57b9-41b0-8ebd-28c6257dd10e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "ExecutionSpans([DoubleSliceSpan(<start='2026-07-15 08:43:57', stop='2026-07-15 08:43:58', size=24>)])"
            ]
          },
          "execution_count": 9,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# take the subset of spans that reference data in PUBs 0 or 2\n",
        "spans.filter_by_pub([0, 2])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4f635472-60a9-4729-9880-5581fb3806f2",
      "metadata": {},
      "source": [
        "Ver información general sobre el conjunto de intervalos de ejecución:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "ba4aa14d-4182-47bf-93a6-df607fd82594",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Number of execution spans: 1\n",
            "  Start of the first span: 2026-07-15 08:43:57.312863\n",
            "     End of the last span: 2026-07-15 08:43:58.426676\n",
            "       Total duration (s): 1.113813\n"
          ]
        }
      ],
      "source": [
        "print(\"Number of execution spans:\", len(spans))\n",
        "print(\"  Start of the first span:\", spans.start)\n",
        "print(\"     End of the last span:\", spans.stop)\n",
        "print(\"       Total duration (s):\", spans.duration)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1392fbc0-0792-402c-9568-160313ab76c4",
      "metadata": {},
      "source": [
        "Extraer y examinar un tramo concreto:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "077a74ad-2780-4c61-8310-a4821efbfa68",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " Start of first span: 2026-07-15 08:43:57.312863\n",
            "   End of first span: 2026-07-15 08:43:58.426676\n",
            "#shots in first span: 24\n"
          ]
        }
      ],
      "source": [
        "spans.sort()\n",
        "print(\" Start of first span:\", spans[0].start)\n",
        "print(\"   End of first span:\", spans[0].stop)\n",
        "print(\"#shots in first span:\", spans[0].size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "924e26ed-ece0-42ef-a985-ae1aaea86622",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\">\n",
        "  Es posible que los intervalos de tiempo especificados por distintos periodos de ejecución se solapen. Esto no se debe a que una QPU estuviera realizando varias ejecuciones a la vez, sino que se trata de un efecto secundario de ciertos procesos clásicos que pueden tener lugar simultáneamente con la ejecución cuántica. Lo que se garantiza es que los datos a los que se hace referencia se produjeron efectivamente durante el intervalo de ejecución indicado, pero no necesariamente que los límites de ese intervalo sean lo más precisos posible.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "celltoolbar": "Raw Cell Format",
    "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
}