{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "7e6b2936-3a18-4917-9c47-30e2d4ce5775",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"結果の可視化\"\n",
        "description: \"Qiskitを使用して量子回路の実行結果をプロットする\"\n",
        "---\n",
        "\n",
        "<span id=\"visualize-results\" />\n",
        "\n",
        "# 結果の可視化\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "06a4399f-bca6-4c2e-9128-1494017d0249",
      "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=\"パッケージ・バージョン\">\n",
        "    このページのコードは、以下の要件に基づいて開発された。\n",
        "    これらのバージョンまたは新しいバージョンの使用をお勧めします。\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.5.1\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8d0138c-fd97-49c2-88a5-1929a5a09258",
      "metadata": {},
      "source": [
        "<span id=\"plot-histogram\" />\n",
        "\n",
        "## プロットヒストグラム\n",
        "\n",
        "`plot_histogram` 、QPU上で量子回路をサンプリングした結果を可視化する機能。\n",
        "\n",
        "<Admonition title=\"関数からの出力の使用\" type=\"tip\">\n",
        "  この関数は `matplotlib.Figure` オブジェクトを返す。 コード・セルの最終行がこれらのオブジェクトを出力すると、Jupyterノートブックはセルの下にそれらを表示する。 他の環境やスクリプトでこれらの関数を呼び出す場合は、明示的に出力を表示または保存する必要があります。\n",
        "\n",
        "  選択肢は2つある：\n",
        "\n",
        "  * 返されたオブジェクトに対して `.show()` を呼び出し、画像を新しいウィンドウで開きます（設定されている matplotlib バックエンドが対話型であると仮定します）。\n",
        "  * `.savefig(\"out.png\")` を呼び出し、現在の作業ディレクトリの `out.png` に図を保存する。 `savefig()` メソッドはパスを取るので、出力を保存する場所とファイル名を調整できる。 例えば、`plot_state_city(psi).savefig(\"out.png\")`です。\n",
        "</Admonition>\n",
        "\n",
        "例えば、2量子ビットのベル状態を作る：\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "5cf67f92-a86d-496d-9e13-0d8a841c8dfa",
      "metadata": {
        "tags": [
          "ignore-warnings"
        ]
      },
      "outputs": [],
      "source": [
        "from qiskit.primitives import StatevectorSampler as Sampler\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "\n",
        "from qiskit.circuit import QuantumCircuit\n",
        "from qiskit.visualization import plot_histogram"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "938e8206-d7e8-447d-b798-b7c2507f8901",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(), num_shots=1024, num_bits=2>)), metadata={'shots': 1024, 'circuit_metadata': {}})], metadata={'version': 2})\n"
          ]
        }
      ],
      "source": [
        "# Quantum circuit to make a Bell state\n",
        "bell = QuantumCircuit(2)\n",
        "bell.h(0)\n",
        "bell.cx(0, 1)\n",
        "bell.measure_all()\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1)\n",
        "isa_circuit = pm.run(bell)\n",
        "\n",
        "# execute the quantum circuit\n",
        "sampler = Sampler()\n",
        "job = sampler.run([isa_circuit])\n",
        "result = job.result()\n",
        "\n",
        "print(result)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "57d8053e-d030-460d-9c1f-772e53b1a49b",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-results/extracted-outputs/57d8053e-d030-460d-9c1f-772e53b1a49b-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "plot_histogram(result[0].data.meas.get_counts())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e3a68e3d-21e6-45a0-bc40-f9a2214dd5b3",
      "metadata": {},
      "source": [
        "<span id=\"options-when-plotting-a-histogram\" />\n",
        "\n",
        "### ヒストグラム作成時のオプション\n",
        "\n",
        "`plot_histogram` 、以下のオプションを使用して出力グラフを調整する。\n",
        "\n",
        "* `legend`:実行のラベルを提供する。 各実行結果のラベルに使われる文字列のリストを取る。 これは、複数の実行結果を同じヒストグラムにプロットするときに便利です\n",
        "* `sort`:ヒストグラムのバーの順序を調整します。 で昇順、 `asc` で降順に設定できます。 `desc`\n",
        "* `number_to_keep`:表示する項の数を整数で指定する。 残りは \"rest \"と呼ばれる1本の小節にまとめられている\n",
        "* `color`:バーの色を調整します。各実行でバーに使用する色を文字列または文字列のリストで指定します\n",
        "* `bar_labels`:ラベルをバーの上に印刷するかどうかを調整します\n",
        "* `figsize`:出力数字を作るためにインチ単位のサイズのタプルを取る\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "bd70e13f-5c52-42fb-8dde-980b15e3604a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-results/extracted-outputs/bd70e13f-5c52-42fb-8dde-980b15e3604a-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Execute two-qubit Bell state again\n",
        "\n",
        "job = sampler.run([isa_circuit], shots=1000)\n",
        "second_result = job.result()\n",
        "\n",
        "# Plot results with custom options\n",
        "plot_histogram(\n",
        "    [\n",
        "        result[0].data.meas.get_counts(),\n",
        "        second_result[0].data.meas.get_counts(),\n",
        "    ],\n",
        "    legend=[\"first\", \"second\"],\n",
        "    sort=\"desc\",\n",
        "    figsize=(15, 12),\n",
        "    color=[\"orange\", \"black\"],\n",
        "    bar_labels=False,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "019ee04e-0730-4536-94cc-7e2b50d921e1",
      "metadata": {},
      "source": [
        "<span id=\"plot-estimator-results\" />\n",
        "\n",
        "## プロット推定結果\n",
        "\n",
        "QiskitにはEstimatorの結果をプロットする機能は内蔵されていませんが、 Matplotlib 'の [`bar` プロットを使って](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html)素早く視覚化することができます。\n",
        "\n",
        "次のセルは、量子状態上の7つの異なる観測量の期待値を推定します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "17c9893a-d1bf-4726-b444-6dce1d56805f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "PubResult(data=DataBin(evs=np.ndarray(<shape=(7, 1), dtype=float64>), stds=np.ndarray(<shape=(7, 1), dtype=float64>), shape=(7, 1)), metadata={'target_precision': 0.0, 'circuit_metadata': {}})\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<BarContainer object of 7 artists>"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-results/extracted-outputs/17c9893a-d1bf-4726-b444-6dce1d56805f-2.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import numpy as np\n",
        "from qiskit import QuantumCircuit\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit.primitives import StatevectorEstimator as Estimator\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from matplotlib import pyplot as plt\n",
        "\n",
        "# Simple estimation experiment to create results\n",
        "qc = QuantumCircuit(2)\n",
        "qc.h(0)\n",
        "qc.crx(1.5, 0, 1)\n",
        "\n",
        "observables_labels = [\"ZZ\", \"XX\", \"YZ\", \"ZY\", \"XY\", \"XZ\", \"ZX\"]\n",
        "observables = [SparsePauliOp(label) for label in observables_labels]\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1)\n",
        "isa_circuit = pm.run(qc)\n",
        "isa_observables = [\n",
        "    operator.apply_layout(isa_circuit.layout) for operator in observables\n",
        "]\n",
        "\n",
        "# Reshape observable array for broadcasting\n",
        "reshaped_ops = np.fromiter(isa_observables, dtype=object)\n",
        "reshaped_ops = reshaped_ops.reshape((7, 1))\n",
        "\n",
        "estimator = Estimator()\n",
        "job = estimator.run([(isa_circuit, reshaped_ops)])\n",
        "result = job.result()[0]\n",
        "exp_val = job.result()[0].data.evs\n",
        "print(result)\n",
        "\n",
        "# Since the result array is structured as a 2D array where each element is a\n",
        "# list containing a single value, you need to flatten the array.\n",
        "\n",
        "# Plot using Matplotlib\n",
        "plt.bar(observables_labels, exp_val.flatten())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a520f049-c2ee-4f14-8039-b5be671f25ae",
      "metadata": {},
      "source": [
        "以下のセルでは、各結果の推定[標準誤差を](https://en.wikipedia.org/wiki/Standard_error)使用し、エラーバーとして加えている。 プロットの完全な説明については、 [`bar` プロットのドキュメントを](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html)参照してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "4eb79f4b-36b5-4797-a1a0-67d881d46ca4",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "Text(0.5, 1.0, 'Expectation values (with standard errors)')"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-results/extracted-outputs/4eb79f4b-36b5-4797-a1a0-67d881d46ca4-1.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "standard_error = job.result()[0].data.stds\n",
        "\n",
        "_, ax = plt.subplots()\n",
        "ax.bar(\n",
        "    observables_labels,\n",
        "    exp_val.flatten(),\n",
        "    yerr=standard_error.flatten(),\n",
        "    capsize=2,\n",
        ")\n",
        "ax.set_title(\"Expectation values (with standard errors)\")"
      ]
    },
    {
      "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
}