exp_vals
qiskit_addon_utils.exp_vals
Tools for calculating expectation values.
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)
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_dict, to compute observables encoded in values of basis_dict.
Optionally allows averaging over additional axes of bool_array, as when twirling.
Optionally supports measurement twirling, PEC, and postselection.
Parameters
-
bool_array (ndarray[tuple[int, ...], dtype[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
0of the bits axis. Ifmeas_basis_axisis given, that axis ofbool_arrayindexes the measurement bases, with lengthlen(basis_mapping). -
basis_mapping (dict[Pauli, list[SparsePauliOp | None]] |tuple[Sequence[SparsePauliOp], Sequence[str] | PauliList]) –
The Pauli observables and associated bases which were measured. Can be a
tuple,(observables, msmt_bases), or adict,{basis: commuting_observables}.- tuple: A length-2 tuple containing
(observables, msmt_bases), whereobservablesis a sequence ofSparsePauliOpinstances for which individual expectation values should be calculated, andmsmt_basesis a sequence of Pauli observables. Theith Pauli inmsmt_basesis expected to correspond to theith slice ofbool_arrayalong themeas_basis_axis. - dict: The
ith key is a measurement basis assumed to correspond to theith slice ofbool_arrayalong themeas_basis_axisaxis. The values are lists of observables (SparsePauliOp) with length equal to the number of observables.Nonevalues 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.
- tuple: A length-2 tuple containing
-
meas_basis_axis (int | None) – Axis of bool_array that indexes measurement bases. Ordering must match ordering in
basis_mapping. IfNone, thenlen(basis_mapping)must be1, andbool_arrayis assumed to correspond to the only measurement basis. -
avg_axis (int |tuple[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
-2in the boolean array, is always averaged over). -
measurement_flips (ndarray[tuple[int, ...], dtype[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 asbool_array. -
pauli_signs (ndarray[tuple[int, ...], dtype[bool]] | None) – Optional boolean array used with probabilistic error cancellation (PEC). Final axis is assumed to index all noisy boxes in circuit. Value of
Trueindicates an overall sign of-1should 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 bepauli_signs.shape[:-1] == bool_array.shape[:-2]. Note this array does not have a shots axis. -
postselect_mask (ndarray[tuple[int, ...], dtype[bool]] | None) – Optional boolean array used for postselection.
True(False) indicates a shot accepted (rejected) by postselection. Shape must bebool_array.shape[:-1]. -
gamma_factor (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 as1/(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 (Sequence[Sequence[Sequence[float]]] | None) – Scale factor for each Pauli term in each observable in each basis in the given
basis_mapping. Typically used for readout mitigation (“TREX”) correction factors. Each item in the list corresponds to a different basis, and contains a list of lists of factors for each term in each observable related to that basis. The order of the bases and the observables inside each basis should be the same as inbasis_mapping. For empty observables for some of the bases, keep an empty list. IfNone, 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 –
avg_axiscontains negative values. - ValueError –
meas_basis_axisisNonebutlen(basis_mapping) != 1. - ValueError – The number of entries in
basis_mappingdoes not equal the length ofbool_arrayalongmeas_basis_axis. - ValueError – An observable is not covered by the measurement bases.
get_measurement_bases
get_measurement_bases(observables, bases_in_int_format=True)
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 |list[SparsePauliOp]) – The observables to calculate using the quantum computer.
- bases_in_int_format (bool) – If true, return bases as an array of ints, using the samplomatic convention of: I=0, Z=1, X=2, Y=3. The order of the ints will be according to the index of each Pauli in the string. For example, the basis “IXYZ” would be returned as [1, 3, 2, 0]. If false, return the bases as an array of strings.
Returns
- List of Pauli bases to sample encoded in a list of uint8 where 0=I,1=Z,2=X,3=Y or a list of strings (based on bases_in_int_format parameter).
- 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[list[ndarray[tuple[int, …], dtype[uint8]]], dict[Pauli, list[SparsePauliOp]]] | tuple[list[str], dict[Pauli, list[SparsePauliOp]]]
map_observable_isa_to_canonical
map_observable_isa_to_canonical(isa_observable, canonical_qubits)
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).
Parameters
- isa_observable (Pauli |SparsePauliOp |SparseObservable) – A Pauli, SparsePauliOp, or SparseObservable object.
- canonical_qubits (Sequence[int]) – A sequence specifying the physical qubit for each canonical qubit.
Returns
A mapped operator of the same type as isa_observable
Return type
map_observable_virtual_to_canonical
map_observable_virtual_to_canonical(virt_observable, layout, canonical_qubits)
Map an observable with virtual qubit ordering to canonical box-order.
For info on canonical qubit ordering conventions see the Samplomatic docs).
Parameters
- virt_observable (Pauli |SparsePauliOp |SparseObservable) – A Pauli, SparsePauliOp, or SparseObservable object.
- layout (Sequence[int]) – The list of physical qubits used for the isa circuit.
- canonical_qubits (Sequence[int]) – A dictionary mapping canonical qubits within a box to physical qubits within the layout.
Returns
A mapped operator of the same type as virt_observable
map_observable_isa_to_virtual
map_observable_isa_to_virtual(isa_observable, layout)
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 |SparsePauliOp |SparseObservable) – A Pauli, SparsePauliOp, or SparseObservable object.
- layout (Sequence[int]) – The list of physical qubits used for the isa circuit.
Returns
A mapped operator of the same type as isa_observable
Return type