{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "38b90986-2529-4974-9dbd-931f3089b7fa",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"REST APIを使用した実行モード\"\n",
        "description: \"IBM Quantum Compute Service セッションで量子コンピューティングジョブを実行する方法。\"\n",
        "---\n",
        "\n",
        "<span id=\"execution-modes-using-rest-api\" />\n",
        "\n",
        "# REST APIを使用した実行モード\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d501206a-c250-4df7-befc-317678659d32",
      "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",
        "<details>\n",
        "  <summary><b>パッケージ・バージョン</b></summary>\n",
        "\n",
        "  このページのコードは、以下の要件に基づいて開発されました。\n",
        "  これらのバージョン以降のご利用をお勧めします。\n",
        "\n",
        "  ```\n",
        "  qiskit[all]~=2.3.0\n",
        "  ```\n",
        "</details>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2153584e-5711-4168-a4a5-0b94d02dd3e7",
      "metadata": {},
      "source": [
        "IBM Quantum のプリミティブ・ワークロードは、REST API を使用して、ニーズに応じて「ジョブ」、「セッション」、「バッチ」の3つの実行モードのいずれかで実行できます。 このトピックでは、これらのモードについて解説します。\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  このドキュメントでは、 Python`requests` モジュールを使用して、 IBM Quantum Compute ServiceのREST APIについて解説します。 ただし、このワークフローは、REST API の操作をサポートするあらゆる言語やフレームワークを使用して実行することができます。 詳細については、 [APIリファレンス](/docs/api/qiskit-ibm-runtime/tags/jobs)を参照してください。\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"job-mode-with-rest-api\" />\n",
        "\n",
        "## REST APIを使用したジョブモード\n",
        "\n",
        "ジョブモードでは、コンテキストマネージャーを使用せずに、Estimator または Sampler に対して単一のプリミティブリクエストが行われます。 [Estimator](/docs/guides/estimator-rest-api) と [Sampler](/docs/guides/sampler-rest-api) を使用して量子回路を実行する方法については、いくつかの例をご覧ください。\n",
        "\n",
        "<span id=\"session-mode-with-rest-api\" />\n",
        "\n",
        "## REST APIを使用したセッションモード\n",
        "\n",
        "セッションとは、量子コンピュータ上で複数のジョブからなる反復的なワークロードを効率的に実行できる機能です。 セッションを使用することで、各ジョブを個別にキューに入れることによって生じる遅延を回避できます。これは、古典リソースと量子リソースの間で頻繁な通信を必要とする反復的なタスクにおいて、特に有用です。 Sessionsに関する詳細については、 [ドキュメント](/docs/guides/execution-modes)をご覧ください。\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  オープンプランのユーザーはセッションジョブを提出できません。\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"start-a-session\" />\n",
        "\n",
        "### セッションを開始する\n",
        "\n",
        "セッションを作成し、セッションIDを取得することから始める。\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "auth_id = \"Bearer <YOUR_BEARER_TOKEN>\"\n",
        "backend = \"<BACKEND_NAME>\"\n",
        "crn = \"<SERVICE-CRN>\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Content-Type\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"mode\": 'dedicated',\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "\n",
        "print(response.json())\n",
        "```\n",
        "\n",
        "出力\n",
        "\n",
        "```text\n",
        "{'id': 'crw9s7cdbt40008jxesg'}\n",
        "```\n",
        "\n",
        "<span id=\"close-a-session\" />\n",
        "\n",
        "### セッションを閉じる\n",
        "\n",
        "すべての仕事が終わったら、 `Session` 。 これにより、後続のユーザーの待ち時間が短縮される。\n",
        "\n",
        "```python\n",
        "closureURL=\"https://quantum.cloud.ibm.com/api/v1/sessions/\"+sessionId+\"/close\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "closure_response = requests.request(\n",
        "    \"DELETE\",\n",
        "    closureURL,\n",
        "    headers=headersList\n",
        "    )\n",
        "\n",
        "print(\"Session closure response ok?:\",closure_response.ok,closure_response.text)\n",
        "```\n",
        "\n",
        "出力\n",
        "\n",
        "```text\n",
        "Session closure response ok?: True\n",
        "```\n",
        "\n",
        "<span id=\"batch-mode-with-rest-api\" />\n",
        "\n",
        "## バッチモードとREST API\n",
        "\n",
        "あるいは、リクエストのペイ `mode` ロードに を指定して、バッチジョブを送信することもできます。 すべてのジョブを最初に用意できれば、バッチ処理によって処理時間を短縮できます。 [実行モードの概要](/docs/guides/execution-modes#batch-mode)ガイドで、バッチモードについて学びましょう。\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn,\n",
        "  'Content-Type': 'application/json'\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"instance\": \"hub1/group1/project1\",\n",
        "  \"mode\": \"batch\"\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "```\n",
        "\n",
        "<span id=\"examples-of-jobs-submitted-in-a-session\" />\n",
        "\n",
        "## セッションで提出されたジョブの例\n",
        "\n",
        "セッションが設定されると、セッションIDを指定することにより、1つまたは複数のサンプラーまたはエスティメーターのジョブを同じセッションに投入することができます。\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  `PUB` の `<parameter values>` は、単一のパラメーターか、パラメーターのリストである。 また、 `numpy` 。\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"estimator-jobs-in-session-mode\" />\n",
        "\n",
        "### セッションモードにおける推定器ジョブ\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, 4 observables\" label=\"1 circuit, 4 observables\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [obs1, obs2, obs3, obs4]]], #primitive unified blocs (PUBs) containing one circuit each.\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 4 observables, 2 parameter sets\" label=\"1 circuit, 4 observables, 2 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [[obs1], [obs2], [obs3], [obs4]], [[vals1], [vals2]]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 2 observables\" label=\"2 circuits, 2 observables\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'estimator',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, obs1],[resulting_qasm, obs2]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "<span id=\"sampler-jobs-in-session-mode\" />\n",
        "\n",
        "### セッションモードのサンプラージョブ\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, no parameters\" label=\"1 circuit, no parameters\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 3 parameter sets\" label=\"1 circuit, 3 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [vals1, vals2, vals3]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 1 parameter set\" label=\"2 circuits, 1 parameter set\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'sampler',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, [val1]],[resulting_qasm,None,100]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 次のステップ\n",
        "\n",
        "<Admonition type=\"tip\" title=\"推奨事項\">\n",
        "  * REST API を使用した [Sampler](/docs/guides/sampler-rest-api) プリミティブの詳細な例を確認してください。\n",
        "  * REST API を使用した [Estimator](/docs/guides/estimator-rest-api) プリミティブの詳細な例を確認してください。\n",
        "  * プリミティブの練習は、 IBM Quantum® Learning の [Cost function レッスンで行って](/learning/courses/variational-algorithm-design/cost-functions)ください。\n",
        "  * 「[トランスパイル](/docs/guides/transpile) 」のセクションで、ローカルでのトランスパイル方法について学びましょう。\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
}