Skip to main contentIBM Quantum Documentation Preview
This is a preview build of IBM Quantum® documentation. Refer to quantum.cloud.ibm.com/docs for the official documentation.

Tune the TEM function for accuracy and cost

See the overview and the API reference

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.

This example takes a 24-qubit kicked Ising circuit, whose exact result is known, and runs it four times:

  1. With the default options, to see where TEM spends QPU and classical time.
  2. With more shots, and with the noise model that the first run learned, so that the noise learning is not repeated.
  3. As a rerun of the second run with a larger bond dimension, which repeats only the post-processing and uses no QPU time.
  4. As a rerun of the second run with a larger bond dimension and a different observable.

The physics of the circuit is explained in Simulate a kicked Ising model with the TEM function.

Usage estimate: approximately 26 QPU seconds (measured on a Nighthawk r2 device; the runtime depends on the chosen device).


Setup

As a prerequisite, ensure that the necessary dependencies are installed.

%pip install numpy matplotlib qiskit qiskit-ibm-catalog qiskit-ibm-runtime pylatexenc qiskit_qasm3_import
from matplotlib import pyplot as plt
import numpy as np

from qiskit.quantum_info import SparsePauliOp
from qiskit.transpiler import generate_preset_pass_manager

from qiskit_ibm_catalog import FunctionsCatalog
from qiskit_ibm_runtime import QiskitRuntimeService

The circuit is a kicked Ising chain of 24 qubits evolved for 12 periods at the self-dual point with h=0h = 0. The observable ⟨X^n=12⟩\langle \hat{X}_{n=12} \rangle has the exact value [cos⁡(2h)]12=1[\cos(2h)]^{12} = 1, which is used to judge the accuracy of each setting.

from qiskit import QuantumCircuit


def xt_observable(n_qubits, t_steps):
    pauli_str = "".join(["I" * t_steps, "X", "I" * (n_qubits - t_steps - 1)])
    pauli_str = pauli_str[::-1]  # Reverse the string to match qiskit order
    return SparsePauliOp(data=pauli_str, coeffs=1.0)


def kicked_ising_circuit(n_qubits, t_steps):
    """Kicked Ising circuit at the self-dual point (J = b = pi/4, h = 0)."""
    circuit = QuantumCircuit(n_qubits)

    # State preparation: |+> on qubit 0, Bell pairs on (1, 2), (3, 4), ...
    circuit.h(0)
    for i in range(1, n_qubits - 1, 2):
        circuit.h(i)
        circuit.x(i + 1)
        circuit.cx(i, i + 1)
    circuit.barrier()

    # Clifford two-qubit block: one ZZ rotation, X kick, one ZZ rotation
    block = QuantumCircuit(2)
    block.sdg([0, 1])
    block.cx(0, 1)
    block.sdg(0)
    block.h([0, 1])
    block.s(1)
    block.cx(0, 1)
    block.s(0)
    block.h(0)
    block.sdg(0)
    block.y(1)
    block.h(1)

    # Brickwork: even periods act on (0, 1), (2, 3), ...; odd periods on (1, 2), (3, 4), ...
    for step in range(t_steps):
        for q in range(step % 2, n_qubits - 1, 2):
            circuit.compose(block, [q, q + 1], inplace=True)
        circuit.barrier()
    return circuit
# Parameters of the kicked Ising model
h = 0.0
num_qubits = 24
t_steps = 12

small_circuit = kicked_ising_circuit(num_qubits, t_steps)


small_observable = xt_observable(n_qubits=num_qubits, t_steps=t_steps)
exact_evs = np.cos(2 * h) ** t_steps

Next, get access to the TEM function and select a backend from the available devices. This code assumes you've already saved your account to your local environment.

# Select the QPU backend
backend_name = "ibm_phoenix"  # Replace with your desired backend's name

Load the TEM function from the IBM Quantum® Functions Catalog:

# Load the TEM function from the Quantum Functions Catalog
catalog = FunctionsCatalog()
tem = catalog.load("algorithmiq/tem")

Transpile the circuit one time

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.

service = QiskitRuntimeService()
backend = service.backend(backend_name)

pass_manager = generate_preset_pass_manager(
    optimization_level=3, backend=backend, seed_transpiler=42
)
small_circuit.measure_all()
isa_circuit = pass_manager.run(small_circuit)
small_circuit.remove_final_measurements(inplace=True)
isa_circuit.remove_final_measurements(inplace=True)
isa_observable = small_observable.apply_layout(isa_circuit.layout)


