---
title: utils (latest version)
description: API reference for qiskit_mitigation.utils in the latest version of qiskit-mitigation
source: https://quantum.cloud.ibm.com/docs/en/api/qiskit-mitigation/utils
---

# Utils

`qiskit_mitigation.utils`

Qiskit mitigation utilities.

### load\_tasks\_from\_result

`load_tasks_from_result(result, return_trex=False)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/utils.py#L29-L91)

Load `MitigationTask` objects from an execution result using the passthrough\_data saved in the result.

**Parameters**

- **result** (*QuantumProgramResult*) – The resul object to load the tasks from.
- **return\_trex** ([*bool*](https://docs.python.org/3/builtins/functions.html#bool)) – If True, include TREX calibration element in the returned list of MitigationTask objects.

**Returns**

List of `MitigationTask` objects that created the program of the given result.

**Return type**

[list](https://docs.python.org/3/builtins/stdtypes.html#list)\[[MitigationTask](/docs/api/qiskit-mitigation/mitigation-task#qiskit_mitigation.MitigationTask "qiskit_mitigation.MitigationTask")]

### find\_combined\_unique\_layers

`find_combined_unique_layers(circuits, mitigation_types=None, custom_boxing_options=None, box_types='all')`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/utils.py#L94-L147)

Return the unique boxed layers found across the given circuits using the given boxing options.

The returned list contains one instance of each distinct boxed layer (represented as a `CircuitInstruction`) appearing in the input circuits. Some mitigation methods enforce relevant boxing options. By supllying the wanted mitigation methods, these options are enforced when boxing the circuits to find unique layers. Supplying the wanted mitigation methods is recommended to ensure that the unique layers used for learning wiil be equal to those used in execution. The returned boxes can be filtered so only boxes containing measurements, only boxes containing solely gates or all types of boxes are returned.

**Parameters**

- **circuits** ([*list*](https://docs.python.org/3/builtins/stdtypes.html#list)*\[QuantumCircuit]*) – The circuit to find the unique layers for.
- **mitigation\_types** ([*list*](https://docs.python.org/3/builtins/stdtypes.html#list)*\[*[*MitigationTask*](/docs/api/qiskit-mitigation/mitigation-task#qiskit_mitigation.MitigationTask "qiskit_mitigation.MitigationTask")*] | None*) – List of initiated mitigation classes that the circuits will be mitigated with. Each mitigation method might enforce boxing options that will affect the unique layers. If given, the list must be the same length as `circuits`.
- **custom\_boxing\_options** ([*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)  *|*[*list*](https://docs.python.org/3/builtins/stdtypes.html#list)*\[*[*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)*] | None*) – The custom boxing options that will be used by `generate_boxing_pass_manager()` function to find the unique layers. If a single dict is given, the same custom boxing option will be used for all tasks. If `None` is given, the default boxing option will be used.
- **box\_types** (*Literal\['gates', 'measurement', 'all']*) – Can be either `"gates"`, `"measurements"` or `"all"`, corresponding to filter boxes with only gate layers, only measurement layers or all layers, respectively.

**Returns**

Unique boxed layers found across the given circuits using the given boxing options.

**Return type**

[list](https://docs.python.org/3/builtins/stdtypes.html#list)\[CircuitInstruction]

### executor\_expectation\_values

`executor_expectation_values(bool_array, basis_mapping, /, meas_basis_axis=None, *, avg_axis=None, measurement_flips=None, pauli_signs=None, postselect_mask=None, gamma_factor=None, rescale_factors=None)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/expectation_values.py#L32-L245)

Computes expectation values from shot data from `qiskit_ibm_runtime.Executor` and metadata.

Uses data in `bool_array`, acquired with measurement bases as ordered in keys of `basis_mapping`, to compute observables encoded in values of `basis_mapping`.

Optionally allows averaging over additional axes of `bool_array`, as when twirling.

Optionally supports measurement twirling, PEC, and postselection.

**Parameters**

- **bool\_array** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)*\[*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*, ...],* [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype)*\[*[*bool*](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bool)*]]*) – Boolean array, presumably representing data from measured qubits. The last two axes are the number of shots and number of classical bits, respectively. The least significant bit is assumed to be at index `0` of the bits axis. If `meas_basis_axis` is given, that axis of `bool_array` indexes the measurement bases, with length `len(basis_mapping)`.

