{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "7e51aef7-70db-4772-a53f-100af6ad6902",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"Exemplos de estimadores\"\n",
        "description: \"Exemplos práticos de uso da primitiva Estimator do IBM Quantum.\"\n",
        "---\n",
        "\n",
        "<span id=\"estimator-examples\" />\n",
        "\n",
        "# Exemplos de estimadores\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "10cf3d45-503c-41c9-b0a1-51c23e32bc5f",
      "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=\"Versões do pacote\">\n",
        "    O código desta página foi desenvolvido com base nos seguintes requisitos.\n",
        "    Recomendamos usar essas versões ou versões mais recentes.\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.5.1\n",
        "    qiskit-ibm-runtime~=0.47.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a98beb8-d1df-4daf-80ce-d51e4dc31cfa",
      "metadata": {},
      "source": [
        "Os exemplos desta seção ilustram algumas formas comuns de usar o Estimator. Antes de executar estes exemplos, siga as instruções em [Instalar o Qiskit.](install-qiskit)\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  Todos esses exemplos utilizam as primitivas do tipo `IBM Quantum`, mas você também pode usar as primitivas básicas.\n",
        "</Admonition>\n",
        "\n",
        "Calcule e interprete com eficiência os valores esperados dos operadores quânticos necessários para muitos algoritmos com o Estimator. Explore as aplicações em modelagem molecular, aprendizado de máquina e problemas complexos de otimização.\n",
        "\n",
        "<span id=\"run-a-single-experiment\" />\n",
        "\n",
        "## Executar um único experimento\n",
        "\n",
        "Use o Estimador para determinar o valor esperado de um único par circuito-observável.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "6bc4a6a3-612e-4ad8-9fe3-3d56a4cb9a8f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " > Expectation value: -0.008839779005524863\n",
            " > Metadata: {'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32}\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "from qiskit.circuit.library import iqp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit.quantum_info import SparsePauliOp, random_hermitian\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator\n",
        "\n",
        "n_qubits = 50\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=n_qubits\n",
        ")\n",
        "\n",
        "mat = np.real(random_hermitian(n_qubits, seed=1234))\n",
        "circuit = iqp(mat)\n",
        "observable = SparsePauliOp(\"Z\" * 50)\n",
        "\n",
        "pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n",
        "isa_circuit = pm.run(circuit)\n",
        "isa_observable = observable.apply_layout(isa_circuit.layout)\n",
        "\n",
        "estimator = Estimator(mode=backend)\n",
        "job = estimator.run([(isa_circuit, isa_observable)])\n",
        "result = job.result()\n",
        "\n",
        "print(f\" > Expectation value: {result[0].data.evs}\")\n",
        "print(f\" > Metadata: {result[0].metadata}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c8594feb-0516-4cca-9064-232906b980a4",
      "metadata": {},
      "source": [
        "<span id=\"run-multiple-experiments-in-a-single-job\" />\n",
        "\n",
        "## Execute várias experiências em uma única tarefa\n",
        "\n",
        "Use o Estimator para determinar os valores esperados de vários pares de variáveis observáveis do circuito.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "662e73e9-8454-470a-b6aa-e84343005ca6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Expectation values for PUB 0: 0.9937888198757764\n",
            ">>> Standard errors for PUB 0: 1.7873718562576024\n",
            ">>> Expectation values for PUB 1: -0.1038961038961039\n",
            ">>> Standard errors for PUB 1: 1.3378580728628524\n",
            ">>> Expectation values for PUB 2: -0.6753246753246753\n",
            ">>> Standard errors for PUB 2: 1.7025095006727553\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "from qiskit.circuit.library import iqp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit.quantum_info import SparsePauliOp, random_hermitian\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator\n",
        "\n",
        "n_qubits = 50\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=n_qubits\n",
        ")\n",
        "\n",
        "rng = np.random.default_rng()\n",
        "mats = [np.real(random_hermitian(n_qubits, seed=rng)) for _ in range(3)]\n",
        "\n",
        "pubs = []\n",
        "circuits = [iqp(mat) for mat in mats]\n",
        "observables = [\n",
        "    SparsePauliOp(\"X\" * 50),\n",
        "    SparsePauliOp(\"Y\" * 50),\n",
        "    SparsePauliOp(\"Z\" * 50),\n",
        "]\n",
        "\n",
        "# Get ISA circuits\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "\n",
        "for qc, obs in zip(circuits, observables):\n",
        "    isa_circuit = pm.run(qc)\n",
        "    isa_obs = obs.apply_layout(isa_circuit.layout)\n",
        "    pubs.append((isa_circuit, isa_obs))\n",
        "\n",
        "estimator = Estimator(backend)\n",
        "job = estimator.run(pubs)\n",
        "job_result = job.result()\n",
        "\n",
        "for idx in range(len(pubs)):\n",
        "    pub_result = job_result[idx]\n",
        "    print(f\">>> Expectation values for PUB {idx}: {pub_result.data.evs}\")\n",
        "    print(f\">>> Standard errors for PUB {idx}: {pub_result.data.stds}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5176c806-e00d-4def-93b4-64216bf8cc64",
      "metadata": {},
      "source": [
        "<span id=\"run-parameterized-circuits\" />\n",
        "\n",
        "## Executar circuitos parametrizados\n",
        "\n",
        "Use o Estimator para executar três experimentos em uma única tarefa, aproveitando os valores dos parâmetros para aumentar a reutilização dos circuitos.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "3f991c86-8bcd-4d9e-bed1-a6a7ac0cabb6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Expectation values: [[ 9.89263974e-01  9.41062225e-01  7.87637085e-01  5.83548830e-01\n",
            "   3.06029826e-01 -7.99943914e-03 -3.11567899e-01 -5.91343155e-01\n",
            "  -8.05892215e-01 -9.36139493e-01 -9.88853746e-01 -9.42703136e-01\n",
            "  -8.10609833e-01 -5.90522700e-01 -3.15465062e-01 -5.94830090e-03\n",
            "   2.90851403e-01  5.85805082e-01  8.02200166e-01  9.41882681e-01\n",
            "   9.90494657e-01]\n",
            " [ 9.23012209e-03  3.12183240e-01  6.00163049e-01  8.02405280e-01\n",
            "   9.48446323e-01  9.84956584e-01  9.42703136e-01  8.05071760e-01\n",
            "   5.92984066e-01  3.07055395e-01 -3.07670736e-03 -3.18131541e-01\n",
            "  -5.60165854e-01 -7.94200727e-01 -9.43728705e-01 -9.91315112e-01\n",
            "  -9.39626428e-01 -8.03430849e-01 -5.79446553e-01 -3.04799143e-01\n",
            "  -4.92273178e-03]\n",
            " [ 8.20455297e-03 -3.00696866e-01 -5.99752822e-01 -8.11635402e-01\n",
            "  -9.45574729e-01 -9.92340681e-01 -9.40036656e-01 -8.00354142e-01\n",
            "  -5.82113033e-01 -2.90441175e-01  1.84602442e-03  3.24284956e-01\n",
            "   5.64883472e-01  8.04866646e-01  9.44138933e-01  9.93366250e-01\n",
            "   9.48651437e-01  7.87842199e-01  5.58730057e-01  3.16490631e-01\n",
            "  -6.97387002e-03]\n",
            " [ 9.91930454e-01  9.40446884e-01  7.89483109e-01  5.52986870e-01\n",
            "   2.97209931e-01  2.25625207e-03 -3.11567899e-01 -5.92984066e-01\n",
            "  -8.08353581e-01 -9.48036095e-01 -9.90699771e-01 -9.42498022e-01\n",
            "  -8.09584264e-01 -5.96265887e-01 -3.07055395e-01 -2.05113824e-04\n",
            "   3.02132663e-01  5.95240318e-01  7.93995613e-01  9.42703136e-01\n",
            "   9.93776478e-01]]\n",
            ">>> Standard errors: [[0.00312841 0.00403472 0.00759426 0.00833516 0.01030326 0.01122794\n",
            "  0.01128844 0.00813687 0.00865973 0.00513426 0.00345264 0.00388667\n",
            "  0.00736782 0.01026783 0.01038179 0.01246262 0.01191826 0.01081814\n",
            "  0.00850225 0.00496315 0.00269764]\n",
            " [0.01123964 0.01177892 0.00819503 0.0073663  0.00427303 0.00289125\n",
            "  0.00435623 0.0066848  0.01140235 0.00993107 0.00840459 0.00821741\n",
            "  0.0097656  0.0082026  0.00506637 0.00357209 0.0041762  0.00767615\n",
            "  0.00831383 0.01094546 0.01373803]\n",
            " [0.0121451  0.01227001 0.00831633 0.00691503 0.00385729 0.00267653\n",
            "  0.00454884 0.00722136 0.01080783 0.0098484  0.01141928 0.01035556\n",
            "  0.00804047 0.0058858  0.00398198 0.00281015 0.00501157 0.00714316\n",
            "  0.00954163 0.00878997 0.01213102]\n",
            " [0.00290704 0.0047878  0.00638958 0.00768626 0.00875767 0.00887984\n",
            "  0.01145493 0.00904896 0.00599187 0.00482709 0.00298048 0.00428419\n",
            "  0.00690245 0.00855953 0.00997334 0.00862447 0.00870133 0.00872892\n",
            "  0.00487633 0.00504538 0.00311229]]\n",
            ">>> Metadata: {'shots': 10016, 'target_precision': 0.01, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32}\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "\n",
        "from qiskit.circuit import QuantumCircuit, Parameter\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(operational=True, simulator=False)\n",
        "\n",
        "# Step 1: Map classical inputs to a quantum problem\n",
        "theta = Parameter(\"θ\")\n",
        "\n",
        "chsh_circuit = QuantumCircuit(2)\n",
        "chsh_circuit.h(0)\n",
        "chsh_circuit.cx(0, 1)\n",
        "chsh_circuit.ry(theta, 0)\n",
        "\n",
        "number_of_phases = 21\n",
        "phases = np.linspace(0, 2 * np.pi, number_of_phases)\n",
        "individual_phases = [[ph] for ph in phases]\n",
        "\n",
        "ZZ = SparsePauliOp.from_list([(\"ZZ\", 1)])\n",
        "ZX = SparsePauliOp.from_list([(\"ZX\", 1)])\n",
        "XZ = SparsePauliOp.from_list([(\"XZ\", 1)])\n",
        "XX = SparsePauliOp.from_list([(\"XX\", 1)])\n",
        "ops = [ZZ, ZX, XZ, XX]\n",
        "\n",
        "# Step 2: Optimize problem for quantum execution.\n",
        "\n",
        "pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n",
        "chsh_isa_circuit = pm.run(chsh_circuit)\n",
        "isa_observables = [\n",
        "    operator.apply_layout(chsh_isa_circuit.layout) for operator in ops\n",
        "]\n",
        "\n",
        "# Step 3: Execute using IBM Quantum primitives.\n",
        "\n",
        "# Reshape observable array for broadcasting\n",
        "reshaped_ops = np.fromiter(isa_observables, dtype=object)\n",
        "reshaped_ops = reshaped_ops.reshape((4, 1))\n",
        "\n",
        "estimator = Estimator(backend, options={\"default_shots\": int(1e4)})\n",
        "job = estimator.run([(chsh_isa_circuit, reshaped_ops, individual_phases)])\n",
        "# Get results for the first (and only) PUB\n",
        "pub_result = job.result()[0]\n",
        "print(f\">>> Expectation values: {pub_result.data.evs}\")\n",
        "print(f\">>> Standard errors: {pub_result.data.stds}\")\n",
        "print(f\">>> Metadata: {pub_result.metadata}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "117454c0-c8df-48cd-8503-f4fd137d6991",
      "metadata": {},
      "source": [
        "<span id=\"use-batches-and-advanced-options\" />\n",
        "\n",
        "## Use lotes e opções avançadas\n",
        "\n",
        "Explore o [modo de execução](/docs/guides/execution-modes) em lote e as opções avançadas para otimizar o desempenho dos circuitos nas QPUs.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "f009e993-98fe-451c-96f5-738153005543",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " > Expectation value: 0.025219391667376672\n",
            " > Metadata: {'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32}\n",
            " > Another Expectation value: 0.002376355265112134\n",
            " > More Metadata: {'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32}\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "from qiskit.circuit.library import iqp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit.quantum_info import SparsePauliOp, random_hermitian\n",
        "from qiskit_ibm_runtime import (\n",
        "    QiskitRuntimeService,\n",
        "    Batch,\n",
        "    EstimatorV2 as Estimator,\n",
        ")\n",
        "\n",
        "n_qubits = 15\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=n_qubits\n",
        ")\n",
        "\n",
        "rng = np.random.default_rng(1234)\n",
        "mat = np.real(random_hermitian(n_qubits, seed=rng))\n",
        "circuit = iqp(mat)\n",
        "mat = np.real(random_hermitian(n_qubits, seed=rng))\n",
        "another_circuit = iqp(mat)\n",
        "observable = SparsePauliOp(\"X\" * n_qubits)\n",
        "another_observable = SparsePauliOp(\"Y\" * n_qubits)\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "isa_circuit = pm.run(circuit)\n",
        "another_isa_circuit = pm.run(another_circuit)\n",
        "isa_observable = observable.apply_layout(isa_circuit.layout)\n",
        "another_isa_observable = another_observable.apply_layout(\n",
        "    another_isa_circuit.layout\n",
        ")\n",
        "\n",
        "# The context manager automatically closes the batch.\n",
        "with Batch(backend=backend) as batch:\n",
        "    estimator = Estimator(mode=batch)\n",
        "\n",
        "    estimator.options.resilience_level = 1\n",
        "\n",
        "    job = estimator.run([(isa_circuit, isa_observable)])\n",
        "    another_job = estimator.run(\n",
        "        [(another_isa_circuit, another_isa_observable)]\n",
        "    )\n",
        "    result = job.result()\n",
        "    another_result = another_job.result()\n",
        "\n",
        "    # first job\n",
        "    print(f\" > Expectation value: {result[0].data.evs}\")\n",
        "    print(f\" > Metadata: {result[0].metadata}\")\n",
        "\n",
        "    # second job\n",
        "    print(f\" > Another Expectation value: {another_result[0].data.evs}\")\n",
        "    print(f\" > More Metadata: {another_result[0].metadata}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e207719d-da1b-4af2-ae63-4cb033865a1b",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## Próximas etapas\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recomendações\">\n",
        "  * [Especifique opções avançadas de tempo de execução](runtime-options-overview).\n",
        "  * Pratique com primitivas seguindo a [lição](/learning/courses/variational-algorithm-design/cost-functions) sobre a função `Cost` em IBM Quantum® Learning.\n",
        "  * Saiba como fazer a transpilagem localmente na seção [Transpilagem](/docs/guides/transpile/).\n",
        "  * Consulte o guia [de comparação de configurações do transpiler](/docs/guides/circuit-transpilation-settings).\n",
        "  * Entenda os [limites da tarefa](/docs/guides/job-limits) ao enviar uma tarefa para uma QPU do IBM®.\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
}