{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "2d6582ed-04c1-44bb-9dd8-042d46bd8a7b",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"집행자 빠른 시작\"\n",
        "description: \"qiskit-ibm-runtime에서 Executor 프리미티브를 사용하는 방법.\"\n",
        "\n",
        "---\n",
        "\n",
        "<span id=\"executor-quickstart\" />\n",
        "\n",
        "# 집행자 빠른 시작\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b91b019e-f1d9-4a7f-9c5a-68ead8bf2a6d",
      "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",
        "    samplomatic~=0.21.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e82a5b3c-eed9-41fe-8940-e88838101ca3",
      "metadata": {},
      "source": [
        "[Sampler](/docs/guides/get-started-with-sampler) 프리미티브와 마찬가지로, Executor는 양자 회로 실행 시 출력 레지스터를 샘플링하지만, 내장된 오류 억제 또는 완화 기능은 없습니다. 오히려 이는 클라이언트 측에서 설계 의도를 파악할 수 있는 요소를 제공하고, 비용이 많이 드는 회로 변형 생성을 서버 측으로 이전하는 [지시형 실행](/docs/guides/directed-execution-model) 모델의 일부입니다. 실행기는 회로 주석 및 옵션에 명시된 지침을 따르고, 매개변수 값을 생성 및 바인딩하며, 하드웨어에서 바인딩된 회로를 실행한 후 실행 결과와 메타데이터를 반환합니다. 이 시스템은 사용자를 대신해 암묵적으로 결정을 내리지 않으며, 사용자에게 완전한 통제권과 투명성을 제공합니다.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  Qiskit 패키지에는 아직 Executor 기본 객체를 위한 기본 클래스가 없습니다.\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"before-you-begin\" />\n",
        "\n",
        "## 시작하기 전에\n",
        "\n",
        "`samplex`이 페이지의 일부 코드 예제에서는 Samplomatic 패키지의 일부인 를 사용합니다.  따라서, 해당 코드 블록을 실행하기 전에 다음 코드 블록에 표시된 대로 Samplomatic을 설치해야 합니다.  자세한 내용은 [Samplomatic](https://qiskit.github.io/samplomatic) 설명서를 참조하십시오.\n",
        "\n",
        "```python\n",
        "pip install samplomatic\n",
        "\n",
        "# For visualization support, include the visualization dependencies.\n",
        "# pip install samplomatic[vis]\n",
        "```\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9112ddbd-7101-4cac-a53f-5ecf492bc8d4",
      "metadata": {},
      "source": [
        "<span id=\"steps-to-use-the-executor-primitive\" />\n",
        "\n",
        "## Executor 기본 객체 사용 방법\n",
        "\n",
        "<span id=\"1-initialize-the-account\" />\n",
        "\n",
        "### 1. 계정 초기화\n",
        "\n",
        "IBM Quantum Compute Service는 관리형 서비스이므로, 먼저 계정을 초기화해야 합니다. 그런 다음 기대값을 계산하는 데 사용할 QPU를 선택할 수 있습니다.\n",
        "\n",
        "아직 계정이 없다면 [‘ IBM Cloud® 계정](/docs/guides/cloud-setup) 설정’의 단계에 따라 진행해 주세요.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "c0b08867-a635-481e-ac4f-52359382c94d",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_runtime import QiskitRuntimeService, Executor\n",
        "from qiskit_ibm_runtime.quantum_program import QuantumProgram\n",
        "from qiskit.circuit import QuantumCircuit\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "from samplomatic.transpiler import generate_boxing_pass_manager\n",
        "from samplomatic import build\n",
        "\n",
        "# Initialize the service and choose a backend\n",
        "service = QiskitRuntimeService()\n",
        "backend = service.least_busy(operational=True, simulator=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "ec105ea7-d806-4333-92af-2d7c578c67d9",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "<IBMBackend('ibm_fez')>\n"
          ]
        }
      ],
      "source": [
        "print(backend)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "89c4ffd9-acde-4b1f-8ada-fc39b7a708ed",
      "metadata": {},
      "source": [
        "<span id=\"2-create-and-transpile-a-circuit\" />\n",
        "\n",
        "### 2. 회로 생성 및 트랜스파일링\n",
        "\n",
        "Executor 기본 요소를 사용하려면 최소한 하나의 회로가 필요합니다.  선택적으로 매개변수를 가질 수 있습니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "7671b4dd-b031-44b7-bd4a-48dd39fb93f4",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generate the circuit\n",
        "circuit = QuantumCircuit(2)\n",
        "circuit.h(0)\n",
        "circuit.h(1)\n",
        "circuit.cz(0, 1)\n",
        "circuit.h(1)\n",
        "\n",
        "# Using `measure_all` automatically creates the necessary\n",
        "# classical registers.\n",
        "circuit.measure_all()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "127d6de9-084e-47d5-82d6-f2197c0bd74c",
      "metadata": {},
      "source": [
        "이 회로는 QPU에서 지원하는 명령어만 사용하도록 변환되어야 합니다(이를 *명령어 집합 아키텍처(ISA)* 회로라고 합니다). 이를 수행하려면 트랜스파일러를 사용하세요.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "7a98fb20-8731-43f3-a81c-fb2bc8cba9db",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Transpile the circuit\n",
        "preset_pass_manager = generate_preset_pass_manager(\n",
        "    backend=backend, optimization_level=0\n",
        ")\n",
        "isa_circuit = preset_pass_manager.run(circuit)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "172b3622-adbb-43f6-9cec-b70dc72094e0",
      "metadata": {},
      "source": [
        "<span id=\"3-initialize-a-quantumprogram\" />\n",
        "\n",
        "### 3. ` `QuantumProgram` ` 객체를 초기화합니다\n",
        "\n",
        "작업 부하에 맞춰 를 `QuantumProgram` 초기화하십시오. `QuantumProgramItems`A는 `QuantumProgram` 로 구성된다. 일반적으로 각 항목은 회로, 일련의 매개변수 값, 그리고 경우에 따라 회로 내용을 무작위화하기 위한 요소로 `samplex` 구성됩니다. 자세한 내용은 [‘Executor 입력 및 출력’을](/docs/guides/executor-input-output) 참조하십시오.\n",
        "\n",
        "다음 셀은 를 `QuantumProgram` 초기화하고 25회의 시뮬레이션을 수행하도록 지정합니다. 다음으로, 트랜스파일링된 대상 회로를 추가합니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "eb6719cf-c7f1-4265-8602-9a65071a2dd5",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Initialize an empty program\n",
        "program = QuantumProgram(shots=25)\n",
        "\n",
        "# Append the circuit to the program\n",
        "program.append_circuit_item(isa_circuit)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "da542e9b-f143-4651-ab3d-86fb54c066ab",
      "metadata": {},
      "source": [
        "<span id=\"4-optional-group-gates-and-measurements-into-annotated-boxes\" />\n",
        "\n",
        "### 4. 선택 사항: 게이트와 측정값을 주석이 달린 상자로 묶기\n",
        "\n",
        "명령어를 상자에 묶어 주석을 달아주는 것이 의도를 명확히 전달하는 가장 기본적인 방법입니다. 다음 예제에서는 및 그 트위링 매개변수를 사용하여 `generate_boxing_pass_manager` 2-큐비트 게이트와 측정 연산을 상자로 묶고 트위링 주석을 적용합니다.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "245a4574-3ce9-4f77-98c8-af32cde8ac01",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/get-started-with-executor/extracted-outputs/245a4574-3ce9-4f77-98c8-af32cde8ac01-0.svg\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Generate a boxing pass manager to group gates\n",
        "# and measurements into boxes and add\n",
        "# a`Twirl` annotation.\n",
        "boxes_pm = generate_boxing_pass_manager(\n",
        "    # Add gate twirling\n",
        "    enable_gates=True,\n",
        "    # Add measurement twirling\n",
        "    enable_measures=True,\n",
        ")\n",
        "\n",
        "boxed_circuit = boxes_pm.run(isa_circuit)\n",
        "boxed_circuit.draw(\"mpl\", idle_wires=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2b2fe4a7-2a1c-489e-9063-3084edfc2517",
      "metadata": {},
      "source": [
        "<span id=\"5-optional-build-a-template-circuit-and-samplex-and-add-them-to-the-program\" />\n",
        "\n",
        "### 5. 선택 사항: 템플릿 회로와 샘플렉스를 제작하여 프로그램에 추가합니다\n",
        "\n",
        "다음으로, Samplomatic [빌드](https://qiskit.github.io/samplomatic/api/auto/samplomatic.build.html#samplomatic.build) 방식을 사용하여 *템플릿 회로* 와 *samplex* 쌍을 생성합니다. 이 템플릿 회로는 구조적으로 원래 회로와 동일합니다. 그러나 규정된 주석(이 예에서는 게이트 및 측정 트위링)을 구현하기 위해 단일 큐비트 게이트가 매개변수화 게이트로 대체됩니다. 이 샘플렉스는 템플릿 회로의 무작위 매개변수를 생성하는 데 필요한 모든 정보를 인코딩합니다.\n",
        "\n",
        "템플릿 회로와 샘플렉스 쌍을 생성한 후, 메서드를 `append_samplex_item` 사용하여 해당 쌍을 프로그램에 추가하십시오.\n",
        "\n",
        "및 그 인자에 대한 `samplomatic.samplex.Samplex` 자세한 내용은 Samplomatic [API](https://qiskit.github.io/samplomatic/api/index.html) 문서를 참조하십시오.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "47bbeef2-2d85-4495-b740-2e64eb9066b7",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Build the template circuit and the samplex\n",
        "template_circuit, samplex = build(boxed_circuit)\n",
        "\n",
        "# Append the template circuit and samplex as a `samplex_item`\n",
        "program.append_samplex_item(\n",
        "    template_circuit,\n",
        "    samplex=samplex,\n",
        "    shape=(num_randomizations := 20,),\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3733cce7-15d5-4c04-a1cd-0bf83e94aeaf",
      "metadata": {},
      "source": [
        "<span id=\"6-invoke-executor-and-get-results\" />\n",
        "\n",
        "### 6. Executor 호출 및 결과 확인\n",
        "\n",
        "기본 옵션을 사용하여 프라이머리 `Executor` (primitive)를 통해 IBM® 백엔드에서 를 `QuantumProgram` 실행합니다. 사용 가능한 옵션에 대해서는 [‘실행기 옵션’을](/docs/guides/executor-options) 참조하십시오.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "b767050c-0299-4100-8be4-b73b0587e088",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<RuntimeJobV2('dab7lcrvpcac73ddek40', 'executor')>"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Initialize an Executor with the default options\n",
        "executor = Executor(mode=backend)\n",
        "\n",
        "# Submit the job\n",
        "job = executor.run(program)\n",
        "job"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "a341681d-0704-4800-af65-e49b7627bb36",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Retrieve the result\n",
        "result = job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e649245b-633d-4123-ad55-9971b9366433",
      "metadata": {},
      "source": [
        "[`QuantumProgramResult`](/docs/api/qiskit-ibm-runtime/results-quantum-program-result)결과는 형입니다. 결과 객체에 대한 자세한 내용은 [‘Executor 입력 및 출력’을](/docs/guides/executor-input-output) 참조하십시오.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a6e149b1-de4f-41bb-b972-0781f082fa45",
      "metadata": {},
      "source": [
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 다음 단계\n",
        "\n",
        "<Admonition type=\"tip\" title=\"권장사항\">\n",
        "  * [Executor 예제를](/docs/guides/executor-examples) 직접 해보세요.\n",
        "  * [실행자의 입력과 출력을](/docs/guides/executor-input-output) 이해한다.\n",
        "  * [Executor 브로드캐스팅의 동작 원리에](/docs/guides/executor-broadcasting) 대해 알아보세요.\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
}