- **basis\_mapping** ([*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)*\[*[*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli)*,* [*list*](https://docs.python.org/3/builtins/stdtypes.html#list)*\[*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)  *| None]] |*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)*],* [*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str)*] |* [*PauliList*](/docs/api/qiskit/qiskit.quantum_info.PauliList)*]*) –

  The Pauli observables and associated bases which were measured. Can be a `tuple`, `(observables, msmt_bases)`, or a `dict`, `{basis: commuting_observables}`.

  - **tuple**: A length-2 tuple containing `(observables, msmt_bases)`, where `observables` is a sequence of `SparsePauliOp` instances for which individual expectation values should be calculated, and `msmt_bases` is a sequence of Pauli observables. The `i` th Pauli in `msmt_bases` is expected to correspond to the `i` th slice of `bool_array` along the `meas_basis_axis`.
  - **dict**: The `i` th key is a measurement basis assumed to correspond to the `i` th slice of `bool_array` along the `meas_basis_axis` axis. The values are lists of observables (`SparsePauliOp`) with length equal to the number of observables. `None` values are used when an observable does not qubit-wise commute with the basis. This method assumes each observable appears only once in the values, even if it commutes with more than one basis.

- **meas\_basis\_axis** ([*int*](https://docs.python.org/3/builtins/functions.html#int) *| None*) – Axis of bool\_array that indexes measurement bases. Ordering must match ordering in `basis_mapping`. If `None`, then `len(basis_mapping)` must be `1`, and `bool_array` is assumed to correspond to the only measurement basis.

- **avg\_axis** ([*int*](https://docs.python.org/3/builtins/functions.html#int)  *|*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*, ...] | None*) – Optional axis or axes of bool\_array to average over when computing expectation values. Usually this is the “twirling” axis. Must be nonnegative. (The shots axis, assumed to be at index `-2` in the boolean array, is always averaged over).

- **measurement\_flips** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)*\[*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*, ...],* [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype)*\[*[*bool*](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bool)*]] | None*) – Optional boolean array used with measurement twirling. Indicates which bits were acquired with measurements preceded by bit-flip gates. Data processing will use the result of XOR’ing this array with `bool_array`. Must be same shape as `bool_array`.

- **pauli\_signs** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)*\[*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*, ...],* [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype)*\[*[*bool*](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bool)*]] | None*) – Optional boolean array used with probabilistic error cancellation (PEC). Final axis is assumed to index all noisy boxes in circuit. Value of `True` indicates an overall sign of `-1` should be associated with the noisy box, typically because an odd number of inverse-noise errors were inserted in that box for the specified circuit randomization. The final axis is immediately collapsed as a sum mod 2 to obtain the overall sign associated with each circuit randomization. Remaining shape must be `pauli_signs.shape[:-1] == bool_array.shape[:-2]`. Note this array does not have a shots axis.

- **postselect\_mask** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)*\[*[*tuple*](https://docs.python.org/3/builtins/stdtypes.html#tuple)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*, ...],* [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype)*\[*[*bool*](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bool)*]] | None*) – Optional boolean array used for postselection. `True` (`False`) indicates a shot accepted (rejected) by postselection. Shape must be `bool_array.shape[:-1]`.

- **gamma\_factor** ([*float*](https://docs.python.org/3/builtins/functions.html#float) *| None*) – Rescaling factor gamma to be applied to PEC mitigated expectation values. If `None`, rescaling factors will be computed as the number of positive samples minus the number of negative samples, computed as `1/(np.sum(~pauli_signs, axis=avg_axis) - np.sum(pauli_signs, axis=avg_axis))`. This can fail due to division by zero if there are an equal number of positive and negative samples. Also note this rescales each expectation value by a different factor. (TODO: allow specifying an array of gamma values).

- **rescale\_factors** ([*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)*\[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str)*,* [*float*](https://docs.python.org/3/builtins/functions.html#float)*] | None*) – Scale factor for each unique Pauli term found in the calculated observables. Typically used for readout mitigation (“TREX”) correction factors. If `None`, scaling factor will not be applied.

**Returns**

A list of (exp. val, variance) 2-tuples, one for each desired observable.

**Note: Covariances between summed terms in each observable are not currently accounted for in the**

returned variances. # TODO

**Raises**

- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – `avg_axis` contains negative values, repeated axes, or one of the last two (shots, bits) axes.
- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – `avg_axis` contains `meas_basis_axis`.
- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – `meas_basis_axis` is `None` but `len(basis_mapping) != 1`.
- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – `meas_basis_axis` is negative or indexes one of the last two (shots, bits) axes of `bool_array`.
- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – The number of entries in `basis_mapping` does not equal the length of `bool_array` along `meas_basis_axis`.
- [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – An observable is not covered by the measurement bases.

### get\_measurement\_bases

`get_measurement_bases(observables)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/measurement_bases.py#L33-L74)

Choose bases to sample in order to calculate expectation values for all given observables.

Here a “basis” refers to measurement of a full-weight or high-weight Pauli, from which multiple qubit-wise commuting Paulis may be estimated.

The bases are chosen by grouping commuting Paulis across the different observables.

**Parameters**

**observables** ([*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)  *|*[*list*](https://docs.python.org/3/builtins/stdtypes.html#list)*\[*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)*]*) – The observables to calculate using the quantum computer.

**Returns**

- List of Pauli bases to sample encoded in a list of uint8 where 0=I,1=Z,2=X,3=Y.
- Dict that maps each measured basis to the relevant Paulis and their coefficients for each observable. With the measured bases as keys, for each observable there is a SparsePauliOp representing it.

**Return type**

[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)\[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)\[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)\[[int](https://docs.python.org/3/builtins/functions.html#int), …], [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype)\[*uint8*]], [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)\[[*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli), [list](https://docs.python.org/3/builtins/stdtypes.html#list)\[[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)]]]

### map\_observable\_isa\_to\_canonical

`map_observable_isa_to_canonical(isa_observable, canonical_qubits)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/observable_mappings.py#L45-L62)

Map an observable defined relative to the transpiled circuit to canonical box-order.

In the transpiled (or ISA) ordering, the qubits are indexed based on the “physical” layout of qubits in the device.

For info on canonical qubit ordering conventions see the [Samplomatic docs](https://qiskit.github.io/samplomatic/guides/samplex_io.html#qubit-ordering-convention)).

**Parameters**

- **isa\_observable** ([*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli)  *|*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)  *|*[*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)) – A Pauli, SparsePauliOp, or SparseObservable object.
- **canonical\_qubits** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*]*) – A sequence specifying the physical qubit for each canonical qubit.

**Returns**

A mapped operator of the same type as `isa_observable`

**Return type**

[*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli) | [*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp) | [*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)

### map\_observable\_virtual\_to\_canonical

`map_observable_virtual_to_canonical(virt_observable, layout, canonical_qubits)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/observable_mappings.py#L65-L83)

Map an observable with virtual qubit ordering to canonical box-order.

For info on canonical qubit ordering conventions see the [Samplomatic docs](https://qiskit.github.io/samplomatic/guides/samplex_io.html#qubit-ordering-convention)).

**Parameters**

- **virt\_observable** ([*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli)  *|*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)  *|*[*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)) – A Pauli, SparsePauliOp, or SparseObservable object.
- **layout** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*]*) – The list of physical qubits used for the isa circuit.
- **canonical\_qubits** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*]*) – A sequence specifying the physical qubit for each canonical qubit.

**Returns**

A mapped operator of the same type as `virt_observable`

**Return type**

[*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli) | [*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp) | [*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)

### map\_observable\_isa\_to\_virtual

`map_observable_isa_to_virtual(isa_observable, layout)`

[GitHub](https://github.com/Qiskit/qiskit-mitigation/tree/stable/0.1/qiskit_mitigation/utils/observable_mappings.py#L86-L101)

Map an observable defined relative to the transpiled circuit to virtual order.

In the transpiled (or ISA) ordering, the qubits are indexed based on the “physical” layout of qubits in the device.

**Parameters**

- **isa\_observable** ([*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli)  *|*[*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp)  *|*[*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)) – A Pauli, SparsePauliOp, or SparseObservable object.
- **layout** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*\[*[*int*](https://docs.python.org/3/builtins/functions.html#int)*]*) – The list of physical qubits used for the isa circuit.

**Returns**

A mapped operator of the same type as `isa_observable`

**Return type**

[*Pauli*](/docs/api/qiskit/qiskit.quantum_info.Pauli) | [*SparsePauliOp*](/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp) | [*SparseObservable*](/docs/api/qiskit/qiskit.quantum_info.SparseObservable)
