{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "7ed4867f",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"深さ削減のための回路切断\"\n",
        "description: \"量子回路のゲートを削減して回路深さを減らすためのQiskitパターンを構築する。\"\n",
        "---\n",
        "\n",
        "<span id=\"circuit-cutting-for-depth-reduction\" />\n",
        "\n",
        "# 深さ削減のための回路切断\n",
        "\n",
        "*使用時間の目安イーグルプロセッサーで8分（注：あくまでも目安です。 ランタイムは異なるかもしれない)。*\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "387c5e80",
      "metadata": {},
      "source": [
        "<span id=\"background\" />\n",
        "\n",
        "## 背景\n",
        "\n",
        "このチュートリアルでは、量子回路のゲートを切断して回路の深さを減らすための `Qiskit pattern` 。 回路切断に関するより詳細な議論については、 [回路切断Qiskitアドオンのドキュメントを](https://qiskit.github.io/qiskit-addon-cutting/)ご覧ください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a62460d9",
      "metadata": {},
      "source": [
        "<span id=\"requirements\" />\n",
        "\n",
        "## 要件\n",
        "\n",
        "このチュートリアルを始める前に、以下のものがインストールされていることを確認してください：\n",
        "\n",
        "* Qiskit SDK v2.0 またはそれ以降、 [可視化](/docs/api/qiskit/visualization)サポート付き\n",
        "* Qiskit Runtime v0.22 またはそれ以降 (`pip install qiskit-ibm-runtime`)\n",
        "* 回路切断 Qiskit アドオン v0.9.0 以降 (`pip install qiskit-addon-cutting`)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a89fe306",
      "metadata": {},
      "source": [
        "<span id=\"setup\" />\n",
        "\n",
        "## セットアップ\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "c795c670",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "from qiskit.circuit.library import EfficientSU2\n",
        "from qiskit.quantum_info import PauliList, Statevector, SparsePauliOp\n",
        "from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager\n",
        "\n",
        "from qiskit_addon_cutting import (\n",
        "    cut_gates,\n",
        "    generate_cutting_experiments,\n",
        "    reconstruct_expectation_values,\n",
        ")\n",
        "\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "07f7f75d",
      "metadata": {},
      "source": [
        "<span id=\"step-1-map-classical-inputs-to-a-quantum-problem\" />\n",
        "\n",
        "## ステップ1：古典的な入力を量子問題にマッピングする\n",
        "\n",
        "[ドキュメントに](/docs/guides/intro-to-patterns)概説されている4つのステップを使用して、Qiskitパターンを実装します。 この場合、スワップ・ゲートになるゲートをカットし、より浅い回路でサブ実験を実行することで、ある深さの回路で期待値をシミュレートする。 ゲート切断は、ステップ2（離れたゲートを分解して量子実行のために回路を最適化する）とステップ4（元の回路の期待値を再構成する後処理）に関連している。\n",
        "最初のステップでは、Qiskit回路ライブラリから回路を生成し、いくつかのobservablesを定義する。\n",
        "\n",
        "* インプット回路を定義するための古典的なパラメータ\n",
        "* 出力抽象回路と観測値\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "54ed0f13",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/depth-reduction-with-circuit-cutting/extracted-outputs/54ed0f13-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "circuit = EfficientSU2(num_qubits=4, entanglement=\"circular\").decompose()\n",
        "circuit.assign_parameters([0.4] * len(circuit.parameters), inplace=True)\n",
        "observables = PauliList([\"ZZII\", \"IZZI\", \"IIZZ\", \"XIXI\", \"ZIZZ\", \"IXIX\"])\n",
        "circuit.draw(\"mpl\", scale=0.8, style=\"iqp\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "080a2a8b",
      "metadata": {},
      "source": [
        "<span id=\"step-2-optimize-problem-for-quantum-hardware-execution\" />\n",
        "\n",
        "## ステップ2：量子ハードウェア実行に向けた問題の最適化\n",
        "\n",
        "* 入力抽象回路と観測値\n",
        "* 出力：出力：トランスパイルド回路の深さを減らすために遠くのゲートをカットすることによって生成されるターゲット回路と観測値\n",
        "\n",
        "初期レイアウトは、量子ビット3と0の間のゲートを実行するために2回のスワップを必要とし、量子ビットを初期位置に戻すためにさらに2回のスワップを必要とするものを選んだ。 私たちは、プリセット・パス・マネージャーで利用可能な最高レベルの最適化である `optimization_level=3`。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b394da7a",
      "metadata": {},
      "outputs": [],
      "source": [
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, min_num_qubits=circuit.num_qubits, simulator=False\n",
        ")\n",
        "\n",
        "pm = generate_preset_pass_manager(\n",
        "    optimization_level=3, initial_layout=[0, 1, 2, 3], backend=backend\n",
        ")\n",
        "transpiled_qc = pm.run(circuit)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "68c00476",
      "metadata": {},
      "source": [
        "![スワップが必要な量子ビットを示すカップリングマップ](https://quantum.cloud.ibm.com/docs/images/tutorials/depth-reduction-with-circuit-cutting/swaps.avif)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "4fe4af43",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Transpiled circuit depth: 103\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/depth-reduction-with-circuit-cutting/extracted-outputs/4fe4af43-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "print(f\"Transpiled circuit depth: {transpiled_qc.depth()}\")\n",
        "transpiled_qc.draw(\"mpl\", scale=0.4, idle_wires=False, style=\"iqp\", fold=-1)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "babfbd0f",
      "metadata": {},
      "source": [
        "*遠隔ゲートを検索して切り取る：* 非局所量子ビット（0と3）を接続する遠隔ゲートを、そのインデックスを指定 `TwoQubitQPDGate` することでオブジェクトに置き換える。 `cut_gates` 指定されたインデ `TwoQubitQPDGate` ックスのゲートをオブジェクトで置き換え、さらに各ゲート分解に対応 `QPDBasis` するインスタンスのリストを返します。 オブジェクト `QPDBasis` は、カットゲートを単一量子ビット操作に分解する方法に関する情報を含みます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "23e3d25e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/depth-reduction-with-circuit-cutting/extracted-outputs/23e3d25e-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Find the indices of the distant gates\n",
        "cut_indices = [\n",
        "    i\n",
        "    for i, instruction in enumerate(circuit.data)\n",
        "    if {circuit.find_bit(q)[0] for q in instruction.qubits} == {0, 3}\n",
        "]\n",
        "\n",
        "# Decompose distant CNOTs into TwoQubitQPDGate instances\n",
        "qpd_circuit, bases = cut_gates(circuit, cut_indices)\n",
        "\n",
        "qpd_circuit.draw(\"mpl\", scale=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "069eb942-e947-4eff-a250-9a99c5ec47f0",
      "metadata": {},
      "source": [
        "*バックエンドで実行するサブ実験を生成する*。 `generate_cutting_experiments` は、 `TwoQubitQPDGate` インスタンスと観測値を含む回路を `PauliList` として受け取る。\n",
        "\n",
        "フルサイズの回路の期待値をシミュレートするために、分解されたゲートの結合準確率分布から多数のサブ実験が生成され、1つ以上のバックエンドで実行される。 分布から取られたサンプルの数は `num_samples` で制御され、各ユニークなサンプルに対して1つの結合係数が与えられます。 係数の計算方法の詳細については、 [説明資料を](https://qiskit.github.io/qiskit-addon-cutting/explanation/index.html)参照のこと。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "83b1efed-bafa-48c4-bbf0-cf7eb9027ac5",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generate the subexperiments and sampling coefficients\n",
        "subexperiments, coefficients = generate_cutting_experiments(\n",
        "    circuits=qpd_circuit, observables=observables, num_samples=np.inf\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6929264d",
      "metadata": {},
      "source": [
        "*比較のため、遠くのゲートをカットするとQPDサブ実験が浅くなることがわかる* ：以下は、QPD回路から生成された、任意に選択されたサブ実験の例である。 その深さは半分以下になった。 より深い回路の期待値を再構築するためには、このような確率的なサブ実験の多くを生成し、評価しなければならない。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "70e2f1b6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Original circuit depth after transpile: 103\n",
            "QPD subexperiment depth after transpile: 46\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/depth-reduction-with-circuit-cutting/extracted-outputs/70e2f1b6-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Transpile the decomposed circuit to the same layout\n",
        "transpiled_qpd_circuit = pm.run(subexperiments[100])\n",
        "\n",
        "print(f\"Original circuit depth after transpile: {transpiled_qc.depth()}\")\n",
        "print(\n",
        "    f\"QPD subexperiment depth after transpile: {transpiled_qpd_circuit.depth()}\"\n",
        ")\n",
        "transpiled_qpd_circuit.draw(\n",
        "    \"mpl\", scale=0.6, style=\"iqp\", idle_wires=False, fold=-1\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "87368cb9",
      "metadata": {},
      "source": [
        "*一方、カットすることで余計なサンプリングが必要になる*。 ここでは、3つのCNOTゲートをカットした結果、サンプリング・オーバーヘッドが $9^3$。回路カットで発生するサンプリング・オーバーヘッドについては、 [Circuit Knitting Toolboxのドキュメントを](https://qiskit-extensions.github.io/circuit-knitting-toolbox/circuit_cutting/explanation/index.html)参照。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "2ab65bd4",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Sampling overhead: 729.0\n"
          ]
        }
      ],
      "source": [
        "print(f\"Sampling overhead: {np.prod([basis.overhead for basis in bases])}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fd9a126c",
      "metadata": {},
      "source": [
        "<span id=\"step-3-execute-using-qiskit-primitives\" />\n",
        "\n",
        "## ステップ3: `Qiskit primitives`を使用して実行する\n",
        "\n",
        "Samplerプリミティブを使用して、対象の回路（「サブ実験」）を実行します。\n",
        "\n",
        "* 入力ターゲット回路\n",
        "* アウトプット準確率分布\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "a437de20-2042-4e62-87a7-804058cff5db",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Transpile the subexperiments to the backend's instruction set architecture (ISA)\n",
        "isa_subexperiments = pm.run(subexperiments)\n",
        "\n",
        "# Set up the IBM Quantum Sampler primitive.  For a fake backend, this will use a local simulator.\n",
        "sampler = SamplerV2(backend)\n",
        "\n",
        "# Submit the subexperiments\n",
        "job = sampler.run(isa_subexperiments)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "ca53d638",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Retrieve the results\n",
        "results = job.result()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "32d35001",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "czypg1r6rr3g008mgp6g\n"
          ]
        }
      ],
      "source": [
        "print(job.job_id())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f04d9134-651b-446e-93f4-aa0281786200",
      "metadata": {},
      "source": [
        "<span id=\"step-4-post-process-and-return-result-in-desired-classical-format\" />\n",
        "\n",
        "## ステップ4：後処理を行い、結果を希望の古典形式で返す\n",
        "\n",
        "サブ実験結果、サブ観測値、サンプリング係数を用いて、元の回路の期待値を再構築する。\n",
        "\n",
        "入力準確率分布 出力再構成された期待値\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "ace12f7f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Final reconstructed expectation value\n",
            "1.0751342773437473\n"
          ]
        }
      ],
      "source": [
        "reconstructed_expvals = reconstruct_expectation_values(\n",
        "    results,\n",
        "    coefficients,\n",
        "    observables,\n",
        ")\n",
        "# Reconstruct final expectation value\n",
        "final_expval = np.dot(reconstructed_expvals, [1] * len(observables))\n",
        "print(\"Final reconstructed expectation value\")\n",
        "print(final_expval)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "e6237a6f",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Ideal expectation value\n",
            "1.2283177520039992\n"
          ]
        }
      ],
      "source": [
        "ideal_expvals = [\n",
        "    Statevector(circuit).expectation_value(SparsePauliOp(observable))\n",
        "    for observable in observables\n",
        "]\n",
        "print(\"Ideal expectation value\")\n",
        "print(np.dot(ideal_expvals, [1] * len(observables)).real)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e366d14e",
      "metadata": {},
      "source": [
        "<span id=\"tutorial-survey\" />\n",
        "\n",
        "## チュートリアル調査\n",
        "\n",
        "このチュートリアルに関するご意見・ご感想をお寄せください。 あなたの洞察は、私たちのコンテンツの提供とユーザーエクスペリエンスを向上させるのに役立ちます。\n",
        "\n",
        "[アンケートへのリンク](https://your.feedback.ibm.com/jfe/form/SV_2ftYFf9t72yFNIO)\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"
    },
    "hours": 1.5,
    "qpuSeconds": 480
  },
  "nbformat": 4,
  "nbformat_minor": 5
}