{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "008d2ceb-f6fa-42f6-a7df-6bd604775278",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"추정기 빠른 시작\"\n",
        "description: \"IBM Quantum 의 ‘Estimator’ 프리미티브 사용 방법에 대한 빠른 시작 가이드.\"\n",
        "---\n",
        "\n",
        "<span id=\"estimator-quickstart\" />\n",
        "\n",
        "# 추정기 빠른 시작\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "49f269ba-e11d-4e5c-bbba-9d4a10540ad8",
      "metadata": {},
      "source": [
        "Estimator 기본 함수는 양자 회로에 의해 준비된 상태에 대해 하나 이상의 관측 가능 변수의 기대값을 계산합니다. 매개변수 값이 기본 요소의 입력으로 함께 제공되는 한, 회로에 매개변수를 적용할 수 있습니다.\n",
        "\n",
        "이 프리미티브에는 동적 디커플링, 파울리 트위링, 게이트 폴딩 ZNE, PEA, PEC 등 여러 가지 내장된 [오류 완화 및 억제 기법이](/docs/guides/error-mitigation-and-suppression-techniques) 포함되어 있습니다. 또한 비용과 정확도 간의 균형을 손쉽게 조정할 수 있는 `resilience_level` 옵션을 지원합니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b7e96291-0925-4d7f-81a8-a7738549477c",
      "metadata": {},
      "source": [
        "이 주제의 단계에서는 Estimator를 설정하는 방법, 구성에 사용할 수 있는 옵션을 살펴보는 방법, 그리고 프로그램에서 Estimator를 호출하는 방법을 설명합니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "818a2b3d-3950-4a28-8e37-39959c56484b",
      "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.2\n",
        "    qiskit-ibm-runtime~=0.47.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bafa61f0-c049-4ee6-ac76-a0ed97e67caf",
      "metadata": {},
      "source": [
        "{/*Verified the v2 examples 2/29/24 - updated 10/29/24*/}\n",
        "\n",
        "<span id=\"steps-to-use-the-estimator-primitive\" />\n",
        "\n",
        "## 에스티메이터 프리미티브 사용 방법\n",
        "\n",
        "<span id=\"1-initialize-the-account\" />\n",
        "\n",
        "### 1. 계정 초기화\n",
        "\n",
        "먼저 계정을 초기화해야 합니다. 그런 다음 기대값을 계산하는 데 사용할 QPU를 선택할 수 있습니다.\n",
        "\n",
        "아직 계정이 없다면 [‘ IBM Cloud 계정](cloud-setup) 설정’의 단계에 따라 진행해 주세요.\n",
        "\n",
        "<Admonition type=\"note\" title=\"분할 게이트\">\n",
        "  새로 지원되는 [분할 게이트](/docs/guides/fractional-gates) 를 사용하려면, `QiskitRuntimeService` 인스턴스에서 백엔드를 요청할 때 를 `use_fractional_gates=True` 설정하십시오. 예를 들어,\n",
        "\n",
        "  ```python\n",
        "  service = QiskitRuntimeService()\n",
        "  fractional_gate_backend = service.least_busy(use_fractional_gates=True)\n",
        "  ```\n",
        "\n",
        "  이 기능은 실험적인 기능이며, 향후 변경될 수 있습니다.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "71d62ba2-b1ba-405a-b304-5bdd7ec5e11b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ibm_fez\n"
          ]
        }
      ],
      "source": [
        "from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(\n",
        "    operational=True, simulator=False, min_num_qubits=127\n",
        ")\n",
        "\n",
        "print(backend.name)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d894fbe3-3ea8-4db0-908e-95790b560ddb",
      "metadata": {},
      "source": [
        "<span id=\"2-create-a-circuit-and-an-observable\" />\n",
        "\n",
        "### 2. 회로와 관측 가능한 변수를 생성합니다\n",
        "\n",
        "Estimator 기본 요소에 입력으로 최소한 하나의 회로와 하나의 관측값이 필요합니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "c0ad8982-d19b-46d4-8a2d-dd30357c0e52",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit.circuit.library import qaoa_ansatz\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "\n",
        "entanglement = [tuple(edge) for edge in backend.coupling_map.get_edges()]\n",
        "observable = SparsePauliOp.from_sparse_list(\n",
        "    [(\"ZZ\", [i, j], 0.5) for i, j in entanglement],\n",
        "    num_qubits=backend.num_qubits,\n",
        ")\n",
        "circuit = qaoa_ansatz(observable, reps=2)\n",
        "# The circuit is parametrized, so we will define the parameter values for execution\n",
        "param_values = [0.1, 0.2, 0.3, 0.4]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "84b42c6f-d80e-4cff-8e34-03affa566a97",
      "metadata": {},
      "source": [
        "회로와 관측량은 QPU에서 지원하는 명령어만 사용하도록 변환되어야 합니다(이를 *명령어 집합 아키텍처(ISA)* 회로라고 합니다). 이를 위해 트랜스파일러를 사용하세요.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "abefc665-24a7-466e-a9ec-67cac6a50ebd",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Circuit ops (ISA): OrderedDict([('rz', 4472), ('sx', 1884), ('cz', 1120)])\n"
          ]
        }
      ],
      "source": [
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "\n",
        "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n",
        "isa_circuit = pm.run(circuit)\n",
        "isa_observable = observable.apply_layout(isa_circuit.layout)\n",
        "print(f\">>> Circuit ops (ISA): {isa_circuit.count_ops()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b53e9ab3-7d87-4dd5-b362-138b24cfa73b",
      "metadata": {},
      "source": [
        "<span id=\"3-initialize-the-ibm-quantum-estimator\" />\n",
        "\n",
        "### 3. IBM Quantum 추정기를 초기화합니다\n",
        "\n",
        "Estimator를 초기화할 때, 매개변수를 `mode` 사용하여 실행 모드를 지정하십시오.  가능한 값은 각각 배치, 세션, 작업 실행 모드에 대해 `batch`, `session`, 또는 객체입니다 `backend` . 자세한 내용은 [‘ IBM Quantum Compute 서비스 실행 모드 개요’를](/docs/guides/execution-modes) 참조하십시오. Open Plan 사용자는 세션 작업을 제출할 수 없으므로 유의하시기 바랍니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "961508db-e534-4fc9-970d-7babcd6c39ef",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_runtime import EstimatorV2 as Estimator\n",
        "\n",
        "estimator = Estimator(mode=backend)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "59b13a43-0c9f-4fdb-a379-af5115c153e1",
      "metadata": {},
      "source": [
        "<span id=\"4-invoke-estimator-and-get-results\" />\n",
        "\n",
        "### 4. Estimator를 호출하고 결과를 확인합니다\n",
        "\n",
        "다음으로, `run()` 메서드를 호출하여 입력 회로와 관측 변수에 대한 기대값을 계산합니다. 회로, 관측 가능 매개변수 및 선택적 매개변수 값 집합은 *기본 통합 블록* ( PUB ) 튜플 형태로 입력됩니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "f1a60bad-cf09-4136-aa1a-4482759b3aea",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job ID: dab7lfurrl7c7386gjn0\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> Job Status: QUEUED\n"
          ]
        }
      ],
      "source": [
        "job = estimator.run([(isa_circuit, isa_observable, param_values)])\n",
        "print(f\">>> Job ID: {job.job_id()}\")\n",
        "print(f\">>> Job Status: {job.status()}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "c817cce5-4686-43d2-89a1-ed0842d8ace3",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            ">>> PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(), dtype=float64>), stds=np.ndarray(<shape=(), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(), dtype=float64>)), 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",
            "  > Expectation value: 28.60306448415693\n",
            "  > Metadata: {'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32}\n"
          ]
        }
      ],
      "source": [
        "result = job.result()\n",
        "print(f\">>> {result}\")\n",
        "print(f\"  > Expectation value: {result[0].data.evs}\")\n",
        "print(f\"  > Metadata: {result[0].metadata}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d38dd409-e0d8-4749-bb22-58ae9a53d26a",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 다음 단계\n",
        "\n",
        "<Admonition type=\"tip\" title=\"권장사항\">\n",
        "  * 양자 컴퓨터에서 실행하기 전에 [로컬 환경에서 테스트하는](local-testing-mode) 방법을 알아보세요.\n",
        "  * 자세한 [예시를](/docs/guides/estimator-examples) 살펴보세요.\n",
        "  * IBM Quantum Learning 의 [‘Cost’ 함수](/learning/courses/variational-algorithm-design/cost-functions) 강의를 따라가며 기본형(primitives)을 연습해 보세요.\n",
        "  * [‘트랜스파일’](/docs/guides/transpile/) 섹션에서 로컬 환경에서 트랜스파일하는 방법을 알아보세요.\n",
        "  * [‘트랜스파일러 설정 비교’](/docs/guides/circuit-transpilation-settings#compare-transpiler-settings) 가이드를 확인해 보세요.\n",
        "  * [기본 옵션](runtime-options-overview) 사용법을 알아보세요.\n",
        "  * [Estimator](/docs/api/qiskit-ibm-runtime/options-estimator-options) 옵션에 대한 API를 확인하세요.\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
}