{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "066d7e4d-a975-4519-b56f-095f861be3ac",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"見積もりツールの入力と出力\"\n",
        "description: \"Estimatorプリミティブの入力および出力形式を理解する\"\n",
        "---\n",
        "\n",
        "<span id=\"estimator-inputs-and-outputs\" />\n",
        "\n",
        "# 見積もりツールの入力と出力\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "23e7dff0-fde5-4c2d-89c2-fc5ab99240fe",
      "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": "90d0c1e0-28e7-48da-a35f-6016fddea82c",
      "metadata": {},
      "source": [
        "このページでは、 IBM Quantum® のコンピューティングリソース上でワークロードを実行する「 IBM Quantum Estimator」プリミティブの入力と出力の概要について説明します。 Estimator を使用すると、 [**Primitive Unified Bloc（ PUB ）**](/docs/guides/primitive-input-output#pubs) と呼ばれるデータ構造を活用して、ベクトル化されたワークロードを効率的に定義することができます。 これらは、Estimatorプリミティブのメソッド [`run()`](/docs/api/qiskit-ibm-runtime/estimator-v2#run) への入力として使用され、そのメソッドは定義されたワークロードをジョブとして実行します。 その後、ジョブが完了すると、結果は、使用されたPUBと、プリミティブから指定された実行時オプションの両方に依存する形式で返されます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "83a5fdd8-6547-47c7-9441-a7458edc7896",
      "metadata": {},
      "source": [
        "<span id=\"inputs\" />\n",
        "\n",
        "## 入力\n",
        "\n",
        "各 PUB は、以下の形式になっています：\n",
        "\n",
        "(`<single circuit>`, `<one or more observables>`, `<optional one or more parameter values>`, `<optional precision>`),\n",
        "\n",
        "オプションは、リストまたは `parameter values` 単一のパラメータにすることができます。 オブザーバブルの要素とパラメータ値は、「 [プリミティブ入力と出力](primitive-input-output#broadcasting-rules) 」のトピックで説明されている NumPy のブロードキャスト規則に従って結合され、ブロードキャストされた形状の各要素に対して1つの期待値の推定値が返されます。\n",
        "\n",
        "<Admonition types=\"note\">\n",
        "  入力に測定値が含まれている場合、それらは無視されます。\n",
        "</Admonition>\n",
        "\n",
        "Estimatorプリミティブの場合、 PUB には最大4つの値を含めることができます：\n",
        "\n",
        "* 1つのオブジェクト、または複数の [`Parameter`](/docs/api/qiskit/qiskit.circuit.Parameter)`QuantumCircuit` オブジェクトを含むシングル\n",
        "* 推定する期待値を指定する1つ以上の観測変数のリストで、配列として構成されたもの（例えば、単一の観測変数は0次元配列として、観測変数のリストは1次元配列として表されるなど）。 データは、 `SparsePauliOp``Pauli`、 `PauliList`、、などのいずれかの `ObservablesArrayLike` 形式 `str`で指定できます。\n",
        "  <Admonition type=\"note\" title=\"通勤時の観測値\">\n",
        "    * [このメソッド](/docs/api/qiskit/qiskit.quantum_info.PauliList#group_qubit_wise_commuting)を使用すると、 **同じ PUB 内の**コミューティング観測量がグループ化されます。\n",
        "    * 異なるPUBにある通勤観測量は、たとえ同じ回路に属していても、同じ測定値を用いて推定されることはありません。 各 PUB は異なる測定基準を表しているため、各 PUB に対して個別の測定を行う必要があります。\n",
        "    * 通勤に関する観測値が同じ測定値を用いて推定されるようにするため、それらを同じ PUB 内にグループ化してください。\n",
        "  </Admonition>\n",
        "* 回路をバインドするためのパラメータ値の集合。 これは、単一の配列のようなオブジェクトとして指定できます。この場合、最後のインデックスは回路 `Parameter` オブジェクトの数を上回る値とするか、回路にオブジェクト `Parameter` が存在しない場合は省略（あるいは、に設定）します `None`。\n",
        "* （任意）推定する期待値の目標精度\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "846b3109-02a1-4783-ad3f-1c22f753c324",
      "metadata": {},
      "source": [
        "***\n",
        "\n",
        "以下のコードは、 `Estimator` プリミティブへのベクトル化された入力の例を示しており、 IBM®`RuntimeJobV2 ` バックエンド上で単一のオブジェクトとして実行します。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "2f50a9f5-2cc1-4d83-9fe1-1b3a8be0d766",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit.circuit import (\n",
        "    Parameter,\n",
        "    QuantumCircuit,\n",
        ")\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "\n",
        "from qiskit_ibm_runtime import (\n",
        "    QiskitRuntimeService,\n",
        "    EstimatorV2 as Estimator,\n",
        ")\n",
        "\n",
        "import numpy as np\n",
        "\n",
        "# Instantiate runtime service and get\n",
        "# the least busy backend\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(operational=True, simulator=False)\n",
        "\n",
        "# Define a circuit with two parameters.\n",
        "circuit = QuantumCircuit(2)\n",
        "circuit.h(0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.ry(Parameter(\"a\"), 0)\n",
        "circuit.rz(Parameter(\"b\"), 0)\n",
        "circuit.cx(0, 1)\n",
        "circuit.h(0)\n",
        "\n",
        "# Transpile the circuit\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "transpiled_circuit = pm.run(circuit)\n",
        "layout = transpiled_circuit.layout\n",
        "\n",
        "# Now define a sweep over parameter values, the last axis of dimension 2 is\n",
        "# for the two parameters \"a\" and \"b\"\n",
        "params = np.vstack(\n",
        "    [\n",
        "        np.linspace(-np.pi, np.pi, 100),\n",
        "        np.linspace(-4 * np.pi, 4 * np.pi, 100),\n",
        "    ]\n",
        ").T\n",
        "\n",
        "# Define three observables. The inner length-1 lists cause this array of\n",
        "# observables to have shape (3, 1), rather than shape (3,) if they were\n",
        "# omitted.\n",
        "observables = [\n",
        "    [SparsePauliOp([\"XX\", \"IY\"], [0.5, 0.5])],\n",
        "    [SparsePauliOp(\"XX\")],\n",
        "    [SparsePauliOp(\"IY\")],\n",
        "]\n",
        "# Apply the same layout as the transpiled circuit.\n",
        "observables = [\n",
        "    [observable.apply_layout(layout) for observable in observable_set]\n",
        "    for observable_set in observables\n",
        "]\n",
        "\n",
        "# Estimate the expectation value for all 300 combinations of observables\n",
        "# and parameter values, where the pub result will have shape (3, 100).\n",
        "#\n",
        "# This shape is due to our array of parameter bindings having shape\n",
        "# (100, 2), combined with our array of observables having shape (3, 1).\n",
        "estimator_pub = (transpiled_circuit, observables, params)\n",
        "\n",
        "# Instantiate the new Estimator object, then run the transpiled circuit\n",
        "# using the set of parameters and observables.\n",
        "estimator = Estimator(mode=backend)\n",
        "job = estimator.run([estimator_pub])\n",
        "result = job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "90dccb20-1848-4367-a12d-434110ad5a5c",
      "metadata": {},
      "source": [
        "<span id=\"outputs\" />\n",
        "\n",
        "## 出力\n",
        "\n",
        "1つ以上のPUBがQPUに送信されて実行され、ジョブが正常に完了すると、データはコンテナオブジェクト [`PrimitiveResult`](/docs/api/qiskit/qiskit.primitives.PrimitiveResult) として返され、このオブジェクトには `RuntimeJobV2.result()` メソッドを呼び出すことでアクセスできます。\n",
        "\n",
        "には、各 `PrimitiveResult`PUB の実行結果を含む [`PubResult`](/docs/api/qiskit/qiskit.primitives.PubResult) オブジェクトの反復可能なリストが含まれています。\n",
        "\n",
        "このリストの各要素は、プリミティブの `run()` メソッドに送信された各 PUB に対応しています（たとえば、20個のPUBで送信されたジョブは、20個の PUB に対応する20 `PubResult` 個のオブジェクトのリストを含むオブジェクト `PrimitiveResult` を返します）。\n",
        "\n",
        "各Estimator `PubResult` プリミティブには、少なくとも期待値の配列 (`PubResult.data.evs`) と、それに対応する標準偏差（使用 `resilience_level` される に応じて `PubResult.data.ensemble_standard_error` または `PubResult.data.stds` のいずれか）が含まれますが、指定された誤差低減オプションによっては、さらに多くのデータが含まれる場合があります。\n",
        "\n",
        "各オブジェクト `PubResult` は、 `data` とという2 `metadata` つの属性を持っています。\n",
        "\n",
        "* この `data` 属性は、実際の測定値や標準偏差などを含む、 [`DataBin`](/docs/api/qiskit/qiskit.primitives.DataBin) カスタマイズされたデータセットです。\n",
        "* このオブジェクトは、関連する PUB の形状や構造、およびジョブの送信に使用された `DataBin` プリミティブによって指定されたエラー軽減オプション（ [Z](/docs/guides/error-mitigation-and-suppression-techniques#zero-noise-extrapolation-zne)[ NE](/docs/guides/error-mitigation-and-suppression-techniques#probabilistic-error-cancellation-pec) やPECなど）に応じて、さまざまな属性を持つ。\n",
        "* この `metadata` 属性には、使用された実行時およびエラー軽減オプションに関する情報が含まれています（詳細は、このページの「 [結果メタデータ](#result-metadata) 」セクションで後述します）。\n",
        "\n",
        "以下は、Estimatorの出力に関するデータ `PrimitiveResult` 構造の概要図です：\n",
        "\n",
        "```\n",
        "└── PrimitiveResult\n",
        "    ├── PubResult[0]\n",
        "    │   ├── metadata\n",
        "    │   └── data  ## In the form of a DataBin object\n",
        "    │       ├── evs\n",
        "    │       │   └── List of estimated expectation values in the shape\n",
        "    |       |         specified by the first pub\n",
        "    │       └── stds\n",
        "    │           └── List of calculated standard deviations in the\n",
        "    |                 same shape as above\n",
        "    ├── PubResult[1]\n",
        "    |   ├── metadata\n",
        "    |   └── data  ## In the form of a DataBin object\n",
        "    |       ├── evs\n",
        "    |       │   └── List of estimated expectation values in the shape\n",
        "    |       |        specified by the second pub\n",
        "    |       └── stds\n",
        "    |           └── List of calculated standard deviations in the\n",
        "    |                same shape as above\n",
        "    ├── ...\n",
        "    ├── ...\n",
        "    └── ...\n",
        "```\n",
        "\n",
        "簡単に言えば、1つのジョブは オブジェクトを `PrimitiveResult` 返し、1つ以上の `PubResult` オブジェクトのリストを含んでいます。 これらの `PubResult` オブジェクトは、そのジョブに送信された各 PUB の測定データを保存します。\n",
        "\n",
        "以下のコードスニペットは、上記で作成したジョブの（および関連する `PubResult`） `PrimitiveResult` フォーマットを示しています。\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "53a4d5ae-109b-452b-bbc5-2d7940c5182c",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The result of the submitted job had 1 PUBs and has a value:\n",
            " PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(3, 100), dtype=float64>), stds=np.ndarray(<shape=(3, 100), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(3, 100), dtype=float64>), shape=(3, 100)), metadata={'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32})], metadata={'dynamical_decoupling': {'enable': False, 'sequence_type': 'XX', 'extra_slack_distribution': 'middle', 'scheduling_method': 'alap'}, 'twirling': {'enable_gates': False, 'enable_measure': True, 'num_randomizations': 'auto', 'shots_per_randomization': 'auto', 'interleave_randomizations': True, 'strategy': 'active-accum'}, 'resilience': {'measure_mitigation': True, 'zne_mitigation': False, 'pec_mitigation': False}, 'version': 2})\n",
            "\n",
            "The associated PubResult of this job has the following data bins:\n",
            " {result[0].data}\n",
            "\n",
            "And this DataBin has attributes: dict_keys(['evs', 'stds', 'ensemble_standard_error'])\n",
            "Recall that this shape is due to our array of parameter binding setshaving shape (100, 2), where 2 is the number of parameters in the circuit, combined with our array of observables having shape (3, 1). \n",
            "\n",
            "The expectation values measured from this PUB are: \n",
            "{result[0].data.evs}\n",
            "\n"
          ]
        }
      ],
      "source": [
        "print(\n",
        "    f\"The result of the submitted job had {len(result)} \"\n",
        "    f\"PUBs and has a value:\\n {result}\\n\"\n",
        ")\n",
        "print(\n",
        "    \"The associated PubResult of this job has the following data bins:\\n \"\n",
        "    \"{result[0].data}\\n\"\n",
        ")\n",
        "print(f\"And this DataBin has attributes: {result[0].data.keys()}\")\n",
        "print(\n",
        "    \"Recall that this shape is due to our array of parameter binding sets\"\n",
        "    \"having shape (100, 2), where 2 is the number of parameters in the \"\n",
        "    \"circuit, combined with our array of observables having shape (3, 1). \\n\"\n",
        ")\n",
        "with np.printoptions(threshold=200):\n",
        "    print(\n",
        "        \"The expectation values measured from this PUB are: \\n\"\n",
        "        \"{result[0].data.evs}\\n\"\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "000ade51-d940-45f9-84ea-16ad283a930f",
      "metadata": {},
      "source": [
        "<span id=\"how-the-estimator-primitive-calculates-error\" />\n",
        "\n",
        "#### Estimatorプリミティブによる誤差の計算方法\n",
        "\n",
        "Estimatorは、入力PUB（のフィールド `evs``DataBin` ）に渡された観測値の平均値の推定に加え、それらの期待値に関連する誤差の推定値も提供しようと試みます。 Estimatorへのすべてのクエリでは、各期待値について平均の標準誤差のような値が `stds` フィールドに設定されますが、一部の誤差低減オプションでは、などの追加情報が生成 `ensemble_standard_error`されます。\n",
        "\n",
        "単一の観測量 $\\mathcal{O}$ について考える。 [ZNE](/docs/guides/error-mitigation-and-suppression-techniques#zero-noise-extrapolation-zne) が適用されない場合、推定器の実行における各ショットは、期待値 $\\langle \\mathcal{O} \\rangle$ の点推定値を提供するものと考えられる。点ごとの推定値がベクトルである場合、で `Os`返される `ensemble_standard_error` 値は、以下に等しい（ここで、 $\\sigma_{\\mathcal{O}}$ は[期待値の](/docs/api/qiskit/qiskit.primitives.BackendEstimatorV2)推定値の標準偏差、 $N_{shots}$ はショットの数である）：\n",
        "\n",
        "$\\frac{ \\sigma_{\\mathcal{O}} }{ \\sqrt{N_{shots}} },$\n",
        "\n",
        "すべてのショットを単一のアンサンブルの一部として扱う。 [ゲ](/docs/guides/error-mitigation-and-suppression-techniques#pauli-twirling) ート・トゥワリング（`twirling.enable_gates = True`）を指定した場合、 $\\langle \\mathcal{O} \\rangle$ の点ごとの推定値を、共通のトゥワリングを持つグループに分類することができます。 これらの推定値の集合を `O_twirls`と呼び、その数は （ツイ `num_randomizations` ールの数）個である。 ここで、 `O_twirls`はの平均の標準誤差 `stds` であり、次のように表される\n",
        "\n",
        "$\\frac{ \\sigma_{\\mathcal{O}} }{ \\sqrt{N_{twirls}} },$\n",
        "\n",
        "ここで、 $\\sigma_{\\mathcal{O}}$ はの標準偏差であり `O_twirls` 、 $N_{twirls}$ はツイールの数である。 「トゥワリング」を有効にしていない場合、 `stds` と `ensemble_standard_error` は等しくなります。\n",
        "\n",
        "ZNEを有効にすると、前述の `stds` 要素は、外挿モデルに対する非線形回帰における重みとなります。 この `stds` 場合、最終的に返されるのは、ノイズ係数がゼロの時点で評価された適合モデルの不確実性である。 適合度が低い場合や、適合に大きな不確実性がある場合、報告される値は非常に `stds` 大きくなることがあります。 ZNEを有効にすると、 `pub_result.data.evs_noise_factors` と `pub_result.data.stds_noise_factors` にも値が入力されるため、独自の外挿を行うことができます。\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c4341184-a41a-4442-bc05-838c90ea93b8",
      "metadata": {},
      "source": [
        "<span id=\"result-metadata\" />\n",
        "\n",
        "## 結果のメタデータ\n",
        "\n",
        "実行結果に加え、および `PubResult``PrimitiveResult` オブジェクトには、送信されたジョブに関するメタデータ属性が含まれています。 提出されたすべてのPUBに関する情報（利用可能な各種[実行時オプション](/docs/api/qiskit-ibm-runtime/options)など）を含むメタデータは にあり `PrimitiveResult.metatada`、各 PUB 固有のメタデータは にあります `PubResult.metadata`。\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  メタデータフィールドでは、プリミティブの実装は、自身に関連する実行に関するあらゆる情報を返すことができ、ベースプリミティブによって保証されるキーと値のペアは存在しません。 したがって、返されるメタデータは、プリミティブの実装によって異なる場合があります。\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "626ba203-44e2-4b8f-b04d-04388b8b1fa1",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The metadata of the PrimitiveResult is:\n",
            "'dynamical_decoupling' : {'enable': False, 'sequence_type': 'XX', 'extra_slack_distribution': 'middle', 'scheduling_method': 'alap'},\n",
            "'twirling' : {'enable_gates': False, 'enable_measure': True, 'num_randomizations': 'auto', 'shots_per_randomization': 'auto', 'interleave_randomizations': True, 'strategy': 'active-accum'},\n",
            "'resilience' : {'measure_mitigation': True, 'zne_mitigation': False, 'pec_mitigation': False},\n",
            "'version' : 2,\n",
            "\n",
            "The metadata of the PubResult result is:\n",
            "'shots' : 4096,\n",
            "'target_precision' : 0.015625,\n",
            "'circuit_metadata' : {},\n",
            "'resilience' : {},\n",
            "'num_randomizations' : 32,\n"
          ]
        }
      ],
      "source": [
        "# Print out the results metadata\n",
        "print(\"The metadata of the PrimitiveResult is:\")\n",
        "for key, val in result.metadata.items():\n",
        "    print(f\"'{key}' : {val},\")\n",
        "\n",
        "print(\"\\nThe metadata of the PubResult result is:\")\n",
        "for key, val in result[0].metadata.items():\n",
        "    print(f\"'{key}' : {val},\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "celltoolbar": "Raw Cell Format",
    "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
}