{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "ac506e80-3188-4cdb-9e67-e9016dac3ebf",
      "metadata": {},
      "source": [
        "---\n",
        "title: Tune the TEM function for accuracy and cost\n",
        "description: Tune the options of TEM, a quantum function by Algorithmiq, to trade accuracy against QPU and classical time, reuse a noise model, and rerun post-processing.\n",
        "---\n",
        "\n",
        "# Tune the TEM function for accuracy and cost\n",
        "\n",
        "*See the [overview](/docs/functions/algorithmiq-tem) and the [API reference](/docs/functions/algorithmiq-tem/api-reference)*\n",
        "\n",
        "{/* cspell:ignore linestyles, informationally, ecolor */}\n",
        "\n",
        "Algorithmiq's Tensor-network Error Mitigation (TEM) removes the effect of hardware noise in classical post-processing. Its default options give good results for typical circuits, but every run makes trade-offs: more shots lower the statistical error but cost QPU time, a better-learned noise model lowers the bias of the mitigated value, and a larger tensor network represents the noise inverse more accurately at the price of classical time.\n",
        "\n",
        "This example takes a 24-qubit kicked Ising circuit, whose exact result is known, and runs it four times:\n",
        "\n",
        "1. With the default options, to see where TEM spends QPU and classical time.\n",
        "2. With more shots, and with the noise model that the first run learned, so that the noise learning is not repeated.\n",
        "3. As a **rerun** of the second run with a larger bond dimension, which repeats only the post-processing and uses no QPU time.\n",
        "4. As a **rerun** of the second run with a larger bond dimension and a different observable.\n",
        "\n",
        "The physics of the circuit is explained in [Simulate a kicked Ising model with the TEM function](/docs/tutorials/simulate-kicked-ising-tem).\n",
        "\n",
        "*Usage estimate: approximately 26 QPU seconds (measured on a Nighthawk r2 device; the runtime depends on the chosen device).*\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5f86ab75-daa5-4d9b-abde-f0ad01f0606b",
      "metadata": {},
      "source": [
        "## Setup\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9cf6d15e-324b-474a-886c-c3dca5a24141",
      "metadata": {},
      "source": [
        "As a prerequisite, ensure that the necessary dependencies are installed.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1eeec332-29ca-4882-8129-d1c93ed82b2b",
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install numpy matplotlib qiskit qiskit-ibm-catalog qiskit-ibm-runtime pylatexenc qiskit_qasm3_import"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "ad0002b7-dbff-4699-af52-ba0df72ed200",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:39.258723Z",
          "iopub.status.busy": "2026-10-21T12:41:39.258578Z",
          "iopub.status.idle": "2026-10-21T12:41:40.735063Z",
          "shell.execute_reply": "2026-10-21T12:41:40.734027Z"
        }
      },
      "outputs": [],
      "source": [
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit.transpiler import generate_preset_pass_manager\n",
        "\n",
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "75f92fb3-616b-44d3-8e00-ce0dd3dcd392",
      "metadata": {},
      "source": [
        "The circuit is a kicked Ising chain of 24 qubits evolved for 12 periods at the self-dual point with $h = 0$. The observable $\\langle \\hat{X}_{n=12} \\rangle$ has the exact value $[\\cos(2h)]^{12} = 1$, which is used to judge the accuracy of each setting.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "d55afeb3-1517-4da7-a205-547139f0de5e",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:40.738970Z",
          "iopub.status.busy": "2026-10-21T12:41:40.738751Z",
          "iopub.status.idle": "2026-10-21T12:41:40.742923Z",
          "shell.execute_reply": "2026-10-21T12:41:40.742035Z"
        }
      },
      "outputs": [],
      "source": [
        "from qiskit import QuantumCircuit\n",
        "\n",
        "\n",
        "def xt_observable(n_qubits, t_steps):\n",
        "    pauli_str = \"\".join([\"I\" * t_steps, \"X\", \"I\" * (n_qubits - t_steps - 1)])\n",
        "    pauli_str = pauli_str[::-1]  # Reverse the string to match qiskit order\n",
        "    return SparsePauliOp(data=pauli_str, coeffs=1.0)\n",
        "\n",
        "\n",
        "def kicked_ising_circuit(n_qubits, t_steps):\n",
        "    \"\"\"Kicked Ising circuit at the self-dual point (J = b = pi/4, h = 0).\"\"\"\n",
        "    circuit = QuantumCircuit(n_qubits)\n",
        "\n",
        "    # State preparation: |+> on qubit 0, Bell pairs on (1, 2), (3, 4), ...\n",
        "    circuit.h(0)\n",
        "    for i in range(1, n_qubits - 1, 2):\n",
        "        circuit.h(i)\n",
        "        circuit.x(i + 1)\n",
        "        circuit.cx(i, i + 1)\n",
        "    circuit.barrier()\n",
        "\n",
        "    # Clifford two-qubit block: one ZZ rotation, X kick, one ZZ rotation\n",
        "    block = QuantumCircuit(2)\n",
        "    block.sdg([0, 1])\n",
        "    block.cx(0, 1)\n",
        "    block.sdg(0)\n",
        "    block.h([0, 1])\n",
        "    block.s(1)\n",
        "    block.cx(0, 1)\n",
        "    block.s(0)\n",
        "    block.h(0)\n",
        "    block.sdg(0)\n",
        "    block.y(1)\n",
        "    block.h(1)\n",
        "\n",
        "    # Brickwork: even periods act on (0, 1), (2, 3), ...; odd periods on (1, 2), (3, 4), ...\n",
        "    for step in range(t_steps):\n",
        "        for q in range(step % 2, n_qubits - 1, 2):\n",
        "            circuit.compose(block, [q, q + 1], inplace=True)\n",
        "        circuit.barrier()\n",
        "    return circuit"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "04ca8389-9105-441f-8a71-2b26421c4e9e",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:40.748104Z",
          "iopub.status.busy": "2026-10-21T12:41:40.747977Z",
          "iopub.status.idle": "2026-10-21T12:41:40.753268Z",
          "shell.execute_reply": "2026-10-21T12:41:40.752394Z"
        }
      },
      "outputs": [],
      "source": [
        "# Parameters of the kicked Ising model\n",
        "h = 0.0\n",
        "num_qubits = 24\n",
        "t_steps = 12\n",
        "\n",
        "small_circuit = kicked_ising_circuit(num_qubits, t_steps)\n",
        "\n",
        "\n",
        "small_observable = xt_observable(n_qubits=num_qubits, t_steps=t_steps)\n",
        "exact_evs = np.cos(2 * h) ** t_steps"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9a4bcd8d-ae21-40ab-b0e2-510236ba92de",
      "metadata": {},
      "source": [
        "Next, get access to the TEM function and select a backend from the available devices. This code 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": 4,
      "id": "6c9f80a8-4a65-4daa-94bb-a98edd6a1989",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:40.757212Z",
          "iopub.status.busy": "2026-10-21T12:41:40.757090Z",
          "iopub.status.idle": "2026-10-21T12:41:40.760110Z",
          "shell.execute_reply": "2026-10-21T12:41:40.758891Z"
        }
      },
      "outputs": [],
      "source": [
        "# Select the QPU backend\n",
        "backend_name = \"ibm_phoenix\"  # Replace with your desired backend's name"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "10df1803-5245-42b2-8eea-c0773cd655b6",
      "metadata": {},
      "source": [
        "Load the TEM function from the [IBM Quantum® Functions Catalog](/functions):\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "2473b284-108f-45fe-a8d8-3aed584137f6",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:40.763873Z",
          "iopub.status.busy": "2026-10-21T12:41:40.763742Z",
          "iopub.status.idle": "2026-10-21T12:41:46.592764Z",
          "shell.execute_reply": "2026-10-21T12:41:46.591480Z"
        }
      },
      "outputs": [],
      "source": [
        "# Load the TEM function from the Quantum Functions Catalog\n",
        "catalog = FunctionsCatalog()\n",
        "tem = catalog.load(\"algorithmiq/tem\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3b1f7c2e-8a4d-4e6b-9c1a-5d2e7f8a9b01",
      "metadata": {},
      "source": [
        "## Transpile the circuit one time\n",
        "\n",
        "The second run reuses the noise model learned by the first one. A learned noise model belongs to the physical qubits it was learned on, so both runs must place the circuit on the same qubits. TEM transpiles a circuit that is not in the instruction set architecture (ISA) of the device itself, and two transpilations can choose different qubits. Therefore, transpile the circuit one time and pass the same ISA circuit and observable to every run. TEM detects an ISA circuit and does not transpile it again.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "7c2e9d4a-1b3f-4a5c-8e6d-2f9a0b1c3d02",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:46.597940Z",
          "iopub.status.busy": "2026-10-21T12:41:46.597723Z",
          "iopub.status.idle": "2026-10-21T12:41:50.490951Z",
          "shell.execute_reply": "2026-10-21T12:41:50.489337Z"
        }
      },
      "outputs": [],
      "source": [
        "service = QiskitRuntimeService()\n",
        "backend = service.backend(backend_name)\n",
        "\n",
        "pass_manager = generate_preset_pass_manager(\n",
        "    optimization_level=3, backend=backend, seed_transpiler=42\n",
        ")\n",
        "small_circuit.measure_all()\n",
        "isa_circuit = pass_manager.run(small_circuit)\n",
        "small_circuit.remove_final_measurements(inplace=True)\n",
        "isa_circuit.remove_final_measurements(inplace=True)\n",
        "isa_observable = small_observable.apply_layout(isa_circuit.layout)\n",
        "\n",
        "\n",
        "pubs = [(isa_circuit, [isa_observable])]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e3017423",
      "metadata": {},
      "source": [
        "## Calculate the function size\n",
        "\n",
        "Every TEM job runs at a size, `S`, `M` or `L`, which selects the compute profile it runs on; see [Function sizes](/docs/functions/algorithmiq-tem/get-started#function-sizes).\n",
        "\n",
        "The following calculator sizes the **circuit** only. It maps the circuits onto the backend and returns the size they need, without submitting anything. This size is the smallest `function_size` that the job accepts: a smaller one fails the job with error `4600`. Size the ISA circuit that you submit, not the logical one, because the calculator maps a logical circuit less efficiently than TEM does and can overestimate its size.\n",
        "\n",
        "The circuit size does not account for the classical post-processing, whose memory depends mostly on the bond dimension. The dry run, described in the [next section](#estimate-the-resources-before-running), estimates it and more accurately recommends the size the classical compute needs. Request the larger of the two sizes.\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.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": "code",
      "execution_count": null,
      "id": "ad7662d6",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "S\n"
          ]
        }
      ],
      "source": [
        "size = calculate_function_size(pubs, backend)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "99c4eba4-e075-4037-ba57-d841a6d46fa5",
      "metadata": {},
      "source": [
        "## Estimate the resources before running\n",
        "\n",
        "Before submitting a run, you can ask TEM what resources it needs. With the `dry_run` option, TEM validates and transpiles the PUBs as in a normal run, then estimates the QPU time of the noise learning, readout calibration, and sampling, the classical time of the post-processing, and its peak memory, without submitting any QPU job. The estimate takes up to about a minute per PUB, and is returned in the metadata of the result.\n",
        "\n",
        "* `circuit_size_tag`: the size the circuit needs, as computed by the preceding size calculator.\n",
        "* `classical_compute_size_tag`: the size needed by the estimated peak memory. If it is larger than `circuit_size_tag`, request it in the run with `tem.run(..., function_size=...)`.\n",
        "* `estimated_resource_usage_pub`, in the metadata of each PUB: the estimated times of each stage, in seconds, and the peak memory.\n",
        "\n",
        "The classical estimate covers the post-processing only. To compare the estimate with the measured usage of a run, pass `resource_estimate_with_run` instead of `dry_run`: the run executes as usual and its result carries the same estimate.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "20d6fbc7-9a5a-4bb2-9f78-5af1b07c9e4d",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:41:50.496811Z",
          "iopub.status.busy": "2026-10-21T12:41:50.496652Z",
          "iopub.status.idle": "2026-10-21T12:44:56.580239Z",
          "shell.execute_reply": "2026-10-21T12:44:56.578518Z"
        }
      },
      "outputs": [],
      "source": [
        "estimate_job = tem.run(\n",
        "    pubs=pubs, backend_name=backend_name, options={\"dry_run\": True}\n",
        ")\n",
        "estimate = estimate_job.result()\n",
        "\n",
        "for key in (\n",
        "    \"estimated_resource_usage_job\",\n",
        "    \"circuit_size_tag\",\n",
        "    \"classical_compute_size_tag\",\n",
        "):\n",
        "    print(f\"{key}: {estimate.metadata[key]}\")\n",
        "for key, value in (\n",
        "    estimate[0].metadata[\"estimated_resource_usage_pub\"].items()\n",
        "):\n",
        "    print(f\"  {key}: {value}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "213c2aad-0ddf-420b-93b9-79d2489edca4",
      "metadata": {},
      "source": [
        "## Run 1: default options\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3c732819-4dca-421c-bc2b-45ff5a5912db",
      "metadata": {},
      "source": [
        "Run an experiment on the kicked Ising circuit with error mitigation provided by TEM. With the default settings, the expected QPU runtime is around 17 seconds on Nighthawk r2, and up to 2.5 minutes on earlier QPUs, depending on the QPU:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "b826e025-f36b-4fb5-90bd-e1ef36f5c1b2",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:44:56.585118Z",
          "iopub.status.busy": "2026-10-21T12:44:56.584981Z",
          "iopub.status.idle": "2026-10-21T12:45:01.537854Z",
          "shell.execute_reply": "2026-10-21T12:45:01.536175Z"
        }
      },
      "outputs": [],
      "source": [
        "tem_job = tem.run(pubs=pubs, backend_name=backend_name, function_size=size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "25b6f313-a928-493e-837f-45e6e7836aef",
      "metadata": {},
      "source": [
        "You can check the status of your job on the [IBM Quantum Platform dashboard](/) or with:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "05e202ff-5b86-4a93-a693-86fbb1cf3e02",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:01.542593Z",
          "iopub.status.busy": "2026-10-21T12:45:01.542422Z",
          "iopub.status.idle": "2026-10-21T12:45:05.859168Z",
          "shell.execute_reply": "2026-10-21T12:45:05.857625Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "7390dda0-55e8-4ab2-b24b-c87ddc519e6a\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DONE\n"
          ]
        }
      ],
      "source": [
        "print(tem_job.job_id)\n",
        "print(tem_job.status())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8e427c75-72fb-4a97-b723-97d695a692d3",
      "metadata": {},
      "source": [
        "When the status is `DONE`, check the raw and mitigated results. The `tem_evs` defined in the following code are the expectation values of the requested observables, in this case only one observable, $\\langle \\hat X_{n=t}\\rangle$, and `tem_std` are the corresponding standard deviations.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "3ca34069-1363-4e37-9718-91639d817a82",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:05.865615Z",
          "iopub.status.busy": "2026-10-21T12:45:05.865476Z",
          "iopub.status.idle": "2026-10-21T12:45:15.586022Z",
          "shell.execute_reply": "2026-10-21T12:45:15.584982Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "TEM Result: 0.942 ± 0.008, unmitigated value 0.90048 ± 0.006566971554072699\n"
          ]
        }
      ],
      "source": [
        "# Get the results of the TEM job\n",
        "tem_results = tem_job.result()[\n",
        "    0\n",
        "]  # Get the first and only result from the job\n",
        "tem_evs = tem_results.data.evs[0]\n",
        "tem_std = tem_results.data.stds[0]\n",
        "\n",
        "unmitigated = tem_results.metadata[\"evs_wo_tem_wo_qdt\"][0]\n",
        "un_std = tem_results.metadata[\"stds_wo_tem_wo_qdt\"][0]\n",
        "\n",
        "print(\n",
        "    f\"TEM Result: {tem_evs:.3f} ± {tem_std:.3f}, unmitigated value {unmitigated} ± {un_std}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "09639dfe-7dc0-476e-870a-a900f8a3d00b",
      "metadata": {},
      "source": [
        "## Where TEM spends its time\n",
        "\n",
        "A TEM run has four stages. The first three run on the QPU, and the last one runs on IBM Cloud®:\n",
        "\n",
        "1. **Noise learning**: learns a sparse Pauli-Lindblad noise model for each distinct layer of two-qubit gates.\n",
        "2. **Readout calibration**: characterizes the measurement error, to mitigate it.\n",
        "3. **Sampling**: runs the circuit with an informationally complete (IC) measurement.\n",
        "4. **Post-processing**: builds the tensor network that inverts the learned noise and applies it to the measurement outcomes.\n",
        "\n",
        "The result metadata reports the time spent in each:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "c700ffcf-8337-43ef-967d-f424d3bca967",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:15.591286Z",
          "iopub.status.busy": "2026-10-21T12:45:15.591121Z",
          "iopub.status.idle": "2026-10-21T12:45:27.900298Z",
          "shell.execute_reply": "2026-10-21T12:45:27.899405Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "RUNNING: OPTIMIZING_FOR_HARDWARE: {'CPU_TIME': 2.7649269999999997}\n",
            "RUNNING: WAITING_FOR_QPU: {'CPU_TIME': 16.077092999999998}\n",
            "RUNNING: POST_PROCESSING: {'CPU_TIME': 486.055132}\n",
            "RUNNING: EXECUTING_QPU: {'QPU_TIME': 17.0}\n"
          ]
        }
      ],
      "source": [
        "resource_usage = tem_job.result().metadata[\"resource_usage\"]\n",
        "for stage, usage in resource_usage.items():\n",
        "    print(f\"{stage}: {usage}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d0f6813f-07fd-4ac8-954b-aff197e4fdb6",
      "metadata": {},
      "source": [
        "## The options, stage by stage\n",
        "\n",
        "Each of the following options acts on one stage. The options of the QPU stages need a new run, which can reuse the noise model learned by an earlier run. The post-processing options can be changed afterwards with a rerun.\n",
        "\n",
        "**Sampling: statistical error.**\n",
        "\n",
        "* `default_precision`: the target standard error of the mitigated values (default 0.05). TEM estimates the number of shots needed from the circuit size and the error rates of the device. A precision can also be given per PUB.\n",
        "* `default_shots`: the number of shots per PUB, which overrides any precision. The standard error scales as $1/\\sqrt{\\text{shots}}$.\n",
        "* `compute_shadows_bias_from_observable`: tailors the probabilities of measuring in the $Z$, $X$, and $Y$ bases to the observables. For an observable dominated by one Pauli, such as the $\\hat{X}$ operator in this example, this lowers the shots needed for a given precision. `shadows_bias` sets the probabilities by hand.\n",
        "\n",
        "**Noise learning: bias.** A noise model that is less accurate leaves a bias in the mitigated values that more shots cannot remove.\n",
        "\n",
        "* `max_layers_to_learn`: the number of distinct layers to learn. Set it to the number of distinct layers of two-qubit gates in your circuit; this kicked Ising circuit has two.\n",
        "* `num_randomizations`, `shots_per_randomization`: the number of twirled learning circuits and the shots for each of them. More of either gives a more accurate noise model at a higher QPU cost.\n",
        "* `layer_pair_depths`: the circuit depths used to fit the noise. Deeper pairs resolve smaller error rates.\n",
        "* `noise_learner_job_id`: the job ID of an earlier TEM run whose learned noise model to reuse. The noise learning is skipped and the preceding options have no effect. The circuit must run on the same backend and physical qubits as in the earlier run. Device noise drifts over time, so a noise model learned long before the current run mitigates poorly: reuse it only shortly after it was learned.\n",
        "\n",
        "These follow the definitions of the `qiskit-ibm-runtime` [`NoiseLearnerOptions`](/docs/api/qiskit-ibm-runtime/options-noise-learner-options).\n",
        "\n",
        "### Advanced TEM settings\n",
        "\n",
        "**Readout calibration.**\n",
        "\n",
        "* `mitigate_readout_error`: whether to mitigate readout errors (default `True`). The metadata always reports the values without readout mitigation too, so you can compare them from a single run.\n",
        "* `num_readout_calibration_shots`: the shots of the calibration (default 10,000).\n",
        "\n",
        "**Post-processing: classical time and truncation error.**\n",
        "\n",
        "* `tem_max_bond_dimension`: the largest bond dimension of the tensor network that inverts the noise (default 128). Larger values represent the inverse more accurately for deep or wide circuits, at a higher classical time and memory.\n",
        "* `tem_compression_cutoff`: the singular values discarded when compressing the network. Smaller values keep more of the network.\n",
        "\n",
        "Refer to the [TEM API reference](/docs/functions/algorithmiq-tem/api-reference) for the full list of options.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "91c80d32",
      "metadata": {},
      "source": [
        "## Reuse previous data\n",
        "\n",
        "When you reuse previous QPU data, a new job uses the results of past experiments.\n",
        "When you make this request, TEM ignores any other QPU settings that you give for the same job, without a warning.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "019bd943-26af-4cab-94d2-5409c8423718",
      "metadata": {},
      "source": [
        "## Run 2: reuse the noise model, increase the shots\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "314d40fb-0a31-4018-ab19-38006bff6888",
      "metadata": {},
      "source": [
        "The statistical error of run 1 is set by the default precision of 0.05. To lower it, run 2 raises the shots to 100,000; the standard error scales as $1/\\sqrt{\\text{shots}}$.\n",
        "\n",
        "The noise does not need to be learned again: the circuit, the backend, and the physical qubits are the same as in run 1. Passing the job ID of run 1 as `noise_learner_job_id` loads its learned noise model and skips the noise learning, which saves its QPU time. The readout calibration and the sampling run as usual.\n",
        "\n",
        "<Admonition type=\"caution\">\n",
        "  The noise of a device drifts over time, and calibrations change it. A noise model learned long before the current run no longer describes the device and mitigates poorly, so submit run 2 shortly after run 1. TEM logs a warning whenever `noise_learner_job_id` is set.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d87b21e4",
      "metadata": {},
      "source": [
        "In run 1, the default precision of `0.05` was used, which can amount to more than the maximum allowed default of 50,000 shots.\n",
        "\n",
        "This can be verified by checking the log for the following warning:\n",
        "\n",
        "> Computed number of shots from the precision is xxx, which exceeds the maximum allowed (50000)\n",
        "\n",
        "To improve the precision in this case, use the `default_shots` key, which is not bounded.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "a2e9a032-91cb-4a18-9a00-00a149e60459",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:40.380363Z",
          "iopub.status.busy": "2026-10-21T12:45:40.380223Z",
          "iopub.status.idle": "2026-10-21T12:45:40.383553Z",
          "shell.execute_reply": "2026-10-21T12:45:40.382138Z"
        }
      },
      "outputs": [],
      "source": [
        "options_shots = {\n",
        "    \"noise_learner_job_id\": tem_job.job_id,  # reuse the noise model of run 1\n",
        "    \"default_shots\": 100_000,\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "216ad12c-8c70-4073-8515-b07fd57f74d4",
      "metadata": {},
      "source": [
        "Submit run 2. Its QPU time is spent on the readout calibration and the sampling only:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "a150f57a",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:40.388880Z",
          "iopub.status.busy": "2026-10-21T12:45:40.388596Z",
          "iopub.status.idle": "2026-10-21T12:45:42.318784Z",
          "shell.execute_reply": "2026-10-21T12:45:42.317766Z"
        }
      },
      "outputs": [],
      "source": [
        "tem_job_shots = tem.run(\n",
        "    pubs=pubs,\n",
        "    backend_name=backend_name,\n",
        "    options=options_shots,\n",
        "    function_size=size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8b3152df-0021-49fa-8c4c-c73254a11959",
      "metadata": {},
      "source": [
        "Save the job ID. Use it to retrieve the results later with `catalog.get_job_by_id(job_id)`, and to rerun the job in run 3.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "0f99101b-9e72-45c8-8b00-9f3a257b8b3b",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:42.323188Z",
          "iopub.status.busy": "2026-10-21T12:45:42.322993Z",
          "iopub.status.idle": "2026-10-21T12:45:44.086671Z",
          "shell.execute_reply": "2026-10-21T12:45:44.083812Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Job ID: 2e39789f-efa4-4fa8-9c6b-e2a566168354\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "DONE\n"
          ]
        }
      ],
      "source": [
        "job_id = tem_job_shots.job_id\n",
        "print(f\"Job ID: {job_id}\")\n",
        "print(tem_job_shots.status())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "0c751dac-e856-4371-aaed-f67aca31061f",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:44.095590Z",
          "iopub.status.busy": "2026-10-21T12:45:44.095343Z",
          "iopub.status.idle": "2026-10-21T12:45:54.328047Z",
          "shell.execute_reply": "2026-10-21T12:45:54.326011Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "TEM Result: 0.963 ± 0.006\n"
          ]
        }
      ],
      "source": [
        "results_shots = tem_job_shots.result()\n",
        "shots_evs = results_shots[0].data.evs[0]\n",
        "shots_std = results_shots[0].data.stds[0]\n",
        "\n",
        "print(f\"TEM Result: {shots_evs:.3f} ± {shots_std:.3f}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "edfef6f9-6bac-42bb-8bd2-95f977f7b31b",
      "metadata": {},
      "source": [
        "Inspect the results and the metadata to get insight into the experiment:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "id": "dd189b2d-860b-4b9a-88c2-7e5c62b1f160",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:54.334667Z",
          "iopub.status.busy": "2026-10-21T12:45:54.334505Z",
          "iopub.status.idle": "2026-10-21T12:45:54.338462Z",
          "shell.execute_reply": "2026-10-21T12:45:54.337729Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Unmitigated Result: 0.917 ± 0.005\n",
            "Exact Result: 1.0\n"
          ]
        }
      ],
      "source": [
        "metadata_shots = results_shots[0].metadata\n",
        "\n",
        "unmitigated_evs = metadata_shots[\"evs_wo_tem_wo_qdt\"][0]\n",
        "unmitigated_stds = metadata_shots[\"stds_wo_tem_wo_qdt\"][0]\n",
        "print(f\"Unmitigated Result: {unmitigated_evs:.3f} ± {unmitigated_stds:.3f}\")\n",
        "print(\"Exact Result:\", exact_evs)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d643bdb4-22e0-4f55-b3a8-d5ef39f6e696",
      "metadata": {},
      "source": [
        "Compare the QPU and classical time of the two runs:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "09cf2226-c48c-483b-aa49-80186229ae95",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:45:54.343946Z",
          "iopub.status.busy": "2026-10-21T12:45:54.343791Z",
          "iopub.status.idle": "2026-10-21T12:46:30.579301Z",
          "shell.execute_reply": "2026-10-21T12:46:30.578436Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Run 1: QPU 17.0 s, classical 488.8 s\n",
            "Run 2: QPU 7.0 s, classical 491.5 s\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": []
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": []
        }
      ],
      "source": [
        "def run_times(result):\n",
        "    \"\"\"Return the QPU time and the classical time of a TEM job, in seconds.\"\"\"\n",
        "    usage = result.metadata[\"resource_usage\"]\n",
        "    qpu = usage[\"RUNNING: EXECUTING_QPU\"][\"QPU_TIME\"]\n",
        "    cpu = sum(\n",
        "        usage.get(step, {}).get(\"CPU_TIME\", 0.0)\n",
        "        for step in (\n",
        "            \"RUNNING: OPTIMIZING_FOR_HARDWARE\",\n",
        "            \"RUNNING: POST_PROCESSING\",\n",
        "        )\n",
        "    )\n",
        "    return qpu, cpu\n",
        "\n",
        "\n",
        "qpu_default, cpu_default = run_times(tem_job.result())\n",
        "qpu_shots, cpu_shots = run_times(results_shots)\n",
        "print(f\"Run 1: QPU {qpu_default} s, classical {cpu_default:.1f} s\")\n",
        "print(f\"Run 2: QPU {qpu_shots} s, classical {cpu_shots:.1f} s\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fc3a37bc-6dfb-4017-9fc0-16fdd7b75307",
      "metadata": {},
      "source": [
        "Run 2 skips the noise learning, so its QPU time is spent on the readout calibration and on the sampling, which grows with the shots.\n",
        "\n",
        "### Effect of readout mitigation\n",
        "\n",
        "The metadata reports the estimate with and without each mitigation, computed from the same outcomes. This separates the contribution of the readout mitigation from that of the noise-inverting network:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "38e7b510-00b2-435b-8bab-cc0478d7b212",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:46:30.588176Z",
          "iopub.status.busy": "2026-10-21T12:46:30.588015Z",
          "iopub.status.idle": "2026-10-21T12:46:30.591663Z",
          "shell.execute_reply": "2026-10-21T12:46:30.590916Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            " No mitigation: 0.917 ± 0.005\n",
            "  Readout only: 0.929 ± 0.005\n",
            "      TEM only: 0.951 ± 0.006\n",
            " TEM + readout: 0.963 ± 0.006\n",
            "         Exact: 1.000\n"
          ]
        }
      ],
      "source": [
        "labels = {\n",
        "    \"No mitigation\": \"evs_wo_tem_wo_qdt\",\n",
        "    \"Readout only\": \"evs_wo_tem_w_qdt\",\n",
        "    \"TEM only\": \"evs_w_tem_wo_qdt\",\n",
        "}\n",
        "for label, key in labels.items():\n",
        "    std_key = key.replace(\"evs\", \"stds\")\n",
        "    print(\n",
        "        f\"{label:>14}: {metadata_shots[key][0]:.3f} ± {metadata_shots[std_key][0]:.3f}\"\n",
        "    )\n",
        "print(f\"{'TEM + readout':>14}: {shots_evs:.3f} ± {shots_std:.3f}\")\n",
        "print(f\"{'Exact':>14}: {exact_evs:.3f}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f1817cba-30bb-44fe-9771-d8fbd14a7855",
      "metadata": {},
      "source": [
        "## Run 3: rerun with a larger bond dimension\n",
        "\n",
        "TEM saves the measurement outcomes and the learned noise model of every run. Passing the `job_id` of a finished run **reruns** only the post-processing: no jobs are submitted to the QPU, the circuits and options of the original run are reused, and any option passed with the rerun overrides the original one. The PUBs passed to a rerun are ignored.\n",
        "\n",
        "Only post-processing options have an effect on a rerun, such as `tem_max_bond_dimension`, `tem_compression_cutoff`, and `mitigate_readout_error`. Options of the QPU stages, such as shots or noise learning, do not.\n",
        "\n",
        "A rerun is not sized from its circuit, so choose its `function_size` from the memory of the post-processing; see [Choose a size for TEM](/docs/functions/algorithmiq-tem/get-started#choose-a-size-for-tem).\n",
        "\n",
        "With a rerun that uses the `job_id` option, you can check convergence in the bond dimension at no additional QPU cost. If the value changes when the bond dimension grows, the network of the earlier run was truncated too much. Rerun run 2 with the bond dimension raised from its default of 128 to 512:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "30b263d3-ab7f-4173-b058-1d195e204793",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:46:30.597141Z",
          "iopub.status.busy": "2026-10-21T12:46:30.597028Z",
          "iopub.status.idle": "2026-10-21T12:46:34.281819Z",
          "shell.execute_reply": "2026-10-21T12:46:34.278973Z"
        }
      },
      "outputs": [],
      "source": [
        "tem_job_rerun = tem.run(\n",
        "    pubs=pubs,  # ignored on a rerun\n",
        "    options={\"tem_max_bond_dimension\": 512, \"job_id\": job_id},\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "e7817e4c-3aa1-4f0e-be8d-0ebc656ec01a",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T12:46:34.288615Z",
          "iopub.status.busy": "2026-10-21T12:46:34.288403Z",
          "iopub.status.idle": "2026-10-21T13:00:39.002042Z",
          "shell.execute_reply": "2026-10-21T13:00:39.000990Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Bond dimension 128: 0.963 ± 0.006, classical 491.5 s\n",
            "Bond dimension 512: 0.963 ± 0.006, classical 658.8 s\n",
            "QPU time of the rerun: 0.0 s\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": []
        }
      ],
      "source": [
        "results_rerun = tem_job_rerun.result()\n",
        "rerun_evs = results_rerun[0].data.evs[0]\n",
        "rerun_std = results_rerun[0].data.stds[0]\n",
        "qpu_rerun, cpu_rerun = run_times(results_rerun)\n",
        "\n",
        "print(\n",
        "    f\"Bond dimension 128: {shots_evs:.3f} ± {shots_std:.3f}, classical {cpu_shots:.1f} s\"\n",
        ")\n",
        "print(\n",
        "    f\"Bond dimension 512: {rerun_evs:.3f} ± {rerun_std:.3f}, classical {cpu_rerun:.1f} s\"\n",
        ")\n",
        "print(f\"QPU time of the rerun: {qpu_rerun} s\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "be9ac053-fe84-4c1e-935b-21b39f018504",
      "metadata": {},
      "source": [
        "If the two values agree within their error bars, a bond dimension of 128 was enough for this circuit, and the larger one only costs classical time. If they differ, raise the bond dimension further with another rerun until the value stops changing. The smallest converged bond dimension is the cheapest accurate choice. For larger circuits it is good practice to start with a moderate bond dimension and raise it with reruns.\n",
        "\n",
        "`tem_compression_cutoff` can be tuned the same way. To estimate observables that were not requested in the original run, pass them in `rerun_observable`; see [Simulate a kicked Ising model with the TEM function](/docs/tutorials/simulate-kicked-ising-tem) for an example.\n",
        "\n",
        "## Compare the three runs\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "9d4e1f6b-2c5a-4b7e-a3f8-6e1d0c2b4a03",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T13:00:39.008707Z",
          "iopub.status.busy": "2026-10-21T13:00:39.008581Z",
          "iopub.status.idle": "2026-10-21T13:00:39.112059Z",
          "shell.execute_reply": "2026-10-21T13:00:39.110769Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/functions/algorithmiq-tem/performance-tuning/extracted-outputs/9d4e1f6b-2c5a-4b7e-a3f8-6e1d0c2b4a03-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "labels = [\n",
        "    \"Unmitigated\",\n",
        "    \"Run 1\\ndefault\",\n",
        "    \"Run 2\\n100k shots\",\n",
        "    \"Run 3\\n100k-bond 512\",\n",
        "]\n",
        "values = [unmitigated_evs, tem_evs, shots_evs, rerun_evs]\n",
        "errors = [unmitigated_stds, tem_std, shots_std, rerun_std]\n",
        "\n",
        "plt.bar(labels, values, yerr=errors, color=[\"grey\", \"c\", \"c\", \"c\"])\n",
        "plt.axhline(y=exact_evs, color=\"r\", linestyle=\"--\", label=\"Exact\")\n",
        "plt.ylabel(\"Expectation value\")\n",
        "plt.ylim(0, 1.1)\n",
        "plt.legend()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "30b40702",
      "metadata": {},
      "source": [
        "## Run 4: measure the light cone from the same data\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2d06314a",
      "metadata": {},
      "source": [
        "Because the measurement is informationally complete, the outcomes collected in run 2 contain the information needed to estimate any observable on the same circuit, not only the one requested. TEM keeps a backup of every run, so you can request new observables later with a **rerun** of the job. Pass its `job_id`, as in run 3, and the new observables in `rerun_observable`. If you do not set this option, the rerun uses the original observables.\n",
        "\n",
        "You can request new observables from a run that used `shadows_bias`, but the results are not as accurate as those from a run whose measurement was tuned for the requested observable. If you plan to reuse a run for different observables, do not set `compute_shadows_bias_from_observable` or `shadows_bias`.\n",
        "\n",
        "The following code estimates $\\langle \\hat{X}_n \\rangle$ on every qubit $n$, to check that the correlation sits only at $n = t$:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "id": "eae2fe7d",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T13:00:39.117737Z",
          "iopub.status.busy": "2026-10-21T13:00:39.117572Z",
          "iopub.status.idle": "2026-10-21T13:00:44.897669Z",
          "shell.execute_reply": "2026-10-21T13:00:44.894872Z"
        }
      },
      "outputs": [],
      "source": [
        "# One observable per qubit: X_n for n = 0, ..., num_qubits - 1\n",
        "light_cone_observables = [\n",
        "    xt_observable(num_qubits, n) for n in range(num_qubits)\n",
        "]\n",
        "\n",
        "rerun_job = tem.run(\n",
        "    pubs=pubs,  # ignored on a rerun\n",
        "    options={\n",
        "        \"job_id\": job_id,\n",
        "        # one list of observables per PUB of the original run\n",
        "        \"rerun_observable\": [light_cone_observables],\n",
        "        \"tem_max_bond_dimension\": 512,\n",
        "    },\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "id": "f40a4c5e",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-10-21T13:00:44.910175Z",
          "iopub.status.busy": "2026-10-21T13:00:44.909699Z",
          "iopub.status.idle": "2026-10-21T13:18:30.493090Z",
          "shell.execute_reply": "2026-10-21T13:18:30.491663Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/functions/algorithmiq-tem/performance-tuning/extracted-outputs/f40a4c5e-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "light_cone = rerun_job.result()[0]\n",
        "x_tem = light_cone.data.evs\n",
        "x_tem_std = light_cone.data.stds\n",
        "x_raw = light_cone.metadata[\"evs_wo_tem_wo_qdt\"]\n",
        "\n",
        "# Exact values at the self-dual point: [cos(2h)]^t at n = t, zero elsewhere\n",
        "x_exact = np.zeros(num_qubits)\n",
        "x_exact[t_steps] = np.cos(2 * h) ** t_steps\n",
        "\n",
        "sites = np.arange(num_qubits)\n",
        "plt.hlines(x_exact, sites - 0.4, sites + 0.4, colors=\"r\", label=\"Exact\")\n",
        "plt.plot(sites, x_raw, \"o\", color=\"grey\", label=\"Unmitigated\")\n",
        "plt.errorbar(sites, x_tem, yerr=x_tem_std, fmt=\"none\", ecolor=\"c\")\n",
        "plt.plot(sites, x_tem, \"o\", color=\"c\", label=\"TEM\")\n",
        "\n",
        "ticks = [\n",
        "    int(n) for n in plt.xticks()[0] if 0 <= n < num_qubits and n != t_steps\n",
        "]\n",
        "plt.xticks(ticks + [t_steps], [str(n) for n in ticks] + [\"$n=t$\"])\n",
        "\n",
        "plt.xlabel(\"Qubit $n$\")\n",
        "plt.ylabel(r\"$\\langle X_n \\rangle$\")\n",
        "plt.legend()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "485e52f1",
      "metadata": {},
      "source": [
        "TEM resolves the correlation on qubit $n = t$ while all other sites stay compatible with zero, which is the ballistic spreading predicted for the dual unitary point. All 24 estimates come from the measurement outcomes of a single QPU run.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "25e11562-5503-4f7c-9a8b-23756ff8106c",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "The following table summarizes each setting: the stage where it is used, what it improves, what it costs, and whether you can change it in a rerun.\n",
        "\n",
        "| Option                                                                                      | Stage               | Improves                                                             | Costs                          | Rerun |\n",
        "| ------------------------------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------- | ------------------------------ | ----- |\n",
        "| `default_precision`, `default_shots`                                                        | Sampling            | Statistical error                                                    | QPU time, classical time       | No    |\n",
        "| `compute_shadows_bias_from_observable`, `shadows_bias`                                      | Sampling            | Statistical error per shot                                           | None                           | No    |\n",
        "| `max_layers_to_learn`, `num_randomizations`, `shots_per_randomization`, `layer_pair_depths` | Noise learning      | Bias from the noise model                                            | QPU time                       | No    |\n",
        "| `noise_learner_job_id`                                                                      | Noise learning      | QPU time, by skipping the noise learning                             | Same qubits as the earlier run | No    |\n",
        "| `mitigate_readout_error`, `num_readout_calibration_shots`                                   | Readout calibration | Readout bias                                                         | QPU time                       | No    |\n",
        "| `tem_max_bond_dimension`, `tem_compression_cutoff`                                          | Post-processing     | Truncation bias                                                      | Classical time and memory      | Yes   |\n",
        "| `rerun_observable`                                                                          | Post-processing     | New observables from the same measurement outcomes, without QPU time | Classical time                 | Yes   |\n",
        "\n",
        "## Next steps\n",
        "\n",
        "* Explore the physics of the kicked Ising model at utility scale in [Simulate a kicked Ising model with the TEM function](/docs/tutorials/simulate-kicked-ising-tem).\n",
        "* See the full list of options in the [TEM API reference](/docs/functions/algorithmiq-tem/api-reference).\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
}