pubs = [(isa_circuit, [isa_observable])]

Calculate the function size

Every TEM job runs at a size, S, M or L, which selects the compute profile it runs on; see Function sizes.

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.

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, estimates it and more accurately recommends the size the classical compute needs. Request the larger of the two sizes.

# Calculate the function size a circuit needs, before submitting it.
#
# Call ``calculate_function_size(pubs, backend)``: it returns "S", "M" or "L" and submits
# nothing. Pass the whole list of PUBs -- a job runs at one size, and the heaviest PUB
# decides it. The circuit is measured after being mapped onto ``backend``, since mapping
# can add both qubits and depth.

from collections.abc import Iterable
from typing import Any, Literal

from qiskit.circuit import Barrier
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
    ApplyLayout,
    BarrierBeforeFinalMeasurements,
    BasisTranslator,
    EnlargeWithAncilla,
    FilterOpNodes,
    FullAncillaAllocation,
    HighLevelSynthesis,
    SabreSwap,
    TrivialLayout,
    UnitarySynthesis,
)

Size = Literal["S", "M", "L"]
_ORDER = {"S": 0, "M": 1, "L": 2}

# Limits are provided by IBM
_SMALL_QUBITS, _SMALL_DEPTH_2Q = 40, 40
_MEDIUM_QUBITS, _MEDIUM_DEPTH_2Q = 100, 100

# Any fixed value works; what matters is that it does not change between calls.
_SEED_TRANSPILER = 42

# Added by BarrierBeforeFinalMeasurements so routing cannot move gates past a measurement,
# then removed again once routing is done.
_PROTECTION_BARRIER = "qiskit.transpiler.internal.routing.protection.barrier"


def calculate_function_size(
    circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any
) -> Size:
    """Return the size ("S", "M" or "L") required to run the function."""
    circuits = pub_circuits(circuit)
    if not circuits:
        raise ValueError(
            "No circuit to size: pass a QuantumCircuit or a non-empty list of PUBs."
        )
    return max(
        (_calculate_circuit_size(qc, backend, **kwargs) for qc in circuits),
        key=_ORDER.__getitem__,
    )


def _calculate_circuit_size(
    circuit: QuantumCircuit, backend, **kwargs: Any
) -> Size:
    """Return the size required to run a single circuit."""
    metrics = _measure(circuit, backend, **kwargs)
    if _is_small(metrics):
        return "S"
    if _is_medium(metrics):
        return "M"
    return "L"


def pub_circuits(problem: Any) -> list[QuantumCircuit]:
    """Return the circuits in ``problem``: one circuit, or one per PUB in a list."""
    if isinstance(problem, QuantumCircuit):
        return [problem]
    circuits: list[QuantumCircuit] = []
    for index, pub in enumerate(problem):
        if isinstance(pub, QuantumCircuit):
            circuit = pub
        elif isinstance(getattr(pub, "circuit", None), QuantumCircuit):
            circuit = pub.circuit
        elif (
            isinstance(pub, (tuple, list))
            and pub
            and isinstance(pub[0], QuantumCircuit)
        ):
            circuit = pub[0]
        else:
            raise ValueError(f"PUB #{index} has no QuantumCircuit to size.")
        circuits.append(circuit)
    return circuits


def _pass_manager(target) -> PassManager:
    """Return the pass manager used to map a circuit onto ``target``.

    Fixed and seeded, so the same circuit always gives the same size.
    """
    basis = list(target.operation_names)
    library = SessionEquivalenceLibrary
    return PassManager(
        [
            UnitarySynthesis(
                basis, approximation_degree=1.0, min_qubits=3, target=target
            ),
            HighLevelSynthesis(
                target=target,
                equivalence_library=library,
                basis_gates=basis,
                min_qubits=3,
            ),
            BasisTranslator(library, basis, target=target, min_qubits=3),
            TrivialLayout(target),
            FullAncillaAllocation(target),
            EnlargeWithAncilla(),
            ApplyLayout(),
            BarrierBeforeFinalMeasurements(label=_PROTECTION_BARRIER),
            SabreSwap(
                target, heuristic="basic", seed=_SEED_TRANSPILER, trials=5
            ),
            FilterOpNodes(lambda node: node.label != _PROTECTION_BARRIER),
            UnitarySynthesis(basis, approximation_degree=1.0, target=target),
            HighLevelSynthesis(
                target=target,
                equivalence_library=library,
                basis_gates=basis,
                use_qubit_indices=True,
            ),
            BasisTranslator(library, basis, target=target),
        ]
    )


