{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "frontmatter",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"AQC + トロッター動力学を用いた中性子散乱のシミュレーション：サーバーレスワークフロー\"\n",
        "description: \"AQC圧縮をデプロイ済み関数テンプレートとして用いたトロッター・ワークフローを実行し、量子磁石 KCuF3 の動的構造因子S(q, w)を計算する。\"\n",
        "---\n",
        "\n",
        "{/* cspell:ignore Trotter Trotterization spinon spinons KCuF quimb DMRG magnon antiferromagnetic Suzuki fidelities isa COBYQA Gjjc qpoints viridis fontsize vmax vmin */}\n",
        "\n",
        "<span id=\"simulate-neutron-scattering-with-an-aqc-+-trotter-dynamics-serverless-workflow\" />\n",
        "\n",
        "# AQC + トロッター動力学を用いた中性子散乱のシミュレーション：サーバーレスワークフロー\n",
        "\n",
        "推定*実行時間：Heron r3 プロセッサで 18 分（注：これはあくまで推定値です。 実行時間は状況によって異なる場合があります。）*\n",
        "\n",
        "<Admonition type=\"note\" title=\"どのチュートリアルを使えばいいですか？\">\n",
        "  このチュートリアルでは、回路の構築、圧縮、実行を1つの呼び出しにまとめた、 Qiskit Serverless の組み込み関数を使用して、中性子散乱実験を実行します。 圧縮処理では、サーバーレスワーカーの演算リソースとメモリリソースが使用されます。ノートブックを閉じた後も処理は継続されますが、初期状態の準備と後処理は引き続きローカルで実行されます。 まず、 [関数テンプレートをデプロイ](/docs/guides/function-template-aqc-trotter)する必要があります。 実装手順を段階的に学ぶには、 [オリジナルのチュートリアル](/docs/tutorials/simulate-neutron-scattering)をご利用ください。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "learning-outcomes",
      "metadata": {},
      "source": [
        "<span id=\"learning-outcomes\" />\n",
        "\n",
        "## 学習成果\n",
        "\n",
        "* 非弾性中性子散乱スペクトルが、 1D 量子磁石の動的構造因子 $S(q, \\omega)$ にどのように対応するか。\n",
        "* 密度行列再正規化群（DMRG）および行列積状態（MPS）のフィデリティ最大化を用いて、 KCuF$_3$ （等方性ハイゼンベルク）基底状態を準備する方法。\n",
        "* Trotterの時間発展、近似量子コンパイル（AQC）による回路圧縮、および緩和実行を、単一の関数呼び出しとして実行する方法。\n",
        "* サイトごとの $\\langle \\sigma_z \\rangle(t)$ の時系列データを $S(q, \\omega)$ に変換し、2つのスピノン連続体を同定するための後処理方法。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "prerequisites",
      "metadata": {},
      "source": [
        "<span id=\"prerequisites\" />\n",
        "\n",
        "## 前提条件\n",
        "\n",
        "* [Qiskitのパターン](/docs/guides/intro-to-patterns)、 [`SparsePauliOp`](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)、およびに関する知識 [トロッターの時間発展](/learning/courses/utility-scale-quantum-computing/quantum-simulation)。\n",
        "* テンソルネットワーク法（DMRG および MPS）に関する基本的な知識があると役立ちますが、必須ではありません。また、この関数がトロッター回路を圧縮するために使用する [`qiskit-addon-aqc-tensor`](https://github.com/Qiskit/qiskit-addon-aqc-tensor) ライブラリに精通していることも同様です。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "background",
      "metadata": {},
      "source": [
        "<span id=\"background\" />\n",
        "\n",
        "## 背景\n",
        "\n",
        "非弾性中性子散乱では、スピン間相関関数の時空間フーリエ変換である動的構造因子 $S(q, \\omega)$ が測定されるため、微視的なスピンモデルから $S(q, \\omega)$ を再現することは、量子シミュレーションに対する直接的かつ反証可能な検証となる。 このチュートリアルでは、 KCuF$_3$ について考察する。これは、スピン- $\\frac{1}{2}$ の反強磁性ハイゼンベルグ鎖であり、その励起は単一スピンの反転ではなく、分画化されたスピノン対である。 $S(q, \\omega)$ では、鋭いマグノン分散曲線ではなく、 *広い2スピノン連続*体が示されており、その下限は $\\tfrac{\\pi}{2}|\\sin q|$、上限は $\\pi|\\sin(q/2)|$ によって囲まれている。これらは、以下の図中の破線曲線である。 物理的メカニズムの全容および測定された中性子データとの比較については、 [元のチュートリアル](/docs/tutorials/simulate-neutron-scattering)およびLeeらによる論文で解説されています [arXiv:2603.15608](https://arxiv.org/abs/2603.15608).\n",
        "\n",
        "量子ワークフローは、散乱実験を反映しています：\n",
        "\n",
        "1. チェーンの基底状態 $|\\psi_0\\rangle$ を準備する。\n",
        "2. 中心地点で局所的な摂動、すなわち $\\pi/2$ $Z$ -rotationを加え、中性子からの運動量およびエネルギーの伝達を模倣してみましょう。\n",
        "3. トロッター積公式を用いて、ハイゼンベルク・ハミルトニアン $e^{-iHt}$ の下で時間発展を行う。\n",
        "4. サイトごとの磁化 $\\langle \\sigma_z^j \\rangle(t)$ を測定する。これは、サイト $j$ および時間 $t$ の関数として、まさに遅延グリーン関数 $G^R(j, j_c, t)$ に等しいため、ステップ5でのフーリエ変換の前に変換を行う必要はない。\n",
        "5. $G^R$ をフーリエ変換すると、 $S(q, \\omega)$ となる。\n",
        "\n",
        "ステップ3において、長い進化に対する正確なトロッター回路がハードウェアの処理能力を超えて深くなりすぎる場合、問題が生じる可能性があります。 テンソルネットワークを用いたAQCは、トロッターステップのブロックを、固定された浅いパラメータ化アンサッツに圧縮することでこの問題に対処しており、そのアンサッツの正確な進化に対する状態忠実度は、MPSシミュレータを用いて古典的に最大化される（ [arXiv:2301.08609](https://arxiv.org/abs/2301.08609) ）。 [AQC Dynamicsテンプレート](/docs/guides/function-template-aqc-trotter)は、この量子コア全体（トロッター合成、AQC圧縮、およびリスク軽減実行）を1つの呼び出しにまとめ上げています：\n",
        "\n",
        "| PRE（このノート）                                         | FUNCTION (`aqc-dynamics-function`)                                                                     | 投稿（このノート）             |\n",
        "| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------- |\n",
        "| DMRGとMPSによる忠実度最大化を組み合わせた基底状態。中性子キックは、同じ回路に組み込まれている | トロッター合成 → AQC圧縮 → `statevector`、 `fake`、 または での実行 `runtime`、サイトごとに $\\langle \\sigma_z^j \\rangle(t)$ を返す | $S(q, \\omega)$、動的構造因子 |\n",
        "\n",
        "実験固有の作業は、このノートブック内に残されています。具体的には、基底状態の準備（PRE）と、 $S(q, \\omega)$ による後処理（POST）です。 量子計算を多用する2つのステップ、すなわち圧縮と実行は、この関数内で実行されます。\n",
        "\n",
        "このチュートリアルは、「 [量子回路を用いた量子材料の中性子散乱のシミュレーション](/docs/tutorials/simulate-neutron-scattering) 」の補足資料であり、同記事と同じ実験を順を追って構築しています。具体的には、 KCuF$_3$モデル、基底状態の準備、中性子キック、後処理に加え、トロッター合成、AQC圧縮、およびミティゲート実行について、段階的に解説しています。 AQC圧縮の仕組みについて知りたい場合は、そのチュートリアルをお読みください。 デプロイ済みの関数テンプレートを使って同じ実験を実行するには、こちらの記事をご覧ください。量子コアは単一の関数呼び出しとなり、数時間かかるAQC圧縮処理は、ご自身のマシン上ではなくサーバーレスワーカー内で実行されるため、実行中にHPCシステムやオープンカーネルを用意する必要はありません。 この呼び出しは、 1D の他の動的実験も駆動しています。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "requirements",
      "metadata": {},
      "source": [
        "<span id=\"requirements\" />\n",
        "\n",
        "## 要件\n",
        "\n",
        "このチュートリアルを始める前に、以下のものが揃っていることを確認してください：\n",
        "\n",
        "* Qiskit Serverless アカウントにデプロイされた関数。 まずコンパニオン関数テンプレートを実行します： [AQC + Trotter ダイナミクス関数テンプレートをデプロイして実行します](/docs/guides/function-template-aqc-trotter)。 このガイドでは、ソースファイルの入手方法と、その関数を自分のアカウントにアップロードする方法について順を追って説明しています。 このチュートリアルでは、デプロイされた関数を呼び出すだけです。\n",
        "\n",
        "* IBM Quantum® （ `QiskitServerless` 関数テンプレートを参照）に保存された認証情報。 このチュートリアルの両方の例では、デプロイされた関数が呼び出されるため、どちらもそれが必要です。\n",
        "\n",
        "* Qiskit SDK v2.0 またはそれ以降 (`pip install qiskit`)。\n",
        "\n",
        "* Qiskitの IBM カタログクライアント（`pip install qiskit-ibm-catalog`）。\n",
        "\n",
        "* NumPy, SciPy, また、 Matplotlib (`pip install numpy scipy matplotlib`) も必要です。 SciPy 基底状態の準備に使用される COBYQA オプティマイザーには、 1.14 以降が必要です。\n",
        "\n",
        "* AQCテンソルネットワークスタックは、ステップ1での基底状態の準備が、このノートブック内でローカルに実行されるためです： `pip install 'qiskit-addon-aqc-tensor[quimb-jax]==0.3.1'`。\n",
        "\n",
        "新しくデプロイされた関数への最初の呼び出しでは、Serverlessワーカーが依存関係をインストールする間待機するため、その実行時には通常より遅延が生じることを想定してください。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "setup-md",
      "metadata": {},
      "source": [
        "<span id=\"setup\" />\n",
        "\n",
        "## セットアップ\n",
        "\n",
        "ライブラリをインポートし、後で使用する実験固有のヘルパー関数を定義します： （`build_gs_ansatz` 基底状態の準備のためのハミルトニアン変分アンザッツ（HVA））、 （`prepare_ground_state` DMRGおよびMPS忠実度最大化）、ならびに `get_spectrum`、 `plot_green`、および `plot_spectrum` （$S(q, \\omega)$ による後処理）。 これらは、 [元の中性子散乱チュートリアル](/docs/tutorials/simulate-neutron-scattering)を基に改変したものです。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "setup-imports",
      "metadata": {},
      "outputs": [],
      "source": [
        "from functools import partial\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import scipy.optimize\n",
        "\n",
        "import quimb.tensor as qtn\n",
        "from qiskit import QuantumCircuit\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit_addon_aqc_tensor.simulation import tensornetwork_from_circuit\n",
        "from qiskit_addon_aqc_tensor.simulation.quimb import QuimbSimulator\n",
        "from qiskit_ibm_catalog import QiskitServerless"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "setup-helpers",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Setup complete - helpers defined.\n"
          ]
        }
      ],
      "source": [
        "#  Dynamical structure factor via discrete Fourier transform\n",
        "\n",
        "\n",
        "def get_spectrum(n, Gjjc, dt, time_steps, q_steps, w_steps):\n",
        "    \"\"\"Compute the dynamical structure factor from the retarded Green's function.\n",
        "\n",
        "    Uses the center-site approximation and a discrete Fourier transform.\n",
        "    \"\"\"\n",
        "    green = Gjjc / 4  # sigma -> S=1/2\n",
        "    omega_max = np.pi / dt\n",
        "    qpoints = np.arange(0, 2 * np.pi, 2 * np.pi / q_steps)\n",
        "    omegas = np.arange(0, omega_max, omega_max / w_steps)\n",
        "    green_map = np.zeros((omegas.shape[0], qpoints.shape[0]))\n",
        "    center = n // 2 - 1\n",
        "    for iw, w in enumerate(omegas):\n",
        "        exponent = np.exp(1j * w * dt * np.arange(1, time_steps + 1))\n",
        "        S_w = np.dot(green.T, exponent) * dt\n",
        "        for iq, q in enumerate(qpoints):\n",
        "            q_matrix = np.exp(-1j * q * np.arange(-center, center + 2, 1))\n",
        "            green_map[iw, iq] = np.imag(np.dot(S_w, q_matrix))\n",
        "    return green_map\n",
        "\n",
        "\n",
        "#  Plotting helpers\n",
        "\n",
        "\n",
        "def plot_spectrum(\n",
        "    dsf,\n",
        "    dt,\n",
        "    q_steps,\n",
        "    w_steps,\n",
        "    lower_bound=False,\n",
        "    upper_bound=False,\n",
        "    title=None,\n",
        "):\n",
        "    \"\"\"Heat-map of the dynamical structure factor.\"\"\"\n",
        "    omega_max = np.pi / dt\n",
        "    qpoints = np.arange(0, 2 * np.pi, 2 * np.pi / q_steps)\n",
        "    omegas = np.arange(0, omega_max, omega_max / w_steps)\n",
        "    x, y = np.meshgrid(qpoints, omegas)\n",
        "    fig, ax = plt.subplots(figsize=(8, 5))\n",
        "    c = ax.pcolormesh(x, y, dsf / np.max(dsf), cmap=\"viridis\", shading=\"auto\")\n",
        "    fig.colorbar(c, ax=ax, label=\"Normalized intensity\")\n",
        "    if lower_bound:\n",
        "        ax.plot(\n",
        "            qpoints,\n",
        "            np.pi * np.abs(np.sin(qpoints)) / 2,\n",
        "            \"--\",\n",
        "            color=\"white\",\n",
        "            lw=1.5,\n",
        "            label=\"Lower bound\",\n",
        "        )\n",
        "    if upper_bound:\n",
        "        ax.plot(\n",
        "            qpoints,\n",
        "            np.pi * np.abs(np.sin(qpoints / 2)),\n",
        "            \"--\",\n",
        "            color=\"red\",\n",
        "            lw=1.5,\n",
        "            label=\"Upper bound\",\n",
        "        )\n",
        "    ax.set_ylim(0, 3.6)\n",
        "    ax.set_xlim(0, 2 * np.pi - 2 * np.pi / q_steps)\n",
        "    ax.set_xlabel(r\"$q$\", fontsize=16)\n",
        "    ax.set_ylabel(r\"$\\tilde{\\omega} = \\omega / J$\", fontsize=16)\n",
        "    ax.set_xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi])\n",
        "    ax.set_xticklabels([\"0\", r\"$\\pi/2$\", r\"$\\pi$\", r\"$3\\pi/2$\", r\"$2\\pi$\"])\n",
        "    if lower_bound or upper_bound:\n",
        "        ax.legend(loc=\"upper right\", fontsize=11)\n",
        "    if title:\n",
        "        ax.set_title(title, fontsize=14)\n",
        "    plt.tight_layout()\n",
        "    plt.show()\n",
        "\n",
        "\n",
        "def plot_green(n, Gjjc, time_steps, dt, title=None):\n",
        "    \"\"\"Heat-map of the retarded Green's function in real space and time.\"\"\"\n",
        "    fig, ax = plt.subplots(figsize=(8, 6))\n",
        "    t_axis = np.arange(1, time_steps + 1) * dt\n",
        "    site_axis = np.arange(n)\n",
        "    x, y = np.meshgrid(t_axis, site_axis)\n",
        "    c = ax.pcolormesh(\n",
        "        x,\n",
        "        y,\n",
        "        np.real(Gjjc).T,\n",
        "        cmap=\"RdBu\",\n",
        "        vmax=0.5,\n",
        "        vmin=-0.5,\n",
        "        shading=\"auto\",\n",
        "    )\n",
        "    fig.colorbar(c, ax=ax, label=r\"Re $G^R(j, j_c, t)$\")\n",
        "    ax.set_xlabel(r\"Time  ($t / J^{-1}$)\", fontsize=16)\n",
        "    ax.set_ylabel(\"Site index $j$\", fontsize=16)\n",
        "    if title:\n",
        "        ax.set_title(title, fontsize=14)\n",
        "    plt.tight_layout()\n",
        "    plt.show()\n",
        "\n",
        "\n",
        "#  Variational ground-state ansatz (HVA)\n",
        "\n",
        "\n",
        "def _apply_xxz_pair_gate(qc, q0, q1, theta):\n",
        "    \"\"\"Apply the parameterized XXZ-type two-qubit gate used in the HVA.\"\"\"\n",
        "    qc.cx(q0, q1)\n",
        "    qc.rz(theta, q1)\n",
        "    qc.h(q0)\n",
        "    qc.rz(theta + np.pi / 2, q0)\n",
        "    qc.cx(q0, q1)\n",
        "    qc.rz(-theta, q1)\n",
        "    qc.h(q1)\n",
        "    qc.cx(q1, q0)\n",
        "    qc.rz(np.pi / 2, q1)\n",
        "    qc.rz(-np.pi / 2, q0)\n",
        "    qc.h(q1)\n",
        "    qc.h(q0)\n",
        "\n",
        "\n",
        "def build_gs_ansatz(n, params, layers):\n",
        "    \"\"\"Build the Hamiltonian variational ansatz (HVA) circuit for\n",
        "    ground-state preparation of the 1D Heisenberg model.\n",
        "\n",
        "    Starts from a product of singlet pairs and applies alternating\n",
        "    odd/even layers of parameterized XXZ gates. For layer r,\n",
        "    params[2 * r] is the odd-layer (inter-pair) angle and\n",
        "    params[2 * r + 1] is the even-layer (intra-pair) angle.\n",
        "    \"\"\"\n",
        "    qc = QuantumCircuit(n)\n",
        "    # Initial singlet product state\n",
        "    for i in range(n // 2):\n",
        "        qc.x(2 * i)\n",
        "        qc.x(2 * i + 1)\n",
        "        qc.h(2 * i + 1)\n",
        "        qc.cx(2 * i + 1, 2 * i)\n",
        "    # Variational layers\n",
        "    for r in range(layers):\n",
        "        for i in range(1, (n + 1) // 2):  # odd layer\n",
        "            _apply_xxz_pair_gate(qc, 2 * i - 1, 2 * i, params[2 * r])\n",
        "        for i in range(n // 2):  # even layer\n",
        "            _apply_xxz_pair_gate(qc, 2 * i, 2 * i + 1, params[2 * r + 1])\n",
        "    return qc\n",
        "\n",
        "\n",
        "def prepare_ground_state(n, gs_layers=5, max_bond=128, cutoff=1e-8):\n",
        "    \"\"\"Prepare the KCuF3 (isotropic Heisenberg) ground state as a QuantumCircuit.\n",
        "\n",
        "    Runs DMRG (quimb MPO + DMRG2) to get the chain's ground state, then optimizes\n",
        "    the HVA angles to maximize the MPS overlap |<psi_ansatz|psi_DMRG>|^2. No exact\n",
        "    diagonalization, so it scales to larger n.\n",
        "    \"\"\"\n",
        "    J = Jz = 1.0\n",
        "    builder = qtn.SpinHam1D(S=1 / 2)\n",
        "    builder += J * 0.5, \"+\", \"-\"\n",
        "    builder += J * 0.5, \"-\", \"+\"\n",
        "    builder += Jz, \"Z\", \"Z\"\n",
        "    H_mpo = builder.build_mpo(L=n)\n",
        "    dmrg = qtn.DMRG2(H_mpo)\n",
        "    dmrg.solve(tol=1e-8, verbosity=0)\n",
        "\n",
        "    gs_sim = QuimbSimulator(\n",
        "        quimb_circuit_factory=partial(\n",
        "            qtn.CircuitMPS, gate_opts=dict(cutoff=cutoff, max_bond=max_bond)\n",
        "        ),\n",
        "        autodiff_backend=\"jax\",\n",
        "    )\n",
        "\n",
        "    def gs_infidelity(params):\n",
        "        psi = tensornetwork_from_circuit(\n",
        "            build_gs_ansatz(n, params, gs_layers), gs_sim\n",
        "        ).psi\n",
        "        return 1 - abs(psi.H @ dmrg.state) ** 2\n",
        "\n",
        "    # Seed and optimizer match the original tutorial. Each layer starts at\n",
        "    # [0, pi/2]: an odd-layer angle of 0 makes the inter-pair gate the identity,\n",
        "    # and an even-layer angle of pi/2 makes the intra-pair gate a SWAP (since\n",
        "    # 0.5 * (XX + YY + ZZ) = SWAP - I/2). That puts the seed at the singlet-pair\n",
        "    # product limit, which is already a decent approximation to the Heisenberg\n",
        "    # ground state, so the optimizer only has to refine it. The small jitter\n",
        "    # (fixed RNG seed, so runs are reproducible) breaks the exact symmetry\n",
        "    # between layers; COBYQA then runs for up to 100 iterations.\n",
        "    rng = np.random.default_rng(12345)\n",
        "    x0 = np.tile([0.0, np.pi / 2], gs_layers) + rng.normal(\n",
        "        scale=0.1, size=2 * gs_layers\n",
        "    )\n",
        "    result_gs = scipy.optimize.minimize(\n",
        "        gs_infidelity, x0, method=\"COBYQA\", options={\"maxiter\": 100}\n",
        "    )\n",
        "    print(f\"DMRG ground-state energy: {dmrg.energy:.6f}\")\n",
        "    print(f\"GS fidelity: {1 - result_gs.fun:.4f}\")\n",
        "    return build_gs_ansatz(n, result_gs.x, gs_layers)\n",
        "\n",
        "\n",
        "print(\"Setup complete - helpers defined.\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "setup-load-md",
      "metadata": {},
      "source": [
        "<span id=\"load-the-function-template\" />\n",
        "\n",
        "### 関数テンプレートを読み込む\n",
        "\n",
        "Qiskit Serverless に接続し、デプロイされた `aqc-dynamics-function`. を読み込みます。 このチュートリアルの両方の例では同じハンド `fn` ルを呼び出しているため、ここでは関数が一度だけ読み込まれます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "setup-connect",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Credentials are read from the account saved once via QiskitServerless.save_account(...)\n",
        "serverless = QiskitServerless()\n",
        "fn = serverless.load(\"aqc-dynamics-function\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "small-md",
      "metadata": {},
      "source": [
        "<span id=\"small-scale-simulator-example\" />\n",
        "\n",
        "## 小規模シミュレータの例\n",
        "\n",
        "まず、exactバック `statevector` エンドを使用して、10店舗からなる小規模なチェーンでワークフロー全体を実行します。 これにより、QPUの処理時間を一切消費することなく、PRE → FUNCTION → POST のパイプラインの妥当性を確認できます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "small-s1-md",
      "metadata": {},
      "source": [
        "<span id=\"step-1-map-classical-inputs-to-a-quantum-problem\" />\n",
        "\n",
        "### ステップ1：古典的な入力を量子問題に写像する\n",
        "\n",
        "KCuF$_3$ のハミルトニアンを、各最近接結合において結合定数 $\\tfrac14$ を持つ（ `SparsePauliOp` 等方性ハイゼンベルグ： $XX + YY + ZZ$ ）として構築する。弦はパウリ演算子であるため、 $\\tfrac14$ によりスピン結合 $\\frac{1}{2}$ が得られる。 DMRGとMPS-fidelity最大化を用いて基底状態を準備し、その後、中性子キック（中心サイトにおける $\\pi/2$ $Z$ 回転）を組み込む。 準備した回路こそが、関数にとして渡すものです `initial_state`。 ここではデフォルト設定（サイトごとの $Z$ ）の `observables` ままにします。これは、中性子ワークフローに必要な $\\langle \\sigma_z^j \\rangle(t)$ の読み取り値と完全に一致しています。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "small-s1-code",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DMRG ground-state energy: -4.258035\n",
            "GS fidelity: 0.9841\n",
            "Prepared 10-qubit ground state with the neutron kick at site 4.\n"
          ]
        }
      ],
      "source": [
        "n = 10\n",
        "dt = 0.6  # physical time per Trotter step (also the omega-axis unit in POST)\n",
        "time_steps = 10\n",
        "center = n // 2 - 1\n",
        "\n",
        "# MPS-simulator settings, shared by the ground-state prep here and the AQC\n",
        "# compression inside the function (matches the original tutorial).\n",
        "mps_max_bond = 32\n",
        "mps_cutoff = 1e-8\n",
        "\n",
        "# 1D isotropic Heisenberg (KCuF3) Hamiltonian on n qubits\n",
        "H = SparsePauliOp.from_sparse_list(\n",
        "    [(p, [i, i + 1], 0.25) for i in range(n - 1) for p in (\"XX\", \"YY\", \"ZZ\")],\n",
        "    num_qubits=n,\n",
        ")\n",
        "\n",
        "# Ground state (DMRG + fidelity max) + neutron kick baked into the same circuit\n",
        "gs_circuit = prepare_ground_state(\n",
        "    n, gs_layers=3, max_bond=mps_max_bond, cutoff=mps_cutoff\n",
        ")\n",
        "gs_circuit.rz(\n",
        "    np.pi / 2, center\n",
        ")  # exp(-i (pi/2)/2 Z_center): the neutron perturbation\n",
        "print(\n",
        "    f\"Prepared {n}-qubit ground state with the neutron kick at site {center}.\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "small-s3-md",
      "metadata": {},
      "source": [
        "<span id=\"steps-2-and-3-compress-and-execute-with-the-function-template\" />\n",
        "\n",
        "### 手順 2 および 3：関数テンプレートを使用して圧縮および実行する\n",
        "\n",
        "手作業によるワークフローでは、これらは2つの別々の段階、すなわちハードウェア向けに回路を最適化すること（ステップ2）と、それを実行すること（ステップ3）となります。 この関数テンプレートは、これら2つを1つの呼び出しにまとめます。 トロッター合成、AQC圧縮、ハードウェア向けトランスパイルを行い、その後、回路を実行します（ここではエクサクト・シミュレータ上で、後ほどはハードウェア上で組み込みのエラー緩和機能を用いて実行します）。 2つの調整パラメータは、 `aqc_segments` （圧縮プラン）と `aqc_options` （MPSおよびオプティマイザの設定）です。 各セグメントでは、連続 `k` するトロッターのステップを、- `m`ステップのトロッターターゲットから構成されるアンザッツに圧縮 `{\"n_steps\": k, \"ansatz_steps\": m}` し、それを超えるステップは通常のトロッターとして実行 `sum(n_steps)` される。 初期の、エンタングルメントの低いステップは、浅い（`ansatz_steps=1`）アンザッツにうまく圧縮できるため、ここでは最初の3ステップを単層のアンザッツに、次の2ステップをより深い2層のアンザッツに圧縮する。10ステップあるトロッター法のうち、残りの5ステップは通常のトロッター法として実行される。 これは、元のチュートリアルと同様に、MPS結合寸法 `max_bond=32`、および反復回数の上限を100回に設定したL-BFGS-B最適化アルゴリズムを採用しているため `aqc_options` です `cutoff=1e-8`。\n",
        "\n",
        "Setupで読み込まれた関数を呼び出してください。 `backend=\"statevector\"` 正確な参照パスを実行します：QPU時間はかからず、回路はサーバーレスワーカー内の正確な状態ベクトルシミュレータ上で実行されます（呼び出すには、保存済みの Qiskit Serverless アカウントが依然として必要です）。 は、準備された基底状態（キックを含む）を `initial_state` 表します。は `observables` 省略されるため、この関数はデフォルトのサイトごとの $Z$ を測定します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "small-s3-run",
      "metadata": {},
      "outputs": [],
      "source": [
        "job = fn.run(\n",
        "    t_steps=time_steps,\n",
        "    aqc_segments=[\n",
        "        {\n",
        "            \"n_steps\": 3,\n",
        "            \"ansatz_steps\": 1,\n",
        "        },  # early steps -> shallow 1-layer ansatz\n",
        "        {\n",
        "            \"n_steps\": 2,\n",
        "            \"ansatz_steps\": 2,\n",
        "        },  # later steps -> deeper 2-layer ansatz\n",
        "    ],\n",
        "    aqc_options={\n",
        "        \"max_bond\": mps_max_bond,  # MPS bond dimension for AQC compression\n",
        "        \"cutoff\": mps_cutoff,\n",
        "        \"optimizer_settings\": {\n",
        "            \"method\": \"L-BFGS-B\",\n",
        "            \"jac\": True,\n",
        "            \"options\": {\"maxiter\": 100},\n",
        "        },\n",
        "    },\n",
        "    dt=dt,\n",
        "    hamiltonian=H,\n",
        "    initial_state=gs_circuit,  # prepared ground state including the neutron kick\n",
        "    # observables omitted -> default per-site Z (the neutron sigma_z readout)\n",
        "    backend=\"statevector\",\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "small-status",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DONE\n"
          ]
        }
      ],
      "source": [
        "print(job.status())  # rerun this cell until status says DONE"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "small-s3-result",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AQC fidelities: {'1': 1.0, '2': 0.9999, '3': 0.9992, '4': 0.9998, '5': 0.9995}\n",
            "Green's function shape: (10, 10)\n"
          ]
        }
      ],
      "source": [
        "# The per-site <sigma_z>(t) the function returns is the retarded Green's function\n",
        "# G(j, j_c, t). The workflow samples t = 1..time_steps, so drop the t = 0 row (the\n",
        "# prepared+kicked state before any evolution) before post-processing.\n",
        "result = job.result()\n",
        "print(\n",
        "    \"AQC fidelities:\",\n",
        "    {k: round(v, 4) for k, v in result[\"metadata\"][\"aqc_fidelities\"].items()},\n",
        ")\n",
        "\n",
        "ev = np.array(result[\"expectation_values\"])\n",
        "Gjjc = ev[1:]  # shape (time_steps, n)\n",
        "print(\"Green's function shape:\", Gjjc.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "small-s4-md",
      "metadata": {},
      "source": [
        "<span id=\"step-4-post-process-and-return-result-in-desired-classical-format\" />\n",
        "\n",
        "### ステップ4：後処理を行い、結果を所望の従来の形式で出力する\n",
        "\n",
        "グリーンの関数をフーリエ変換して $S(q, \\omega)$ とし、鏡像対称化を行い、負の値を切り捨てる：これが中性子の標準的な後処理である。 このモデルでは、 $S(q, \\omega) = S(-q, \\omega)$ となるため、ミラーリングは正確に行われます。また、残ってしまう負の値は、有限で離散的にサンプリングされた時系列をフーリエ変換した際に生じるアーティファクトであるため、これらはゼロに切り捨てられます。 この小規模な正確なシミュレーションでは、2スピノン連続体は粗くしか分解されていませんが、その仕組みは、後に続くハードウェア実行と全く同じです。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "small-s4-code",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/extracted-outputs/small-s4-code-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/extracted-outputs/small-s4-code-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "q_res, w_res = 100, 100\n",
        "spectrum = get_spectrum(n, Gjjc, dt, time_steps, q_res, w_res)\n",
        "spectrum = -(spectrum + spectrum[:, ::-1]) / 2  # mirror symmetry\n",
        "spectrum = np.clip(spectrum, a_min=0, a_max=None)  # clip negatives\n",
        "\n",
        "plot_green(\n",
        "    n,\n",
        "    Gjjc,\n",
        "    time_steps,\n",
        "    dt,\n",
        "    title=f\"Retarded Green's function - {n} qubits (AQC, statevector)\",\n",
        ")\n",
        "plot_spectrum(\n",
        "    spectrum,\n",
        "    dt,\n",
        "    q_res,\n",
        "    w_res,\n",
        "    lower_bound=True,\n",
        "    upper_bound=True,\n",
        "    title=f\"Dynamical structure factor - {n} qubits (AQC, statevector)\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "large-md",
      "metadata": {},
      "source": [
        "<span id=\"large-scale-hardware-example\" />\n",
        "\n",
        "## 大規模なハードウェアの例\n",
        "\n",
        "このワークフローは、科学コードを一切変更することなくスケールアップが可能です。具体的には、30サイトのチェーン、トロッター深度の2倍（20ステップ）、アンザッツ深度を変化させる圧縮プラン（後方のより絡み合いの強いステップほど深いアンザッツを使用）、そして IBM Quantum プロセッサ上での実行に加え、関数に組み込まれたエラー軽減機能 （動的デカップリング、パウリ・トゥワーリング、およびトゥワーリング・リードアウト・エラー・エクスティンクション（TREX））を用いて実行されます。 シミュレータの例と同じ4つの手順を順を追って進め、Setupで取得したハンド `fn` ルを再利用します。\n",
        "\n",
        "|                     | 小規模           | 大規模な                      |\n",
        "| ------------------- | ------------- | ------------------------- |\n",
        "| 量子ビット               | 10            | 30時間まで                    |\n",
        "| トロッター・ステップ          | 10            | 20                        |\n",
        "| AQC圧縮されたステップ（1層＋2層） | 3 ＋ 2 ＝ 5     | 6 ＋ 4 ＝ 10                |\n",
        "| 基底状態のアンザッツ層         | 3             | 5                         |\n",
        "| MPSの最大結合寸法          | 32            | 128                       |\n",
        "| バックエンド              | `statevector` | DD、パウリ・トゥイール、TREXを搭載したQPU |\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "large-s1-md",
      "metadata": {},
      "source": [
        "<span id=\"step-1-map-classical-inputs-to-a-quantum-problem\" />\n",
        "\n",
        "### ステップ1：古典的な入力を量子問題に写像する\n",
        "\n",
        "同じ KCuF$_3$ハイゼンベルグを構築し `SparsePauliOp` 、基底状態を準備する。この際、より長い鎖に対応するより深い `gs_layers=5` アンザッツを用い、その後、中心サイトにおいて $\\pi/2$ $Z$ の中性子キックを焼き込む。 これは小規模なマッピングと全く同じですが、 $n = 30$ で行われます。\n",
        "\n",
        "10サイトでのシミュレーションに比べて、基底状態の忠実度は低くなると予想されます。具体的には、ここでは 0.82 程度となるのに対し、より短い鎖の場合は 0.98 でした。これは、5層のHVAでは30サイトの基底状態を完全に捉えきれないためです。 これは失敗というよりは想定内のことであり、同じ理由から、元のチュートリアルでは50のサイトにおいて 0.65 程度が許容されています。 「Raising」または `gs_layers` COBYQAの反復回数上限を引き上げると、追加の古典的コストを伴いながらも、性能が向上します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "id": "large-code",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DMRG ground-state energy: -13.111355\n",
            "GS fidelity: 0.8201\n",
            "Prepared 30-qubit ground state with the neutron kick at site 14.\n"
          ]
        }
      ],
      "source": [
        "n = 30\n",
        "dt = 0.6\n",
        "time_steps = 20\n",
        "center = n // 2 - 1\n",
        "\n",
        "# Same MPS settings as the original large-scale run: a larger bond for the\n",
        "# longer, more-entangled chain (shared by GS prep and AQC compression).\n",
        "mps_max_bond = 128\n",
        "mps_cutoff = 1e-8\n",
        "\n",
        "# Same KCuF3 Hamiltonian and ground-state prep, on a larger chain\n",
        "H = SparsePauliOp.from_sparse_list(\n",
        "    [(p, [i, i + 1], 0.25) for i in range(n - 1) for p in (\"XX\", \"YY\", \"ZZ\")],\n",
        "    num_qubits=n,\n",
        ")\n",
        "gs_circuit = prepare_ground_state(\n",
        "    n, gs_layers=5, max_bond=mps_max_bond, cutoff=mps_cutoff\n",
        ")\n",
        "gs_circuit.rz(np.pi / 2, center)  # neutron kick at the center site\n",
        "print(\n",
        "    f\"Prepared {n}-qubit ground state with the neutron kick at site {center}.\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "large-s3-md",
      "metadata": {},
      "source": [
        "<span id=\"steps-2-and-3-compress-and-execute-with-the-function-template\" />\n",
        "\n",
        "### 手順 2 および 3：関数テンプレートを使用して圧縮および実行する\n",
        "\n",
        "シミュレータの例と同じ単一の呼び出しですが、今回は IBM Quantum プロセッサを指す `backend_name` ように設定されているため、関数はそこでトランスパイルされ、実行されます。 この圧縮計画では、アンザッツの深さを段階的に変化させています。最初の6ステップ（低エンタングルメント）のトロッター法は浅い単層アンザッツに圧縮され、次の4ステップはより深い2層アンザッツに圧縮され、20ステップのうち残りの10ステップは通常のトロッター法として実行されます。 `aqc_options` より長く、より絡み合った鎖については `max_bond=128` 、MPS結合次元を に引き上げ（元のものと同じ）、L-BFGS-B最適化アルゴリズムの反復回数上限を100回に据え置きます。 組み込みのエラー軽減機能（動的デカップリング（ XY4 ）、ゲート・トゥワーリング、およびTREX計測の軽減）を有効 `estimator_options` にします。 TREXの学習予算（`measure_noise_learning`）を除き、これらのすべてについて、関数のデフォルト値は元のチュートリアルとすでに一致しています。呼び出し元から指定された値は、関数のデフォルト値と統合されるのではなく、それらを全面的に上書き `estimator_options` してしまうため、ブロック全体が依然として記述されています。そのため、キーを省略した場合、関数のデフォルト値ではなく、 IBM Quantum Compute のデフォルト値が使用されることになります。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "large-s3-run",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "job ID (save this to reconnect later): 43ed8d07-6d7d-4f33-b70a-7f31b765b310\n"
          ]
        }
      ],
      "source": [
        "# Steps 2 + 3: the function compresses (varied ansatz) and executes on hardware.\n",
        "job = fn.run(\n",
        "    t_steps=time_steps,\n",
        "    aqc_segments=[\n",
        "        {\n",
        "            \"n_steps\": 6,\n",
        "            \"ansatz_steps\": 1,\n",
        "        },  # early steps -> shallow 1-layer ansatz\n",
        "        {\n",
        "            \"n_steps\": 4,\n",
        "            \"ansatz_steps\": 2,\n",
        "        },  # later steps -> deeper 2-layer ansatz\n",
        "    ],\n",
        "    aqc_options={\n",
        "        \"max_bond\": mps_max_bond,  # 128 for the longer chain\n",
        "        \"cutoff\": mps_cutoff,\n",
        "        \"optimizer_settings\": {\n",
        "            \"method\": \"L-BFGS-B\",\n",
        "            \"jac\": True,\n",
        "            \"options\": {\"maxiter\": 100},\n",
        "        },\n",
        "    },\n",
        "    dt=dt,\n",
        "    hamiltonian=H,\n",
        "    initial_state=gs_circuit,\n",
        "    backend_name=\"ibm_pittsburgh\",\n",
        "    # Mitigation settings from the original tutorial. Only the two\n",
        "    # measure_noise_learning values differ from the function's defaults; the rest\n",
        "    # restates them, because a caller-supplied estimator_options dict replaces the\n",
        "    # function's defaults wholesale rather than merging into them.\n",
        "    estimator_options={\n",
        "        \"environment\": {\"job_tags\": [\"TUT-SNS\"]},\n",
        "        \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XY4\"},\n",
        "        \"twirling\": {\n",
        "            \"enable_gates\": True,\n",
        "            \"num_randomizations\": 1000,\n",
        "            \"shots_per_randomization\": 128,\n",
        "        },\n",
        "        \"resilience\": {\n",
        "            \"measure_mitigation\": True,\n",
        "            \"measure_noise_learning\": {\n",
        "                \"num_randomizations\": 32,\n",
        "                \"shots_per_randomization\": 100,\n",
        "            },\n",
        "        },\n",
        "    },\n",
        ")\n",
        "print(\"job ID (save this to reconnect later):\", job.job_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "large-reconnect-md",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"長時間実行中のジョブへの再接続\">\n",
        "  大規模な実行には時間がかかり、その時間のほとんどはQPU上ではなく、従来型CPU上で処理されています。 AQC圧縮は、データがQPUに到達する前に、関数内部で実行されます。30カ所のサイトにおいて、この `max_bond=128` 処理には約4時間かかりましたが、このチュートリアルの冒頭にある「 *使用時間の見積もり* 」で示されているQPUの所要時間は約18分でした。 これら2つに加えて、キュー待ちが発生します。 このノートブックやカーネルは、実行中は開いたままにしておく必要はありません。\n",
        "\n",
        "  前のセルに表示されているジョブIDをコピーして、保存してください。 次の3つのセルでは、後で処理を再開することができます：\n",
        "\n",
        "  1. 再接続（新しいカーネルセッションでのみ必要）： [セットアップ](#setup)セルを再実行して再作成し `serverless`、保存しておいたIDからハンド `job` ルを再構築してください。 送信したセッションがまだ有効な場合は、このセルをスキップしてください。ハンドルはすでに有効になっているためです。\n",
        "  2. ステータスの確認：結果が表示されるまで再実行してください `DONE`。\n",
        "  3. 結果を取得する：ステータスが になった場合にのみ実行する `DONE`。\n",
        "\n",
        "  次の再接続セルにはプレースホルダーが入っています。 これを自分のものに置き換えてください `job_id`：\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "large-reconnect",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Reconnect to a previously submitted job by its ID. Only needed in a NEW kernel\n",
        "# session; if you are still in the session where you submitted, the `job` handle\n",
        "# from the preceding cell is already live, so skip this cell. Replace the ID that follows with your own.\n",
        "job = serverless.get_job_by_id(\"<your job ID>\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 27,
      "id": "large-status",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DONE\n"
          ]
        }
      ],
      "source": [
        "# Check where the job is. Re-run this until it reports DONE before fetching the\n",
        "# result in the following cell: QUEUED -> INITIALIZING -> RUNNING: OPTIMIZING_FOR_HARDWARE ->\n",
        "# RUNNING: WAITING_FOR_QPU -> RUNNING: EXECUTING_QPU -> RUNNING: POST_PROCESSING\n",
        "# -> DONE.\n",
        "print(job.status())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "large-s3-result",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AQC fidelities: {'1': 1.0, '2': 0.9994, '3': 0.9944, '4': 0.9853, '5': 0.9747, '6': 0.959, '7': 0.9495, '8': 0.9542, '9': 0.9533, '10': 0.9451}\n"
          ]
        }
      ],
      "source": [
        "# Run this only once the preceding status cell reports DONE. result() blocks until\n",
        "# the job finishes, so calling it earlier just waits (possibly for hours).\n",
        "result = job.result()\n",
        "print(\n",
        "    \"AQC fidelities:\",\n",
        "    {k: round(v, 4) for k, v in result[\"metadata\"][\"aqc_fidelities\"].items()},\n",
        ")\n",
        "\n",
        "ev = np.array(result[\"expectation_values\"])\n",
        "Gjjc = ev[1:]  # drop the t = 0 row -> shape (time_steps, n)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "large-s4-md",
      "metadata": {},
      "source": [
        "<span id=\"step-4-post-process-and-return-result-in-desired-classical-format\" />\n",
        "\n",
        "### ステップ4：後処理を行い、結果を所望の従来の形式で出力する\n",
        "\n",
        "シミュレータ実行時と同様の後処理を行う：グリーン関数をフーリエ変換して $S(q, \\omega)$ とし、鏡像対称化を行い、負の値をクリップする。 鎖が長くなり、進化が進むにつれて、2スピノン連続体ははるかに鮮明に解明されるようになった。 破線の境界線の間の帯を埋め、 $q = \\pi$ 付近で最も明るく見えるはずです。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "id": "large-result",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/extracted-outputs/large-result-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/extracted-outputs/large-result-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "n = result[\"metadata\"][\"n\"]\n",
        "q_res, w_res = 100, 100\n",
        "spectrum = get_spectrum(n, Gjjc, dt, time_steps, q_res, w_res)\n",
        "spectrum = -(spectrum + spectrum[:, ::-1]) / 2  # mirror symmetry\n",
        "spectrum = np.clip(spectrum, a_min=0, a_max=None)  # clip negatives\n",
        "\n",
        "plot_green(\n",
        "    n,\n",
        "    Gjjc,\n",
        "    time_steps,\n",
        "    dt,\n",
        "    title=f\"Retarded Green's function - {n} qubits (AQC, hardware)\",\n",
        ")\n",
        "plot_spectrum(\n",
        "    spectrum,\n",
        "    dt,\n",
        "    q_res,\n",
        "    w_res,\n",
        "    lower_bound=True,\n",
        "    upper_bound=True,\n",
        "    title=f\"Dynamical structure factor - {n} qubits (AQC, hardware)\",\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "appendix-md",
      "metadata": {},
      "source": [
        "<span id=\"appendix\" />\n",
        "\n",
        "## 別紙\n",
        "\n",
        "前述のハードウェアの例では、1つのチェーン長が実行されます。 以下に示す3つのスペクトルは、この同じワークフローを10、20、30の `ibm_pittsburgh` サイトで以前のハードウェア上で実行した結果であり、その他の入力パラメータはすべて固定されています。具体的には、20のトロッターステップ `dt = 0.6`、6つの1層および4つの2層のAQC圧縮ステップからなる圧縮プラン、および です `max_bond = 128`。 これらは記録された結果であり、前のセルからの出力ではありません。\n",
        "\n",
        "3つのサイズすべてで同じ設定が使用されているため、スペクトルは直接比較可能です。 例えば、チェーンの長さに応じて調整したり、基底状態のアンザッツ層を増やしたり、の値を大きくしたりすることで `max_bond`、ここで示したどの結果よりも優れた結果が得られる可能性があります。\n",
        "\n",
        "![10サイトにおける動的構造因子。下限付近のq = πに、単一の鋭い明るいピークが見られる。10](https://quantum.cloud.ibm.com/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/appendix-dsf-10.avif \"キュービット\")\n",
        "\n",
        "![20サイトにおける動的構造因子。スペクトル重みは、2本の破線の2スピノン境界](https://quantum.cloud.ibm.com/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/appendix-dsf-20.avif \"の間の帯域を埋める。20キュービット\")\n",
        "\n",
        "![30サイトにおける動的構造因子。連続領域はより細かく分解されているが、コントラストは弱く、境界外にも一部の重みが割り当てられている。30](https://quantum.cloud.ibm.com/docs/images/tutorials/simulate-neutron-scattering-with-a-serverless-workflow/appendix-dsf-30.avif \"キュービット\")\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "nextsteps",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * このワークフローを自身のシステムに合わせて調整してください。この関数は、任意の 1D 近傍法を受け入れるため `SparsePauliOp`、異なる連鎖ハミルトニアン、初期状態、あるいは観測量セットであっても、PRE → FUNCTION → POSTという同じパイプラインで実行されます。 [GitHub の「AQC Dynamics](https://github.com/qiskit-community/qiskit-function-templates/tree/main/physics/aqc_trotter) 」テンプレートで、入出力契約の全文をご確認ください。\n",
        "  * このベンチマークの出典となった論文をご覧ください：Lee et al., [*中性子散乱実験を用いた量子シミュレーションのベンチマーク*](https://arxiv.org/abs/2603.15608) （ arXiv:2603.15608 ）。\n",
        "  * [元の「中性子散乱のシミュレーション」](/docs/tutorials/simulate-neutron-scattering) チュートリアルと比較すると、このインラインワークフローは、デプロイ済みの関数テンプレートに移植されたものです。\n",
        "  * ハードウェア実行に適用される[エラー軽減および抑制手法](/docs/guides/error-mitigation-and-suppression-techniques)、すなわち動的デカップリング、パウリ・トゥワーリング、TREXについてさらに詳しく見ていきましょう。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "hours": 4,
    "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"
    },
    "qpuSeconds": 1080
  },
  "nbformat": 4,
  "nbformat_minor": 5
}