{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "0af88701-d9bc-47f2-8ceb-2ae51f567934",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"回路を可視化する\"\n",
        "description: \"Qiskitの可視化モジュールを使用して回路の可視化を作成し、ジョブデータをプロットする\"\n",
        "---\n",
        "\n",
        "{/* cspell:ignore qcircuit mactex, backgroundcolor, lightgreen */}\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8d75dc24-b8d2-45f8-830b-48e45f794a31",
      "metadata": {},
      "source": [
        "<span id=\"visualize-circuits\" />\n",
        "\n",
        "# 回路を可視化する\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7ea76afb-aecf-4ea2-b173-5d5e7e7d68ec",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<Accordion>\n",
        "  <AccordionItem title=\"パッケージ・バージョン\">\n",
        "    このページのコードは、以下の要件に基づいて開発された。\n",
        "    これらのバージョンまたは新しいバージョンの使用をお勧めします。\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.5.1\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bd5865b3-adfa-4c87-be55-51f693335184",
      "metadata": {},
      "source": [
        "自分が作っている回路を見ることは、しばしば役に立つ。 Qiskit回路を表示するには、以下のオプションを使用します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "488c8d7d-5615-40ec-bf84-f1fa94832fce",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit import QuantumCircuit"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8bbddcca-300c-4f20-98dd-a0723cdef026",
      "metadata": {},
      "source": [
        "<span id=\"draw-a-quantum-circuit\" />\n",
        "\n",
        "## 量子回路を描く\n",
        "\n",
        "`QuantumCircuit` クラスは、 `draw()` メソッドによる回路の描画や、回路オブジェクトの印刷をサポートしています。 デフォルトでは、どちらも回路図のアスキーアートバージョンをレンダリングする。\n",
        "\n",
        "`print` は `None` を返しますが、ダイアグラムを印刷するという副作用があります。一方、 `QuantumCircuit.draw` は副作用なしにダイアグラムを返します。 Jupyterノートブックは各セルの最終行の出力を表示するので、同じ効果があるように見える。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "547f07e8-7891-433c-ac53-3186196b3aa7",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Build a quantum circuit\n",
        "circuit = QuantumCircuit(3, 3)\n",
        "circuit.x(1)\n",
        "circuit.h(range(3))\n",
        "circuit.cx(0, 1)\n",
        "circuit.measure(range(3), range(3));"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "d69ae2df-c31c-414f-bba2-4c4a1012de41",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "     ┌───┐          ┌─┐   \n",
            "q_0: ┤ H ├───────■──┤M├───\n",
            "     ├───┤┌───┐┌─┴─┐└╥┘┌─┐\n",
            "q_1: ┤ X ├┤ H ├┤ X ├─╫─┤M├\n",
            "     ├───┤└┬─┬┘└───┘ ║ └╥┘\n",
            "q_2: ┤ H ├─┤M├───────╫──╫─\n",
            "     └───┘ └╥┘       ║  ║ \n",
            "c: 3/═══════╩════════╩══╩═\n",
            "            2        0  1 \n"
          ]
        }
      ],
      "source": [
        "print(circuit)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "04c91fd9-50a1-4ff3-84e4-0b51a6b1541a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "     ┌───┐          ┌─┐   \n",
              "q_0: ┤ H ├───────■──┤M├───\n",
              "     ├───┤┌───┐┌─┴─┐└╥┘┌─┐\n",
              "q_1: ┤ X ├┤ H ├┤ X ├─╫─┤M├\n",
              "     ├───┤└┬─┬┘└───┘ ║ └╥┘\n",
              "q_2: ┤ H ├─┤M├───────╫──╫─\n",
              "     └───┘ └╥┘       ║  ║ \n",
              "c: 3/═══════╩════════╩══╩═\n",
              "            2        0  1 "
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "circuit.draw()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2159af06-93b8-441d-b8aa-c29324d26c6e",
      "metadata": {},
      "source": [
        "<span id=\"alternative-renderers\" />\n",
        "\n",
        "### 代替レンダラー\n",
        "\n",
        "テキスト出力は、回路開発中に出力を素早く確認するのに便利だが、柔軟性に欠ける。 量子回路の出力レンダラーには2つの選択肢がある。 一方は [Matplotlib](https://matplotlib.org/) もう一方は [LaTeX](https://www.latex-project.org/). LaTeX レンダラーには [qcircuit パッケージが](https://github.com/CQuIC/qcircuit)必要です。 output \"引数に文字列 `mpl` と `latex` を設定して、これらのレンダラーを選択する。\n",
        "\n",
        "<Admonition type=\"tip\">\n",
        "  OSXユーザーは、必要な LaTeX パッケージを [mactexパッケージから](https://www.tug.org/mactex/)入手できる。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "3f9c61c9-58f9-4315-a639-455fa2e58450",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/3f9c61c9-58f9-4315-a639-455fa2e58450-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Matplotlib drawing\n",
        "circuit.draw(output=\"mpl\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "94948dab-57de-45f0-8dd7-5901ae69b70a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/94948dab-57de-45f0-8dd7-5901ae69b70a-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Latex drawing\n",
        "circuit.draw(output=\"latex\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "51fc6f51-6345-435d-abed-857f29a3f451",
      "metadata": {},
      "source": [
        "<span id=\"save-output\" />\n",
        "\n",
        "### 出力の保存\n",
        "\n",
        "Jupyterノートブックで大規模な回路をインラインで描くと、時間がかかったり、読めなかったりすることがある。\n",
        "図を直接ファイルに保存し、画像ビューアで開いて必要に応じて拡大することができます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "17889caf-d953-4661-9188-00505c17064e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/17889caf-d953-4661-9188-00505c17064e-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Save as an image using the Matplotlib drawer\n",
        "circuit.draw(output=\"mpl\", filename=\"circuit-mpl.jpeg\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "a36d1aa9-fa0d-4e27-ac83-5deee43a20dd",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/a36d1aa9-fa0d-4e27-ac83-5deee43a20dd-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Or save a LaTeX rendering\n",
        "circuit.draw(output=\"latex\", filename=\"circuit-latex.pdf\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "78688e6c-3ed2-4ef2-b3db-80fdae35e585",
      "metadata": {
        "jp-MarkdownHeadingCollapsed": true
      },
      "source": [
        "<span id=\"control-circuit-drawings\" />\n",
        "\n",
        "### 制御回路図\n",
        "\n",
        "デフォルトでは、 `draw()` メソッドはレンダリングした画像をオブジェクトとして返し、何も出力しません。 返される正確なクラスは、指定された出力によって異なる： `'text'` (デフォルト）は `TextDrawer` オブジェクトを返し、 `'mpl'` は `matplotlib.Figure` オブジェクトを返し、 `latex` は `PIL.Image` オブジェクトを返す。 Jupyterノートブックはこれらのreturn typeを理解し、適切にレンダリングするが、Jupyterの外で実行する場合、画像は自動的に表示されない。\n",
        "\n",
        "`draw()` メソッドには、出力を表示または保存するためのオプション引数がある。 指定された場合、 `filename` kwargはレンダリング出力を保存するパスを取ります。 また、 `mpl` または `latex` 出力を使っている場合は、 `interactive` kwarg を使って画像を新しいウィンドウで開くこともできます（これはノートブック内から常に機能するわけではありません）。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fc41270b-3518-40af-8921-dfa9666fc8e0",
      "metadata": {},
      "source": [
        "<span id=\"customize-the-output\" />\n",
        "\n",
        "### 出力のカスタマイズ\n",
        "\n",
        "出力によっては、回路図をカスタマイズするオプションもある。\n",
        "\n",
        "<span id=\"disable-plot-barriers-and-reverse-bit-order\" />\n",
        "\n",
        "#### プロットバリアを無効化し、ビット順序を反転する\n",
        "\n",
        "最初の2つのオプションは3つのバックエンドで共有される。 ビットオーダーとバリアーを描くかどうかの両方を設定できる。 これらはそれぞれ、 `reverse_bits` kwargと `plot_barriers` kwargで設定できる。 以下の例は、どの出力レンダラーでも動作する。ここでは簡潔にするために `mpl` 。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "db61dc71-4cdc-4bb7-8139-8820e7785e55",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit import QuantumRegister, ClassicalRegister\n",
        "\n",
        "# Draw a new circuit with barriers and more registers\n",
        "q_a = QuantumRegister(3, name=\"a\")\n",
        "q_b = QuantumRegister(5, name=\"b\")\n",
        "c_a = ClassicalRegister(3)\n",
        "c_b = ClassicalRegister(5)\n",
        "\n",
        "circuit = QuantumCircuit(q_a, q_b, c_a, c_b)\n",
        "circuit.x(q_a[1])\n",
        "circuit.x(q_b[1])\n",
        "circuit.x(q_b[2])\n",
        "circuit.x(q_b[4])\n",
        "circuit.barrier()\n",
        "circuit.h(q_a)\n",
        "circuit.barrier(q_a)\n",
        "circuit.h(q_b)\n",
        "circuit.cswap(q_b[0], q_b[1], q_b[2])\n",
        "circuit.cswap(q_b[2], q_b[3], q_b[4])\n",
        "circuit.cswap(q_b[3], q_b[4], q_b[0])\n",
        "circuit.barrier(q_b)\n",
        "circuit.measure(q_a, c_a)\n",
        "circuit.measure(q_b, c_b);"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "8e57cd43-8a48-469d-8f69-8e7c936d4a1e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/8e57cd43-8a48-469d-8f69-8e7c936d4a1e-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Draw the circuit\n",
        "circuit.draw(output=\"mpl\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "8e7a251a-0a4f-43e0-8cf5-48493df7bad9",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/8e7a251a-0a4f-43e0-8cf5-48493df7bad9-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 11,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Draw the circuit with reversed bit order\n",
        "circuit.draw(output=\"mpl\", reverse_bits=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "b4a601ad-1c04-4b16-afbd-ac5a0ad42653",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/b4a601ad-1c04-4b16-afbd-ac5a0ad42653-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 12,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Draw the circuit without barriers\n",
        "circuit.draw(output=\"mpl\", plot_barriers=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "18b0bfbe-b586-4182-9a0d-b858655a9240",
      "metadata": {},
      "source": [
        "<span id=\"renderer-specific-customizations\" />\n",
        "\n",
        "### レンダラー固有のカスタマイズ\n",
        "\n",
        "利用可能なカスタマイズオプションの中には、レンダラー固有のものもあります。\n",
        "\n",
        "`fold` 引数は出力の最大幅を設定する。 `text` レンダラーでは、次の行に折り返す前のダイアグラムの行の長さを設定します。  mpl'レンダラーを使用する場合、これは次の行に折り返す前の（視覚的な）レイヤー数である。\n",
        "\n",
        "`mpl` レンダラーには `style` kwarg があり、色とアウトラインを変更する。 詳細は [APIドキュメントを](/docs/api/qiskit/qiskit.circuit.QuantumCircuit#draw)参照のこと。\n",
        "\n",
        "`scale` オプションは、 `mpl` と `latex` レンダラーの出力をスケーリングする。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "1e08bf74-378f-45e6-b195-a9539061013d",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "   ┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐»\n",
              "q: ┤ H ├┤ H ├┤ H ├┤ H ├┤ H ├┤ H ├┤ H ├»\n",
              "   └───┘└───┘└───┘└───┘└───┘└───┘└───┘»\n",
              "«   ┌───┐┌───┐┌───┐\n",
              "«q: ┤ H ├┤ H ├┤ H ├\n",
              "«   └───┘└───┘└───┘"
            ]
          },
          "execution_count": 13,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "circuit = QuantumCircuit(1)\n",
        "for _ in range(10):\n",
        "    circuit.h(0)\n",
        "# limit line length to 40 characters\n",
        "circuit.draw(output=\"text\", fold=40)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "decadf88-4866-45a0-9e2f-836c51491f9e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/decadf88-4866-45a0-9e2f-836c51491f9e-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 14,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Change the background color in mpl\n",
        "\n",
        "style = {\"backgroundcolor\": \"lightgreen\"}\n",
        "circuit.draw(output=\"mpl\", style=style)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "ade9a653-3243-4ac9-bb0e-c8fb82f7a034",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/ade9a653-3243-4ac9-bb0e-c8fb82f7a034-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 15,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Scale the mpl output to 1/2 the normal size\n",
        "circuit.draw(output=\"mpl\", scale=0.5)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "495b560a-d835-448b-aa01-5025a7a0689e",
      "metadata": {},
      "source": [
        "<span id=\"standalone-circuit-drawing-function\" />\n",
        "\n",
        "### スタンドアロンの回路図作成機能\n",
        "\n",
        "回路オブジェクトのメソッドとしてではなく、自己完結型の関数で回路を描画したいアプリケーションでは、 `qiskit.visualization` からの public stable インターフェイスの一部である `circuit_drawer()` 関数を直接使用できます。 この関数は、必須引数として回路オブジェクトを受け取る以外は、 `circuit.draw()` メソッドと同じ動作をする。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "256dd092-b2eb-47af-a025-0ecdf85c2d5a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/visualize-circuits/extracted-outputs/256dd092-b2eb-47af-a025-0ecdf85c2d5a-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 16,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit.visualization import circuit_drawer\n",
        "\n",
        "circuit_drawer(circuit, output=\"mpl\", plot_barriers=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0761df2f-183f-48e3-9070-766a9920c2b9",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * 回路可視化の例は、チュートリアルの [Grover's Algorithmを](/docs/tutorials/grovers-algorithm)参照してください。\n",
        "  * [IBM Quantum Composer](/docs/guides/composer) を使用して簡単な回路を可視化する。\n",
        "  * [回路のタイミングを可視化する](/docs/guides/visualize-circuit-timing)。\n",
        "  * [Qiskitの可視化API](/docs/api/qiskit/visualization) のドキュメントを確認してください。\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
}