def _count(isa: QuantumCircuit) -> dict:
    """Return the active qubits and two-qubit-gate depth of a mapped circuit."""
    active = {
        q
        for instr in isa.data
        if not isinstance(instr.operation, Barrier)
        for q in instr.qubits
    }
    return {
        "num_qubits": len(active),
        "depth_2q": isa.depth(
            filter_function=lambda instr: len(instr.qubits) == 2
            and not isinstance(instr.operation, Barrier)
        ),
    }


def _measure(circuit: QuantumCircuit, backend, **kwargs: Any) -> dict:
    """Map ``circuit`` onto ``backend`` and return its metrics."""
    return _count(_pass_manager(backend.target).run(circuit))


def _is_small(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'S'."""
    return (
        metrics["num_qubits"] <= _SMALL_QUBITS
        and metrics["depth_2q"] <= _SMALL_DEPTH_2Q
    )


def _is_medium(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'M'."""
    return (
        metrics["num_qubits"] <= _MEDIUM_QUBITS
        and metrics["depth_2q"] <= _MEDIUM_DEPTH_2Q
    )
size = calculate_function_size(pubs, backend)  # "S", "M" or "L"
print(size)

Output:

S

Estimate the resources before running

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.

  • circuit_size_tag: the size the circuit needs, as computed by the preceding size calculator.
  • 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=...).
  • estimated_resource_usage_pub, in the metadata of each PUB: the estimated times of each stage, in seconds, and the peak memory.

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.

estimate_job = tem.run(
    pubs=pubs, backend_name=backend_name, options={"dry_run": True}
)
estimate = estimate_job.result()

for key in (
    "estimated_resource_usage_job",
    "circuit_size_tag",
    "classical_compute_size_tag",
):
    print(f"{key}: {estimate.metadata[key]}")
for key, value in (
    estimate[0].metadata["estimated_resource_usage_pub"].items()
):
    print(f"  {key}: {value}")

Run 1: default options

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:

tem_job = tem.run(pubs=pubs, backend_name=backend_name, function_size=size)

You can check the status of your job on the IBM Quantum Platform dashboard or with:

print(tem_job.job_id)
print(tem_job.status())

Output:

7390dda0-55e8-4ab2-b24b-c87ddc519e6a
DONE

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, ⟨X^n=t⟩\langle \hat X_{n=t}\rangle, and tem_std are the corresponding standard deviations.

# Get the results of the TEM job
tem_results = tem_job.result()[
    0
]  # Get the first and only result from the job
tem_evs = tem_results.data.evs[0]
tem_std = tem_results.data.stds[0]

unmitigated = tem_results.metadata["evs_wo_tem_wo_qdt"][0]
un_std = tem_results.metadata["stds_wo_tem_wo_qdt"][0]

print(
    f"TEM Result: {tem_evs:.3f} ± {tem_std:.3f}, unmitigated value {unmitigated} ± {un_std}"
)

Output:

TEM Result: 0.942 ± 0.008, unmitigated value 0.90048 ± 0.006566971554072699

Where TEM spends its time

A TEM run has four stages. The first three run on the QPU, and the last one runs on IBM Cloud®:

  1. Noise learning: learns a sparse Pauli-Lindblad noise model for each distinct layer of two-qubit gates.
  2. Readout calibration: characterizes the measurement error, to mitigate it.
  3. Sampling: runs the circuit with an informationally complete (IC) measurement.
  4. Post-processing: builds the tensor network that inverts the learned noise and applies it to the measurement outcomes.

The result metadata reports the time spent in each:

resource_usage = tem_job.result().metadata["resource_usage"]
for stage, usage in resource_usage.items():
    print(f"{stage}: {usage}")

Output:

RUNNING: OPTIMIZING_FOR_HARDWARE: {'CPU_TIME': 2.7649269999999997}
RUNNING: WAITING_FOR_QPU: {'CPU_TIME': 16.077092999999998}
RUNNING: POST_PROCESSING: {'CPU_TIME': 486.055132}
RUNNING: EXECUTING_QPU: {'QPU_TIME': 17.0}

The options, stage by stage

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.

Sampling: statistical error.

  • 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.
  • default_shots: the number of shots per PUB, which overrides any precision. The standard error scales as 1/shots1/\sqrt{\text{shots}}.
  • compute_shadows_bias_from_observable: tailors the probabilities of measuring in the ZZ, XX, and YY bases to the observables. For an observable dominated by one Pauli, such as the X^\hat{X} operator in this example, this lowers the shots needed for a given precision. shadows_bias sets the probabilities by hand.

