{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "f7d9993f",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Algorithmiq TEM\n",
        "description: Load the TEM function by Algorithmiq, calculate the function size a job needs, and compute an error-mitigated expectation value of a GHZ state.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore QOBLIB */}\n",
        "\n",
        "# Get started with Algorithmiq TEM\n",
        "\n",
        "*See the [overview](/docs/functions/algorithmiq-tem) and the [API reference](/docs/functions/algorithmiq-tem/api-reference)*\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d606b64e",
      "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=\"Package versions\">\n",
        "    The code on this page was developed using the following requirements.\n",
        "    We recommend using these versions or newer.\n",
        "\n",
        "    ```\n",
        "    qiskit[all]~=2.3.0\n",
        "    qiskit-ibm-catalog~=0.11.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2995da29",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Authenticate using your [IBM Quantum Platform API key](http://quantum.cloud.ibm.com/), and select the TEM function as follows. (This snippet assumes you've already [saved your account](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client) to your local environment.)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "cc0a8093",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "tem_function_name = \"algorithmiq/tem\"\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "\n",
        "# Load your function\n",
        "tem = catalog.load(tem_function_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "56b38fd5",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size: `S`, `M`, or `L`. If the size is too small, the job is rejected.\n",
        "If it is larger than needed, the job runs on a bigger compute profile than the work requires. See\n",
        "[Function sizes](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for how sizes work in general.\n",
        "\n",
        "The size comes from your circuit after it is mapped onto the backend that you target:\n",
        "the number of qubits that carry an operation, and the two-qubit-gate depth. Mapping\n",
        "can add both, so a circuit is sized as it runs, not as you wrote it.\n",
        "\n",
        "| Size | Smallest size for active qubits and two-qubit-gate depth | Compute profile                     | vCPU | RAM     | GPUs     |\n",
        "| ---- | -------------------------------------------------------- | ----------------------------------- | ---- | ------- | -------- |\n",
        "| `S`  | both at most 40                                          | General Medium (`16x128`)           | 16   | 128 GB  | —        |\n",
        "| `M`  | both at most 100                                         | General Medium (`16x128`)           | 16   | 128 GB  | —        |\n",
        "| `L`  | either above 100                                         | Accelerated Large (`80x1200x8a100`) | 80   | 1200 GB | 8 × A100 |\n",
        "\n",
        "A circuit must fit both bounds of a size, so 30 qubits at a two-qubit-gate depth of\n",
        "120 is `L`, not `S`. These are the same bounds for every circuit function, so a size\n",
        "means the same difficulty of circuit whichever one you call.\n",
        "\n",
        "The default is `M`, used when a job does not request a size.\n",
        "\n",
        "You can also get the mapping from the function with `tem.sizes_map`, and the size\n",
        "that is used when a job does not request one with `tem.default_size`.\n",
        "\n",
        "### Choose a size for TEM\n",
        "\n",
        "The circuit sets the smallest size that a job can run at. The memory that TEM's classical\n",
        "post-processing needs depends mostly on the bond dimension of the tensor network\n",
        "(`tem_max_bond_dimension`), not on the circuit size, so a small circuit can still need\n",
        "more memory than its size provides. `S` and `M` run on the same compute profile; request\n",
        "`L` when the post-processing needs more memory than General Medium has, for example at a\n",
        "large bond dimension. The `dry_run` option estimates the peak memory and returns the size\n",
        "it needs as `classical_compute_size_tag`; see\n",
        "[Tune the TEM function for accuracy and cost](/docs/functions/algorithmiq-tem/performance-tuning#estimate-the-resources-before-running).\n",
        "A job that requests a larger size than its circuit needs records a `4601` advisory event.\n",
        "When you request `L` for the memory of the post-processing, this event is expected, and\n",
        "the job runs normally.\n",
        "\n",
        "A rerun (the `job_id` option) and a dry run submit no new QPU jobs, so their size is not\n",
        "checked against the circuit: they run at the size that you request, or at the default. Choose\n",
        "the size of a rerun from the memory its post-processing needs.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bfebdf51",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Run the following code on your own circuits. It only reads the circuits. It submits no\n",
        "job and reserves nothing, so you can call it as often as needed while you reduce a\n",
        "circuit to a smaller size.\n",
        "\n",
        "It needs the backend as well as the circuits, because the size depends on the\n",
        "coupling map they are mapped onto. It requires only Qiskit.\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Size the circuit that you submit after you transpile it\">\n",
        "  TEM transpiles a non-ISA circuit with optimal settings before running it, but the size\n",
        "  calculator maps it with a fixed, simpler layout and routing, which can add many qubits\n",
        "  and much depth: a circuit can size as `L` before transpilation and as `S` after. The\n",
        "  function checks the size on the circuits that you pass, so transpile them for the backend\n",
        "  first, and pass the same ISA circuits to the calculator and to `tem.run`.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "93a925f5",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Calculate the function size a circuit needs, before submitting it.\n",
        "#\n",
        "# Call ``calculate_function_size(pubs, backend)``: it returns \"S\", \"M\" or \"L\" and submits\n",
        "# nothing. Pass the whole list of PUBs -- a job runs at one size, and the heaviest PUB\n",
        "# decides it. The circuit is measured after being mapped onto ``backend``, since mapping\n",
        "# can add both qubits and depth.\n",
        "\n",
        "from collections.abc import Iterable\n",
        "from typing import Any, Literal\n",
        "\n",
        "from qiskit import QuantumCircuit\n",
        "from qiskit.circuit import Barrier\n",
        "from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary\n",
        "from qiskit.transpiler import PassManager\n",
        "from qiskit.transpiler.passes import (\n",
        "    ApplyLayout,\n",
        "    BarrierBeforeFinalMeasurements,\n",
        "    BasisTranslator,\n",
        "    EnlargeWithAncilla,\n",
        "    FilterOpNodes,\n",
        "    FullAncillaAllocation,\n",
        "    HighLevelSynthesis,\n",
        "    SabreSwap,\n",
        "    TrivialLayout,\n",
        "    UnitarySynthesis,\n",
        ")\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "_ORDER = {\"S\": 0, \"M\": 1, \"L\": 2}\n",
        "\n",
        "# Limits are provided by IBM\n",
        "_SMALL_QUBITS, _SMALL_DEPTH_2Q = 40, 40\n",
        "_MEDIUM_QUBITS, _MEDIUM_DEPTH_2Q = 100, 100\n",
        "\n",
        "# Any fixed value works; what matters is that it does not change between calls.\n",
        "_SEED_TRANSPILER = 42\n",
        "\n",
        "# Added by BarrierBeforeFinalMeasurements so routing cannot move gates past a measurement,\n",
        "# then removed again once routing is done.\n",
        "_PROTECTION_BARRIER = \"qiskit.transpiler.internal.routing.protection.barrier\"\n",
        "\n",
        "\n",
        "def calculate_function_size(\n",
        "    circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any\n",
        ") -> Size:\n",
        "    \"\"\"Return the size (\"S\", \"M\" or \"L\") required to run the function.\"\"\"\n",
        "    circuits = pub_circuits(circuit)\n",
        "    if not circuits:\n",
        "        raise ValueError(\n",
        "            \"No circuit to size: pass a QuantumCircuit or a non-empty list of PUBs.\"\n",
        "        )\n",
        "    return max(\n",
        "        (_calculate_circuit_size(qc, backend, **kwargs) for qc in circuits),\n",
        "        key=_ORDER.__getitem__,\n",
        "    )\n",
        "\n",
        "\n",
        "def _calculate_circuit_size(\n",
        "    circuit: QuantumCircuit, backend, **kwargs: Any\n",
        ") -> Size:\n",
        "    \"\"\"Return the size required to run a single circuit.\"\"\"\n",
        "    metrics = _measure(circuit, backend, **kwargs)\n",
        "    if _is_small(metrics):\n",
        "        return \"S\"\n",
        "    if _is_medium(metrics):\n",
        "        return \"M\"\n",
        "    return \"L\"\n",
        "\n",
        "\n",
        "def pub_circuits(problem: Any) -> list[QuantumCircuit]:\n",
        "    \"\"\"Return the circuits in ``problem``: one circuit, or one per PUB in a list.\"\"\"\n",
        "    if isinstance(problem, QuantumCircuit):\n",
        "        return [problem]\n",
        "    circuits: list[QuantumCircuit] = []\n",
        "    for index, pub in enumerate(problem):\n",
        "        if isinstance(pub, QuantumCircuit):\n",
        "            circuit = pub\n",
        "        elif isinstance(getattr(pub, \"circuit\", None), QuantumCircuit):\n",
        "            circuit = pub.circuit\n",
        "        elif (\n",
        "            isinstance(pub, (tuple, list))\n",
        "            and pub\n",
        "            and isinstance(pub[0], QuantumCircuit)\n",
        "        ):\n",
        "            circuit = pub[0]\n",
        "        else:\n",
        "            raise ValueError(f\"PUB #{index} has no QuantumCircuit to size.\")\n",
        "        circuits.append(circuit)\n",
        "    return circuits\n",
        "\n",
        "\n",
        "def _pass_manager(target) -> PassManager:\n",
        "    \"\"\"Return the pass manager used to map a circuit onto ``target``.\n",
        "\n",
        "    Fixed and seeded, so the same circuit always gives the same size.\n",
        "    \"\"\"\n",
        "    basis = list(target.operation_names)\n",
        "    library = SessionEquivalenceLibrary\n",
        "    return PassManager(\n",
        "        [\n",
        "            UnitarySynthesis(\n",
        "                basis, approximation_degree=1.0, min_qubits=3, target=target\n",
        "            ),\n",
        "            HighLevelSynthesis(\n",
        "                target=target,\n",
        "                equivalence_library=library,\n",
        "                basis_gates=basis,\n",
        "                min_qubits=3,\n",
        "            ),\n",
        "            BasisTranslator(library, basis, target=target, min_qubits=3),\n",
        "            TrivialLayout(target),\n",
        "            FullAncillaAllocation(target),\n",
        "            EnlargeWithAncilla(),\n",
        "            ApplyLayout(),\n",
        "            BarrierBeforeFinalMeasurements(label=_PROTECTION_BARRIER),\n",
        "            SabreSwap(\n",
        "                target, heuristic=\"basic\", seed=_SEED_TRANSPILER, trials=5\n",
        "            ),\n",
        "            FilterOpNodes(lambda node: node.label != _PROTECTION_BARRIER),\n",
        "            UnitarySynthesis(basis, approximation_degree=1.0, target=target),\n",
        "            HighLevelSynthesis(\n",
        "                target=target,\n",
        "                equivalence_library=library,\n",
        "                basis_gates=basis,\n",
        "                use_qubit_indices=True,\n",
        "            ),\n",
        "            BasisTranslator(library, basis, target=target),\n",
        "        ]\n",
        "    )\n",
        "\n",
        "\n",
        "def _count(isa: QuantumCircuit) -> dict:\n",
        "    \"\"\"Return the active qubits and two-qubit-gate depth of a mapped circuit.\"\"\"\n",
        "    active = {\n",
        "        q\n",
        "        for instr in isa.data\n",
        "        if not isinstance(instr.operation, Barrier)\n",
        "        for q in instr.qubits\n",
        "    }\n",
        "    return {\n",
        "        \"num_qubits\": len(active),\n",
        "        \"depth_2q\": isa.depth(\n",
        "            filter_function=lambda instr: len(instr.qubits) == 2\n",
        "            and not isinstance(instr.operation, Barrier)\n",
        "        ),\n",
        "    }\n",
        "\n",
        "\n",
        "def _measure(circuit: QuantumCircuit, backend, **kwargs: Any) -> dict:\n",
        "    \"\"\"Map ``circuit`` onto ``backend`` and return its metrics.\"\"\"\n",
        "    return _count(_pass_manager(backend.target).run(circuit))\n",
        "\n",
        "\n",
        "def _is_small(metrics: dict) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'S'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_qubits\"] <= _SMALL_QUBITS\n",
        "        and metrics[\"depth_2q\"] <= _SMALL_DEPTH_2Q\n",
        "    )\n",
        "\n",
        "\n",
        "def _is_medium(metrics: dict) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'M'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_qubits\"] <= _MEDIUM_QUBITS\n",
        "        and metrics[\"depth_2q\"] <= _MEDIUM_DEPTH_2Q\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6b3839d4",
      "metadata": {},
      "source": [
        "Pass the whole list of PUBs, not one at a time. A job runs at a single size, so\n",
        "the heaviest PUB decides it: one deep circuit among many shallow ones makes the\n",
        "whole job `L`. Splitting the batch into separate jobs lets the lighter circuits run\n",
        "at a smaller size.\n",
        "\n",
        "If the size is too small, the job fails with error `4600` and the message names the\n",
        "size to use instead. If it is larger than needed the job runs normally and records a\n",
        "`4601` advisory event. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) to learn more.\n",
        "\n",
        "The following [example](#example) calculates the size of its circuit and passes it to\n",
        "`tem.run` as `function_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a1c3e5f7-0b2d-4f6a-8c1e-3a5b7d9f1c01",
      "metadata": {},
      "source": [
        "## Example\n",
        "\n",
        "The following example uses TEM to compute the expectation value of an observable for a simple quantum circuit.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b2d4f6a8-1c3e-4a7b-9d2f-4b6c8e0a2d02",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit.quantum_info import SparsePauliOp\n",
        "\n",
        "# Prepare a 4-qubit GHZ state, (|0000> + |1111>) / sqrt(2)\n",
        "num_qubits = 4\n",
        "ghz = QuantumCircuit(num_qubits)\n",
        "ghz.h(0)\n",
        "for qubit in range(num_qubits - 1):\n",
        "    ghz.cx(qubit, qubit + 1)\n",
        "\n",
        "# Z on qubits 0 and 3: a stabilizer of the GHZ state, with exact value 1\n",
        "observable = SparsePauliOp(\"ZIIZ\", 1.0)\n",
        "\n",
        "# Define the execution options\n",
        "ghz_pub = (ghz, [observable])\n",
        "options = {\"default_precision\": 0.01}\n",
        "# Define backend to use\n",
        "backend_name = \"ibm_kingston\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "71e60874",
      "metadata": {},
      "source": [
        "Calculate the size the job needs on the target backend, and pass it to `tem.run`:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b7088643",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "S\n"
          ]
        }
      ],
      "source": [
        "backend = catalog.backend(backend_name)\n",
        "size = calculate_function_size([ghz_pub], backend)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b5371269",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Run the TEM function\n",
        "ghz_job = tem.run(\n",
        "    pubs=[ghz_pub],\n",
        "    backend_name=backend_name,\n",
        "    options=options,\n",
        "    function_size=size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c3e5a7b9-2d4f-4b8c-ae3a-5c7d9f1b3e03",
      "metadata": {},
      "source": [
        "Use the Qiskit Serverless APIs to check your quantum function workload's status:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "d4f6b8ca-3e5a-4c9d-bf4b-6d8e0a2c4f04",
      "metadata": {},
      "outputs": [],
      "source": [
        "print(ghz_job.status())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f6b8daec-5a7c-4ebf-9b6d-8f0a2c4e6b06",
      "metadata": {},
      "source": [
        "Return the results as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a7c9ebfd-6b8d-4fca-ac7e-9a1b3d5f7c07",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ZIIZ: TEM +0.952 ± 0.032, unmitigated +0.869, statevector 1.0\n"
          ]
        }
      ],
      "source": [
        "idx = 0  # observable index, 0 in this case\n",
        "\n",
        "ghz_result = ghz_job.result()[0]\n",
        "ghz_ev = ghz_result.data.evs[idx]\n",
        "ghz_std = ghz_result.data.stds[idx]\n",
        "# Unmitigated value, from the same measurement outcomes\n",
        "raw_ev = ghz_result.metadata[\"evs_wo_tem_wo_qdt\"][idx]\n",
        "print(\n",
        "    f\"ZIIZ: TEM {ghz_ev:+.3f} ± {ghz_std:.3f}, unmitigated {raw_ev:+.3f}, statevector {1.0}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5e7a1b2c",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Learn how each option trades accuracy against QPU and classical time in [Tune the TEM function for accuracy and cost](/docs/functions/algorithmiq-tem/performance-tuning).\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Visit the [API reference](/docs/functions/algorithmiq-tem/api-reference) for every option of this quantum function.\n",
        "  * Try the [Simulate a kicked Ising model with the TEM function](/docs/tutorials/simulate-kicked-ising-tem) tutorial.\n",
        "  * Try the [Find the Maximum Independent Set with the Aqarios Constrained Quantum Optimizer](/docs/tutorials/find-the-maximum-independent-set-with-aqarios-constrained-quantum-optimizer) tutorial for a deep-dive into a real QOBLIB benchmark instance.\n",
        "  * Review the publication [Constrained Quantum Optimization via Iterative Warm-Start XY-Mixers](https://doi.org/10.1088/1367-2630/ae8ea2).\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": 5
}