{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "552b1077",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"最初の回路をハードウェアで実行する\"\n",
        "description: \"このHello World例で、 IBM Quantum ハードウェアを使ったQiskitの利用を始めましょう\"\n",
        "---\n",
        "\n",
        "<span id=\"run-your-first-circuit-on-hardware\" />\n",
        "\n",
        "# 最初の回路をハードウェアで実行する\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7cc19a86-a234-4220-bb4f-d66d3834e0c3",
      "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",
        "    qiskit-ibm-runtime~=0.47.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1a3c196d-545d-417f-b34e-fa422aa9a394",
      "metadata": {},
      "source": [
        "この例には二つの部分が含まれています。 まず、シンプルな「Hello world」量子プログラムを作成し、量子処理ユニット（QPU）上で実行します。  実際の量子研究にははるかに堅牢なプログラムが必要であるため、第2節（ [多数の量子ビットへの拡張](#scale-to-large-numbers-of-qubits) ）では、単純なプログラムを実用レベルまで拡張します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7b65f7e0",
      "metadata": {},
      "source": [
        "<span id=\"install-and-authenticate\" />\n",
        "\n",
        "## インストールして認証する\n",
        "\n",
        "1. Qiskitをまだインストールしていない場合は、 [クイックスタート](/docs/guides/quick-start)ガイドの手順を参照してください。\n",
        "\n",
        "   * IBM Quantum Computeクライアントをインストールして、量子ハードウェア上でジョブを実行します：\n",
        "\n",
        "     ```bash\n",
        "     pip install qiskit-ibm-runtime\n",
        "     ```\n",
        "\n",
        "   * ローカルでJupyterノートブックを実行する環境を設定する:\n",
        "\n",
        "     ```bash\n",
        "     pip install jupyter\n",
        "     ```\n",
        "\n",
        "2. 量子ハードウェアへのアクセス認証を、無料の [Open Plan](/docs/guides/plans-overview#open-plan) を通じて設定してください。\n",
        "\n",
        "   （アカウントへの招待メールを受け取った場合は、 [招待されたユーザー向けの手順](/docs/guides/cloud-setup-invited)に従ってください。）\n",
        "\n",
        "   * に [IBM Quantum Platform](/) アクセスしてログインするか、アカウントを作成してください。\n",
        "     <Admonition type=\"note\" title=\"重要\">\n",
        "       プロキシサーバー経由で接続する場合は、 v0.44.0 以降を使用する必要があります `qiskit-ibm-runtime` 。\n",
        "     </Admonition>\n",
        "\n",
        "   * [ダ](/)ッシュボードでAPIキー（ *API* トークンとも呼ばれます）を生成し、安全な場所にコピーしてください。\n",
        "\n",
        "   * [インスタンス](/instances)ページに移動し、使用するインスタンスを探してください。 そのCRNにカーソルを合わせてクリックするとコピーできます。\n",
        "\n",
        "   * このコードで認証情報をローカルに保存します:\n",
        "\n",
        "     ```python\n",
        "     from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "     QiskitRuntimeService.save_account(\n",
        "         # For `token`, use the 44-character API_KEY you created\n",
        "         # and saved from the IBM Quantum Platform Home dashboard\n",
        "         token=\"<your-api-key>\",\n",
        "         instance=\"<CRN>\", # Optional\n",
        "     )\n",
        "     ```\n",
        "\n",
        "3. これで、 IBM Quantum Compute Service への認証が必要なときはいつでも、この Python のコードを使用できるようになりました：\n",
        "   ```python\n",
        "   from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "   # Run every time you need the service\n",
        "   service = QiskitRuntimeService()\n",
        "   ```\n",
        "\n",
        "<Admonition type=\"info\" title=\"信頼された Python 環境を使用していませんか？\">\n",
        "  公共のコンピューターやその他の安全でない環境を使用している場合は、認証情報を安全に保つため、 [手動認証](/docs/guides/cloud-setup-untrusted)の手順に従ってください。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "80471a0a",
      "metadata": {},
      "source": [
        "<span id=\"create-and-run-a-simple-quantum-program\" />\n",
        "\n",
        "## 簡単な量子プログラムを作成して実行する\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "85fe979e",
      "metadata": {
        "raw_mimetype": "text/restructuredtext"
      },
      "source": [
        "Qiskitパターンを用いた量子プログラム作成の4つのステップは以下の通りです：\n",
        "\n",
        "1. 問題を量子ネイティブ形式にマッピングする。\n",
        "\n",
        "2. 回路と演算子を最適化する。\n",
        "\n",
        "3. 量子プリミティブ関数を使用して実行する。\n",
        "\n",
        "4. 結果を分析します。\n",
        "\n",
        "<span id=\"step-1-map-the-problem-to-a-quantum-native-format\" />\n",
        "\n",
        "### ステップ 1. 問題を量子ネイティブ形式にマッピングする\n",
        "\n",
        "量子プログラムにおいて、 *量子回路は*量子命令を表現する固有の形式であり、 *演算子は*測定対象となる観測量を表す。 回路を作成する際には、通常、新しい [`QuantumCircuit`](/docs/api/qiskit/qiskit.circuit.QuantumCircuit#quantumcircuit-class) オブジェクトを作成し、それに順序通りに命令を追加します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "21f7a26c",
      "metadata": {},
      "source": [
        "以下のコードセルは\\*、\\* 2つの量子ビットが互いに完全に絡み合った状態であるベル状態を生成する回路を作成します。\n",
        "\n",
        "<Admonition type=\"note\" title=\"注記: ビット順序\">\n",
        "  LSB 0 ビット番号付けを使用 Qiskit SDK し、第 0 桁 $n^{th}$ の値は $1 \\ll n$ 0 または 1 です。詳細については、「 $2^n$[ ビット順序](/docs/guides/bit-ordering) 」トピック Qiskit SDK を参照してください。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "930ca3b6",
      "metadata": {
        "tags": []
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/hello-world/extracted-outputs/930ca3b6-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit import QuantumCircuit\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "from qiskit_ibm_runtime import EstimatorOptions\n",
        "from qiskit_ibm_runtime import EstimatorV2 as Estimator\n",
        "from matplotlib import pyplot as plt\n",
        "# Uncomment the next line if you want to use a simulator:\n",
        "# from qiskit_ibm_runtime.fake_provider import FakeBelemV2\n",
        "\n",
        "\n",
        "# Create a new circuit with two qubits\n",
        "qc = QuantumCircuit(2)\n",
        "\n",
        "# Add a Hadamard gate to qubit 0\n",
        "qc.h(0)\n",
        "\n",
        "# Perform a controlled-X gate on qubit 1, controlled by qubit 0\n",
        "qc.cx(0, 1)\n",
        "\n",
        "# Return a drawing of the circuit using MatPlotLib (\"mpl\").\n",
        "# These guides are written by using Jupyter notebooks, which\n",
        "# display the output of the last line of each cell.\n",
        "# If you're running this in a script, use `print(qc.draw())` to\n",
        "# print a text drawing.\n",
        "qc.draw(\"mpl\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0c957de9",
      "metadata": {
        "raw_mimetype": "text/restructuredtext"
      },
      "source": [
        "利用可能なすべての操作については、ドキュメントを [`QuantumCircuit`](/docs/api/qiskit/qiskit.circuit.QuantumCircuit#quantumcircuit-class) 参照してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f3ef4248-7938-44c1-85f1-edc997f0edcd",
      "metadata": {},
      "source": [
        "量子回路を作成する際には、実行後にどのような形式のデータを返したいかについても考慮する必要があります。 Qiskit では、データを返す方法が 2 つ用意されています。測定対象として選択した一連の量子ビットのサンプリング出力を取得する方法と、観測量の期待値を取得する方法です。 プリミティブを使用して、以下の2つの方法のいずれかで回路を測定できるよう、作業環境を整えてください（詳細は[ステップ3](#step-3-execute-using-the-quantum-primitives) で説明します）。\n",
        "\n",
        "この例では、量子状態を変化させる作用や過程を表すために用いられる数学的対象である演算子を用いて指定されるサブ `qiskit.quantum_info` モジュールを使用し、期待値を測定する。 以下のコードセルは、6つの2量子ビットパウリ演算子を生成します： `IZ`, `IX`, `ZI` `XI`, `ZZ`,, および `XX`。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "c57b261c-b757-4432-beab-61b526c98a41",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "# Set up six different observables.\n",
        "\n",
        "observables_labels = [\"IZ\", \"IX\", \"ZI\", \"XI\", \"ZZ\", \"XX\"]\n",
        "observables = [SparsePauliOp(label) for label in observables_labels]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "47150779",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"演算子表記法\">\n",
        "  ここでは、演算 `ZZ` 子のようなものはテンソル積の省略形であり、これは量子ビット1と量子 $Z\\otimes Z$ ビット0に対して同時にZを測定し、量子ビット1と量子ビット0の相関に関する情報を得ることを意味する。 このような期待値は通常、. $\\langle Z_1 Z_0 \\rangle$ と表記される。\n",
        "\n",
        "  状態がもつれている場合、の測定結果はの測定結果 $\\langle Z_1 Z_0 \\rangle$ とは異なるはずである。上述の回路によって生成される特定のもつれた $\\langle I_1 \\otimes Z_0 \\rangle \\langle Z_1 \\otimes I_0 \\rangle$ 状態においては、の測定結果は $\\langle Z_1 Z_0 \\rangle$ 1となり、の測定結果は $\\langle I_1 \\otimes Z_0 \\rangle \\langle Z_1 \\otimes I_0 \\rangle$ 0となるはずである。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "83bf9151-3bc9-40d2-8615-31570238b08e",
      "metadata": {},
      "source": [
        "<span id=\"optimize\" />\n",
        "\n",
        "<span id=\"step-2-optimize-the-circuits-and-operators\" />\n",
        "\n",
        "### ステップ 2. 回路と演算子を最適化する\n",
        "\n",
        "デバイス上で回路を実行する際には、回路が含む命令セットを最適化し、回路の全体的な深さ（おおむね命令数に相当）を最小化することが重要である。 これにより、誤差やノイズの影響を低減することで、可能な限り最良の結果を得ることができます。 さらに、回路の命令はバックエンド[デバイ](/docs/guides/transpile#instruction-set-architecture)スの命令セットアーキテクチャ（ISA）に準拠し、デバイスの基本ゲートと量子ビットの接続性を考慮しなければならない。\n",
        "\n",
        "以下のコードは、ジョブを送信する実デバイスをインスタンス化し、回路と観測可能オブジェクトをそのバックエンドの命令セットアーキテクチャ（ISA）に適合するよう変換します。 既に[認証情報を保存している](/docs/guides/cloud-setup)必要があります\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "9a901271",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/hello-world/extracted-outputs/9a901271-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "service = QiskitRuntimeService()\n",
        "\n",
        "backend = service.least_busy(simulator=False, operational=True)\n",
        "\n",
        "# Convert to an ISA circuit and layout-mapped observables.\n",
        "pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n",
        "isa_circuit = pm.run(qc)\n",
        "\n",
        "isa_circuit.draw(\"mpl\", idle_wires=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9acac1d4",
      "metadata": {},
      "source": [
        "<span id=\"step-3-execute-using-the-quantum-primitives\" />\n",
        "\n",
        "### ステップ 3. 量子プリミティブを用いて実行する\n",
        "\n",
        "量子コンピュータはランダムな結果を生み出すため、通常は回路を何度も実行して出力のサンプルを収集します。 この `Estimator` クラスを使用することで、観測値の推定値を求めることができます。 `Estimator` は2つの[プリミティブ](/docs/guides/get-started-with-estimator)のうちの1つであり、もう1つは `Sampler`、量子コンピュータからデータを取得するために使用できる。  これらのオブジェクトは、 [プリミティブな統合ブロック（ PUB ）](/docs/guides/get-started-with-sampler) を使用して、回路、観測可能量、およびパラメータ（該当する場合）の選択を実行するメソッド `run()` を備えています。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "62c4ca44",
      "metadata": {
        "tags": []
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job ID: d9mqa588csec73fagtu0\n"
          ]
        }
      ],
      "source": [
        "# Construct the Estimator instance.\n",
        "\n",
        "estimator = Estimator(mode=backend)\n",
        "estimator.options.resilience_level = 1\n",
        "estimator.options.default_shots = 5000\n",
        "\n",
        "mapped_observables = [\n",
        "    observable.apply_layout(isa_circuit.layout) for observable in observables\n",
        "]\n",
        "\n",
        "# One pub, with one circuit to run against five different observables.\n",
        "job = estimator.run([(isa_circuit, mapped_observables)])\n",
        "\n",
        "# Use the job ID to retrieve your job data later\n",
        "print(f\">>> Job ID: {job.job_id()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "47479e76",
      "metadata": {},
      "source": [
        "ジョブを送信した後、現在のPythonインスタンス内でジョブが完了するまで待機するか、後でデータを取得するために `job_id` \\`\\`を使用できます。  （ [詳細はジョブの取得に関するセクション](/docs/guides/monitor-job#retrieve-job-results-at-a-later-time)を参照してください。）\n",
        "\n",
        "ジョブが完了した後、その出力をジョブの `result()` 属性を通じて確認してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "792d2f01",
      "metadata": {},
      "outputs": [],
      "source": [
        "# This is the result of the entire submission.  You submitted one Pub,\n",
        "# so this contains one inner result (and some metadata of its own).\n",
        "job_result = job.result()\n",
        "\n",
        "# This is the result from our single pub, which had six observables,\n",
        "# so contains information on all six.\n",
        "pub_result = job.result()[0]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "48317a25",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"代替案：シミュレータを使用して例を実行する\">\n",
        "  実際のデバイス上で量子プログラムを実行する場合、そのワークロードは実行されるまでキューで待機する必要があります。 時間を節約するために、代わりに以下のコードを使用して、 `qiskit-ibm-runtime` ローカルテストモード [`fake_provider`](/docs/api/qiskit-ibm-runtime/fake-provider) でこの小さなワークロードを実行することもできます。 なお、これは小規模な回路でのみ可能であることに留意してください。 次のセクションでスケールアップを行う際には、実機を使用する必要があります。\n",
        "\n",
        "  ```python\n",
        "\n",
        "  # Use the following code instead if you want to run on a simulator:\n",
        "\n",
        "  from qiskit_ibm_runtime.fake_provider import FakeBelemV2\n",
        "  backend = FakeBelemV2()\n",
        "  estimator = Estimator(backend)\n",
        "\n",
        "  # Convert to an ISA circuit and layout-mapped observables.\n",
        "\n",
        "  pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n",
        "  isa_circuit = pm.run(qc)\n",
        "  mapped_observables = [\n",
        "      observable.apply_layout(isa_circuit.layout) for observable in observables\n",
        "  ]\n",
        "\n",
        "  job = estimator.run([(isa_circuit, mapped_observables)])\n",
        "  result = job.result()\n",
        "\n",
        "  # This is the result of the entire submission. You submitted one Pub,\n",
        "  # so this contains one inner result (and some metadata of its own).\n",
        "\n",
        "  job_result = job.result()\n",
        "\n",
        "  # This is the result from our single pub, which had five observables,\n",
        "  # so contains information on all five.\n",
        "\n",
        "  pub_result = job.result()[0]\n",
        "  ```\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d200d1f8",
      "metadata": {},
      "source": [
        "<span id=\"step-4-analyze-the-results\" />\n",
        "\n",
        "### ステップ 4. 結果を分析する\n",
        "\n",
        "解析ステップでは通常、測定誤差の軽減やゼロノイズ外挿法（ZNE）などを使って結果の後処理を行う場合があります。 これらの結果を別のワークフローに投入してさらに分析したり、主要な値やデータのグラフを作成したりすることができます。 一般的に、このステップは問題ごとに異なります。  この例では、当回路で測定された期待値をそれぞれプロットする。\n",
        "\n",
        "Estimatorに指定した観測量の期待値と標準偏差は、ジョブ結果の `PubResult.data.evs` および `PubResult.data.stds` 属性を通じて取得できます。 Samplerから結果を取得するには、関数 `PubResult.data.meas.get_counts()` を使用します。この関数は、キーとしてビット列形式の測定値、対応する値としてカウント数を格納したハッシュテーブル `dict` を返します。 詳細については、『 [Sampler クイックスタート](/docs/guides/get-started-with-sampler)ガイド』をご覧ください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "87143fcc",
      "metadata": {
        "tags": []
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/hello-world/extracted-outputs/87143fcc-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Plot the result\n",
        "\n",
        "values = pub_result.data.evs\n",
        "\n",
        "errors = pub_result.data.stds\n",
        "\n",
        "# plotting graph\n",
        "plt.plot(observables_labels, values, \"-o\")\n",
        "plt.xlabel(\"Observables\")\n",
        "plt.ylabel(\"Values\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e6a9ba84",
      "metadata": {},
      "source": [
        "量子ビット0と1について、XとZの両方の独立した期待値は0である一方、相関（`XX` と `ZZ`）は1であることに注意せよ。 これは量子もつれの特徴である。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0bc582d8",
      "metadata": {},
      "source": [
        "<span id=\"scale-to-large-numbers-of-qubits\" />\n",
        "\n",
        "## 多数の量子ビットへの拡張\n",
        "\n",
        "量子コンピューティングにおいて、実用規模の作業は分野の進展に不可欠である。 このような作業には、はるかに大規模な計算が必要となる。100量子ビット以上、1000ゲート以上を使用する回路を扱うことになる。 この例は、100キュービットのGHZ状態を作成・解析することで、QPU IBM® 上で実用規模の作業をどのように達成できるかを示しています。  Qiskitのパターンワークフローを使用し、各量子ビットの期待 $\\langle Z_0 Z_i \\rangle $ 値を測定することで終了します。\n",
        "\n",
        "<span id=\"step-1-map-the-problem\" />\n",
        "\n",
        "### ステップ 1. 問題をマッピングする\n",
        "\n",
        "100 $n$ 量子ビットのGHZ状態を `QuantumCircuit` 準備する関数を記述し、その関数を使用して100量子ビットGHZ状態を準備し、測定対象となる観測量を収集する。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "2ac02692",
      "metadata": {},
      "outputs": [],
      "source": [
        "def get_qc_for_n_qubit_GHZ_state(n: int) -> QuantumCircuit:\n",
        "    \"\"\"This function will create a qiskit.QuantumCircuit (qc)\n",
        "        for an n-qubit GHZ state.\n",
        "\n",
        "    Args:\n",
        "        n (int): Number of qubits in the n-qubit GHZ state\n",
        "\n",
        "    Returns:\n",
        "        QuantumCircuit: Quantum circuit that generate the n-qubit GHZ state,\n",
        "            assuming all qubits start in the 0 state\n",
        "    \"\"\"\n",
        "    if isinstance(n, int) and n >= 2:\n",
        "        qc = QuantumCircuit(n)\n",
        "        qc.h(0)\n",
        "        for i in range(n - 1):\n",
        "            qc.cx(i, i + 1)\n",
        "    else:\n",
        "        raise Exception(\"n is not a valid input\")\n",
        "    return qc\n",
        "\n",
        "\n",
        "# Create a new circuit with 100 qubits in the GHZ state\n",
        "n = 100\n",
        "qc = get_qc_for_n_qubit_GHZ_state(n)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5b3d0d74",
      "metadata": {},
      "source": [
        "次に、関心のある演算子にマッピングします。 この例では、量子ビット間の `ZZ` 演算子を用いて、量子ビットが離れるにつれて生じる挙動を調べます。  遠隔の量子ビット間の期待値が次第に不正確（破損）になることで、存在するノイズのレベルが明らかになる。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "863a4ec9",
      "metadata": {},
      "outputs": [],
      "source": [
        "# ZZII...II, ZIZI...II, ... , ZIII...IZ\n",
        "operator_strings = [\n",
        "    \"Z\" + \"I\" * i + \"Z\" + \"I\" * (n - 2 - i) for i in range(n - 1)\n",
        "]\n",
        "\n",
        "operators = [SparsePauliOp(operator) for operator in operator_strings]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a0b462ce",
      "metadata": {},
      "source": [
        "<span id=\"step-2-optimize-the-problem-for-execution-on-quantum-hardware\" />\n",
        "\n",
        "### ステップ 2. 量子ハードウェア上での実行に向けて問題を最適化する\n",
        "\n",
        "以下のコードは、バックエンドのISAに適合させるため、回路と観測可能量を変換します。 既に[認証情報を保存している](/docs/guides/cloud-setup)必要があります\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "428f05e7",
      "metadata": {},
      "outputs": [],
      "source": [
        "service = QiskitRuntimeService()\n",
        "\n",
        "backend = service.least_busy(\n",
        "    simulator=False, operational=True, min_num_qubits=100\n",
        ")\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "\n",
        "isa_circuit = pm.run(qc)\n",
        "isa_operators_list = [op.apply_layout(isa_circuit.layout) for op in operators]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2d2b5065",
      "metadata": {},
      "source": [
        "<span id=\"step-3-execute-on-hardware\" />\n",
        "\n",
        "### ステップ 3. ハードウェア上で実行する\n",
        "\n",
        "ジョブを送信し、「 [動的デカップリング](/docs/api/qiskit-ibm-runtime/options-dynamical-decoupling-options)」 と呼ばれるエラー低減手法を用いて、エラーの抑制を有効にします。 回復力のレベルは、エラーに対してどの程度の回復力を構築すべきかを指定します。 レベルが高いほど、処理時間は長くなりますが、より正確な結果が得られます。  以下のコードで設定されているオプションの詳細については、「 [エラーの軽減および抑制手法](/docs/guides/error-mitigation-and-suppression-techniques)」 を参照してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "3aaa5025",
      "metadata": {},
      "outputs": [],
      "source": [
        "options = EstimatorOptions()\n",
        "options.resilience_level = 1\n",
        "options.dynamical_decoupling.enable = True\n",
        "options.dynamical_decoupling.sequence_type = \"XY4\"\n",
        "\n",
        "# Create an Estimator object\n",
        "estimator = Estimator(backend, options=options)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "b4c3d3e7-0a0f-4023-8948-1082e225f46c",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "d9mqnjmh4e6s738vioqg\n"
          ]
        }
      ],
      "source": [
        "# Submit the circuit to Estimator\n",
        "job = estimator.run([(isa_circuit, isa_operators_list)])\n",
        "job_id = job.job_id()\n",
        "print(job_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0bc64091",
      "metadata": {},
      "source": [
        "<span id=\"step-4-post-process-results\" />\n",
        "\n",
        "### ステップ 4. ポスト・プロセス結果\n",
        "\n",
        "ジョブ完了後、結果をプロットすると、 $i$ がの増加とともに減少 $\\langle Z_0 Z_i \\rangle$ することが確認できる。理想的なシミュレーションではすべてのが1となる $\\langle Z_0 Z_i \\rangle$ はずであるにもかかわらず。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "de91ebd0",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/hello-world/extracted-outputs/de91ebd0-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# data\n",
        "data = list(range(1, len(operators) + 1))  # Distance between the Z operators\n",
        "result = job.result()[0]\n",
        "values = result.data.evs  # Expectation value at each Z operator.\n",
        "values = [\n",
        "    v / values[0] for v in values\n",
        "]  # Normalize the expectation values to evaluate how they decay with distance.\n",
        "\n",
        "# plotting graph\n",
        "plt.plot(data, values, marker=\"o\", label=\"100-qubit GHZ state\")\n",
        "plt.xlabel(\"Distance between qubits $i$\")\n",
        "plt.ylabel(r\"$\\langle Z_i Z_0 \\rangle / \\langle Z_1 Z_0 \\rangle $\")\n",
        "plt.legend()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0afc307c",
      "metadata": {},
      "source": [
        "前の図は、量子ビット間の距離が増加するにつれて、ノイズの存在により信号が減衰することを示している。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e7c24c81",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * 以下のチュートリアルをお試しください：\n",
        "    * [量子汎用化（VQE）を用いたハイゼンベルグ鎖の基底状態エネルギー推定](/docs/tutorials/spin-chain-vqe)\n",
        "    * [QAOA](/docs/tutorials/quantum-approximate-optimization-algorithm) を用いて最適化問題を解く\n",
        "    * 機械学習タスク向けに[量子カーネル](/docs/tutorials/quantum-kernel-training)モデルを訓練する\n",
        "  * 詳細なインストール手順については[、Install Qiskit](/docs/guides/install-qiskit) ガイドを参照してください。\n",
        "  * ローカルにQiskitをインストールしたくない場合は、 [オンライン](/docs/guides/online-lab-environments)開発環境でQiskitを使用する方法についてご確認ください。\n",
        "  * 複数のアカウント認証情報を保存する場合や、その他のアカウントオプションを指定する場合は、「 [ログイン認証情報の保存](/docs/guides/save-credentials#save-your-access-credentials) 」ガイドの詳細な手順を参照してください。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "celltoolbar": "Raw Cell Format",
    "hours": 0.5,
    "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"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "state": {},
        "version_major": 2,
        "version_minor": 0
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}