Noise learning: bias. A noise model that is less accurate leaves a bias in the mitigated values that more shots cannot remove.

  • 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.
  • 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.
  • layer_pair_depths: the circuit depths used to fit the noise. Deeper pairs resolve smaller error rates.
  • 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.

These follow the definitions of the qiskit-ibm-runtime NoiseLearnerOptions.

Advanced TEM settings

Readout calibration.

  • 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.
  • num_readout_calibration_shots: the shots of the calibration (default 10,000).

Post-processing: classical time and truncation error.

  • 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.
  • tem_compression_cutoff: the singular values discarded when compressing the network. Smaller values keep more of the network.

Refer to the TEM API reference for the full list of options.


Reuse previous data

When you reuse previous QPU data, a new job uses the results of past experiments. When you make this request, TEM ignores any other QPU settings that you give for the same job, without a warning.


Run 2: reuse the noise model, increase the shots

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/shots1/\sqrt{\text{shots}}.

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.

Caution

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.

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.

This can be verified by checking the log for the following warning:

Computed number of shots from the precision is xxx, which exceeds the maximum allowed (50000)

To improve the precision in this case, use the default_shots key, which is not bounded.

options_shots = {
    "noise_learner_job_id": tem_job.job_id,  # reuse the noise model of run 1
    "default_shots": 100_000,
}

Submit run 2. Its QPU time is spent on the readout calibration and the sampling only:

tem_job_shots = tem.run(
    pubs=pubs,
    backend_name=backend_name,
    options=options_shots,
    function_size=size,
)

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.

job_id = tem_job_shots.job_id
print(f"Job ID: {job_id}")
print(tem_job_shots.status())

Output:

Job ID: 2e39789f-efa4-4fa8-9c6b-e2a566168354
DONE
results_shots = tem_job_shots.result()
shots_evs = results_shots[0].data.evs[0]
shots_std = results_shots[0].data.stds[0]

print(f"TEM Result: {shots_evs:.3f} ± {shots_std:.3f}")

Output:

TEM Result: 0.963 ± 0.006

Inspect the results and the metadata to get insight into the experiment:

metadata_shots = results_shots[0].metadata

unmitigated_evs = metadata_shots["evs_wo_tem_wo_qdt"][0]
unmitigated_stds = metadata_shots["stds_wo_tem_wo_qdt"][0]
print(f"Unmitigated Result: {unmitigated_evs:.3f} ± {unmitigated_stds:.3f}")
print("Exact Result:", exact_evs)

Output:

Unmitigated Result: 0.917 ± 0.005
Exact Result: 1.0

Compare the QPU and classical time of the two runs:

def run_times(result):
    """Return the QPU time and the classical time of a TEM job, in seconds."""
    usage = result.metadata["resource_usage"]
    qpu = usage["RUNNING: EXECUTING_QPU"]["QPU_TIME"]
    cpu = sum(
        usage.get(step, {}).get("CPU_TIME", 0.0)
        for step in (
            "RUNNING: OPTIMIZING_FOR_HARDWARE",
            "RUNNING: POST_PROCESSING",
        )
    )
    return qpu, cpu


qpu_default, cpu_default = run_times(tem_job.result())
qpu_shots, cpu_shots = run_times(results_shots)
print(f"Run 1: QPU {qpu_default} s, classical {cpu_default:.1f} s")
print(f"Run 2: QPU {qpu_shots} s, classical {cpu_shots:.1f} s")

Output:

Run 1: QPU 17.0 s, classical 488.8 s
Run 2: QPU 7.0 s, classical 491.5 s

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.

Effect of readout mitigation

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:

labels = {
    "No mitigation": "evs_wo_tem_wo_qdt",
    "Readout only": "evs_wo_tem_w_qdt",
    "TEM only": "evs_w_tem_wo_qdt",
}
for label, key in labels.items():
    std_key = key.replace("evs", "stds")
    print(
        f"{label:>14}: {metadata_shots[key][0]:.3f} ± {metadata_shots[std_key][0]:.3f}"
    )
print(f"{'TEM + readout':>14}: {shots_evs:.3f} ± {shots_std:.3f}")
print(f"{'Exact':>14}: {exact_evs:.3f}")

Output:

 No mitigation: 0.917 ± 0.005
  Readout only: 0.929 ± 0.005
      TEM only: 0.951 ± 0.006
 TEM + readout: 0.963 ± 0.006
         Exact: 1.000

