{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "797fe94d-93a3-4a7b-8d60-0706d5ab21d5",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"トランスパイラ設定を比較する\"\n",
        "description: \"回路の作成、トランスパイル、および提出という一連のプロセスを通じて、トランスパイル・パイプラインについて詳しく見ていきましょう。\"\n",
        "---\n",
        "\n",
        "<span id=\"compare-transpiler-settings\" />\n",
        "\n",
        "# トランスパイラ設定を比較する\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d403684a-9dc5-433b-a788-789881878d6c",
      "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": "a6affcc2-72f4-4f06-8c4c-fc52715b0285",
      "metadata": {},
      "source": [
        "トランスパイラの設定によって回路への最適化の方法が異なり、多くの場合、従来の処理時間が長くなるという代償を伴います。 このガイドでは、回路の作成、トランスパイル、および提出までの全プロセスを順を追って説明し、さまざまな設定におけるパフォーマンスのテスト方法をご紹介します。\n",
        "\n",
        "なお、同じ設定が、ある回路の性能を向上させる一方で、別の回路の性能を低下させる可能性があることに注意してください。 実際のハードウェア上で実行する前に、トランスパイルされた回路を必ず確認してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "39f9c961-c52d-46fc-a2aa-464462474b56",
      "metadata": {},
      "source": [
        "<span id=\"set-up-and-create-sample-circuit\" />\n",
        "\n",
        "## サンプル回路の設定と作成\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "790b4934-ae24-4e69-be9f-d82ae639a5e6",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Create circuit to test transpiler on\n",
        "from qiskit import QuantumCircuit\n",
        "from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager\n",
        "from qiskit.circuit.library import grover_operator, DiagonalGate\n",
        "\n",
        "# Use Statevector object to calculate the ideal output\n",
        "from qiskit.quantum_info import Statevector\n",
        "from qiskit.visualization import plot_histogram\n",
        "from qiskit.transpiler import PassManager\n",
        "\n",
        "from qiskit.circuit.library import XGate\n",
        "from qiskit.quantum_info import hellinger_fidelity"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fe0a4958-b406-4fe4-9415-38a772ad152c",
      "metadata": {},
      "source": [
        "トランスパイラが最適化を試みるための小さな回路を作成する。 この例は、状態をマークするオラクルを用いてグローバーの `111`アルゴリズムを実行する回路を作成する。 次に、後で比較するために理想的な分布（完璧な量子コンピュータで無限回実行した場合に測定されるであろう値）をシミュレートする。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "4ac958d4-b9b5-4939-a359-a9edca7ddb6a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/circuit-transpilation-settings/extracted-outputs/4ac958d4-b9b5-4939-a359-a9edca7ddb6a-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "oracle = DiagonalGate([1] * 7 + [-1])\n",
        "qc = QuantumCircuit(3)\n",
        "qc.h([0, 1, 2])\n",
        "qc = qc.compose(grover_operator(oracle))\n",
        "\n",
        "qc.draw(output=\"mpl\", style=\"iqp\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "6313186e-bc40-432e-9ada-8594d6a26d55",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/circuit-transpilation-settings/extracted-outputs/6313186e-bc40-432e-9ada-8594d6a26d55-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()\n",
        "\n",
        "plot_histogram(ideal_distribution)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "964ca1e0-d1c9-40ed-bcf1-babc50f847ed",
      "metadata": {},
      "source": [
        "<span id=\"transpile\" />\n",
        "\n",
        "## トランスパイル\n",
        "\n",
        "次に、QPU用の回路をトランスパイルします。 トランスパイラのパフォーマンスを、 `optimization_level` 設定値を `0` (最低) と `3` (最高) に設定した場合で比較します。 最適化の最低レベルでは、回路をデバイス上で動作させるために必要な最小限の処理のみを行います。具体的には、回路の量子ビットをデバイスの量子ビットにマッピングし、すべての2量子ビット操作を可能にするためにスワップゲートを追加します。 最高レベルの最適化ははるかに高度で、ゲート総数を削減するために多くの手法を用いる。 マルチ量子ビットゲートはエラー率が高く、量子ビットは時間の経過とともにデコヒーレンスを起こすため、回路が短いほどより良い結果が得られるはずである。\n",
        "\n",
        "<Admonition type=\"important\">\n",
        "  この例では IBM Quantum® ハードウェアを使用していますが、Qiskit対応のQPUであればどれでも試すことができます。  実際の結果は異なる場合があります。\n",
        "</Admonition>\n",
        "\n",
        "以下のセルは、 `optimization_level`の値がどちらの場合でも `qc` 、2量子ビットゲート数を出力し、トランスパイルされた回路をリストに追加する。 トランスパイラのアルゴリズムの一部はランダム化されているため、再現性を確保するためにシードを設定します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "61181ac0-3f89-417f-a31e-9430f63e670b",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Use IBM Quantum Compute Service to run jobs on hardware\n",
        "from qiskit_ibm_runtime import (\n",
        "    QiskitRuntimeService,\n",
        "    SamplerV2 as Sampler,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "c3062a60-1cdc-46e7-8eb3-efc62a1396bd",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'ibm_fez'"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Select the backend with the fewest number of jobs in the queue\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=127\n",
        ")\n",
        "backend.name"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "2a3ebe8c-e47d-4440-b004-f47f6af826f0",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Two-qubit gates (optimization_level=0):  21\n",
            "Two-qubit gates (optimization_level=3):  12\n"
          ]
        }
      ],
      "source": [
        "# Need to add measurements to the circuit\n",
        "qc.measure_all()\n",
        "\n",
        "# Find the correct two-qubit gate\n",
        "twoQ_gates = set([\"ecr\", \"cz\", \"cx\"])\n",
        "for gate in backend.basis_gates:\n",
        "    if gate in twoQ_gates:\n",
        "        twoQ_gate = gate\n",
        "\n",
        "circuits = []\n",
        "for optimization_level in [0, 3]:\n",
        "    pm = generate_preset_pass_manager(\n",
        "        optimization_level, backend=backend, seed_transpiler=0\n",
        "    )\n",
        "    t_qc = pm.run(qc)\n",
        "    print(\n",
        "        f\"Two-qubit gates (optimization_level={optimization_level}): \",\n",
        "        t_qc.count_ops()[twoQ_gate],\n",
        "    )\n",
        "    circuits.append(t_qc)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "99928d6b-a7e7-40c9-b59c-104fc430b57c",
      "metadata": {},
      "source": [
        "CNOTは通常エラー率が高いため、でトランスパイルされた回路は `optimization_level=3` はるかに優れた性能を発揮するはずである。\n",
        "\n",
        "パフォーマンスを向上させるもう一つの方法は、アイドル状態の量子ビットに一連のゲートを適用する「 [動的デカップリング](/docs/api/qiskit/qiskit.transpiler.passes.PadDynamicalDecoupling) 」です。 これにより、環境との望ましくない相互作用の一部が解消されます。 次のセルは、でトランスパイルされた回路に動 `optimization_level=3` 的なデカップリングを追加し、それをリストに追加します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "b20ebca3-4adb-4a95-9f6a-bb4cbd836daf",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_runtime.transpiler.passes.scheduling import (\n",
        "    ASAPScheduleAnalysis,\n",
        "    PadDynamicalDecoupling,\n",
        ")\n",
        "\n",
        "# Get gate durations so the transpiler knows how long each operation takes\n",
        "durations = backend.target.durations()\n",
        "\n",
        "# This is the sequence we'll apply to idling qubits\n",
        "dd_sequence = [XGate(), XGate()]\n",
        "\n",
        "# Run scheduling and dynamic decoupling passes on circuit\n",
        "pm = PassManager(\n",
        "    [\n",
        "        ASAPScheduleAnalysis(durations),\n",
        "        PadDynamicalDecoupling(durations, dd_sequence),\n",
        "    ]\n",
        ")\n",
        "circ_dd = pm.run(circuits[1])\n",
        "\n",
        "# Add this new circuit to our list\n",
        "circuits.append(circ_dd)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "c1c91fbd-acfe-413e-a6c9-ad97f4dd5543",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/circuit-transpilation-settings/extracted-outputs/c1c91fbd-acfe-413e-a6c9-ad97f4dd5543-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "circ_dd.draw(output=\"mpl\", style=\"iqp\", idle_wires=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5bcc75c7-8af0-4862-8e3c-ec4d06aed1f1",
      "metadata": {},
      "source": [
        "<span id=\"execute-the-circuit\" />\n",
        "\n",
        "## このコースを走破する\n",
        "\n",
        "これで、さまざまな設定でトランスパイルされた回路のリストが完成しました。 次に、Samplerプリミティブを使用してこれらの回路を実行し、結果を に保存します `result`。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "c1b36384-fd9b-4e24-a399-32d35fc6fa5b",
      "metadata": {},
      "outputs": [],
      "source": [
        "sampler = Sampler(backend)\n",
        "job = sampler.run(\n",
        "    [(circuit) for circuit in circuits],  # sample all three circuits\n",
        "    shots=8000,\n",
        ")\n",
        "result = job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c85b4da4-592f-45a6-87a2-a8f2d3415576",
      "metadata": {},
      "source": [
        "<span id=\"view-results\" />\n",
        "\n",
        "## 「結果の表示」\n",
        "\n",
        "最後に、装置の実測結果を理想分布と対比してプロットする。 ゲート数が少ないため、の `optimization_level=3` 結果は理想的な分布により近く、さらに動的デカップリングにより、 `optimization_level=3 + dd` の結果はさらに理想的な分布に近づいていることがわかります。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "9e86132d-a8b2-40db-af42-53042dfa108b",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/circuit-transpilation-settings/extracted-outputs/9e86132d-a8b2-40db-af42-53042dfa108b-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "binary_prob = [\n",
        "    {\n",
        "        k: v / res.data.meas.num_shots\n",
        "        for k, v in res.data.meas.get_counts().items()\n",
        "    }\n",
        "    for res in result\n",
        "]\n",
        "plot_histogram(\n",
        "    binary_prob + [ideal_distribution],\n",
        "    bar_labels=False,\n",
        "    legend=[\n",
        "        \"optimization_level=0\",\n",
        "        \"optimization_level=3\",\n",
        "        \"optimization_level=3 + dd\",\n",
        "        \"ideal distribution\",\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "47a9eec8-7b31-4b2d-a291-559ddfd7a36b",
      "metadata": {},
      "source": [
        "各結果セットと理想分布間の[ヘリンガー忠実度](/docs/api/qiskit/quantum_info)を計算することでこれを確認できます（値が高いほど良く、1が完全な忠実度です）。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "d2b5e797-176b-48b9-ac2b-ba73abe9300f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "0.774\n",
            "0.978\n",
            "0.979\n"
          ]
        }
      ],
      "source": [
        "for prob in binary_prob:\n",
        "    print(f\"{hellinger_fidelity(prob, ideal_distribution):.3f}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1b5b7bb9-eedb-45eb-a4cf-9b7708cbbb3e",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * 以下のような、高度なトランスパイルに関するリソースをいくつか紹介しましょう：\n",
        "\n",
        "    * [カスタム・トランスパイラー・パスを書く](/docs/guides/custom-transpiler-pass)\n",
        "    * [カスタムバックエンドに対してビルドおよびトランスパイルを行う](/docs/guides/custom-backend)\n",
        "    * [トランスパイラープラグインのインストールと使用](/docs/guides/transpiler-plugins)\n",
        "\n",
        "  * 利用可能な[チュートリアル](/docs/tutorials)をご覧ください。\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
}