Run 3: rerun with a larger bond dimension

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.

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.

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.

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:

tem_job_rerun = tem.run(
    pubs=pubs,  # ignored on a rerun
    options={"tem_max_bond_dimension": 512, "job_id": job_id},
)
results_rerun = tem_job_rerun.result()
rerun_evs = results_rerun[0].data.evs[0]
rerun_std = results_rerun[0].data.stds[0]
qpu_rerun, cpu_rerun = run_times(results_rerun)

print(
    f"Bond dimension 128: {shots_evs:.3f} ± {shots_std:.3f}, classical {cpu_shots:.1f} s"
)
print(
    f"Bond dimension 512: {rerun_evs:.3f} ± {rerun_std:.3f}, classical {cpu_rerun:.1f} s"
)
print(f"QPU time of the rerun: {qpu_rerun} s")

Output:

Bond dimension 128: 0.963 ± 0.006, classical 491.5 s
Bond dimension 512: 0.963 ± 0.006, classical 658.8 s
QPU time of the rerun: 0.0 s

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.

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 for an example.


Compare the three runs

labels = [
    "Unmitigated",
    "Run 1\ndefault",
    "Run 2\n100k shots",
    "Run 3\n100k-bond 512",
]
values = [unmitigated_evs, tem_evs, shots_evs, rerun_evs]
errors = [unmitigated_stds, tem_std, shots_std, rerun_std]

plt.bar(labels, values, yerr=errors, color=["grey", "c", "c", "c"])
plt.axhline(y=exact_evs, color="r", linestyle="--", label="Exact")
plt.ylabel("Expectation value")
plt.ylim(0, 1.1)
plt.legend()
plt.show()

Output:

Output of the previous code cell

Run 4: measure the light cone from the same data

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.

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.

The following code estimates ⟨X^n⟩\langle \hat{X}_n \rangle on every qubit nn, to check that the correlation sits only at n=tn = t:

# One observable per qubit: X_n for n = 0, ..., num_qubits - 1
light_cone_observables = [
    xt_observable(num_qubits, n) for n in range(num_qubits)
]

rerun_job = tem.run(
    pubs=pubs,  # ignored on a rerun
    options={
        "job_id": job_id,
        # one list of observables per PUB of the original run
        "rerun_observable": [light_cone_observables],
        "tem_max_bond_dimension": 512,
    },
)
light_cone = rerun_job.result()[0]
x_tem = light_cone.data.evs
x_tem_std = light_cone.data.stds
x_raw = light_cone.metadata["evs_wo_tem_wo_qdt"]

# Exact values at the self-dual point: [cos(2h)]^t at n = t, zero elsewhere
x_exact = np.zeros(num_qubits)
x_exact[t_steps] = np.cos(2 * h) ** t_steps

sites = np.arange(num_qubits)
plt.hlines(x_exact, sites - 0.4, sites + 0.4, colors="r", label="Exact")
plt.plot(sites, x_raw, "o", color="grey", label="Unmitigated")
plt.errorbar(sites, x_tem, yerr=x_tem_std, fmt="none", ecolor="c")
plt.plot(sites, x_tem, "o", color="c", label="TEM")

ticks = [
    int(n) for n in plt.xticks()[0] if 0 <= n < num_qubits and n != t_steps
]
plt.xticks(ticks + [t_steps], [str(n) for n in ticks] + ["$n=t$"])

plt.xlabel("Qubit $n$")
plt.ylabel(r"$\langle X_n \rangle$")
plt.legend()
plt.show()

Output:

Output of the previous code cell

TEM resolves the correlation on qubit n=tn = 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.


Summary

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.

Option
Stage
Improves
Costs
Rerun
default_precision, default_shotsSamplingStatistical errorQPU time, classical timeNo
compute_shadows_bias_from_observable, shadows_biasSamplingStatistical error per shotNoneNo
max_layers_to_learn, num_randomizations, shots_per_randomization, layer_pair_depthsNoise learningBias from the noise modelQPU timeNo
noise_learner_job_idNoise learningQPU time, by skipping the noise learningSame qubits as the earlier runNo
mitigate_readout_error, num_readout_calibration_shotsReadout calibrationReadout biasQPU timeNo
tem_max_bond_dimension, tem_compression_cutoffPost-processingTruncation biasClassical time and memoryYes
rerun_observablePost-processingNew observables from the same measurement outcomes, without QPU timeClassical timeYes

Next steps