API-doc#
Benchmarks#
Mirror Circuits#
Functions for creating mirror circuits as defined in [49] for benchmarking quantum computers (with error mitigation).
- mitiq.benchmarks.mirror_circuits.edge_grab(two_qubit_gate_prob, connectivity_graph, random_state)[source]#
- Parameters:
two_qubit_gate_prob (
float
) – Probability of an edge being chosen from the set of candidate edges.connectivity_graph (
Graph
) – The connectivity graph for the backend on which the circuit will be run.random_state (
RandomState
) – Random state to select edges (uniformly at random).
- Return type:
Graph
- Returns:
Returns a set of edges for which two qubit gates are to be applied given a two qubit gate density and the connectivity graph that must be satisfied.
- mitiq.benchmarks.mirror_circuits.generate_mirror_circuit(nlayers, two_qubit_gate_prob, connectivity_graph, two_qubit_gate_name='CNOT', seed=None, return_type=None)[source]#
- Parameters:
nlayers (
int
) – The number of random Clifford layers to be generated.two_qubit_gate_prob (
float
) – Probability of a two-qubit gate being applied.connectivity_graph (
Graph
) – The connectivity graph of the backend on which the mirror circuit will be run. This is used to make sure 2-qubit gates are only applied to connected qubits.two_qubit_gate_name (
str
) – Name of two-qubit gate to use. Options are “CNOT” and “CZ”.seed (
Optional
[int
]) – Seed for generating randomized mirror circuit.return_type (
Optional
[str
]) – String which specifies the type of the returned circuit. See the keys ofmitiq.SUPPORTED_PROGRAM_TYPES
for options. IfNone
, the returned circuit is acirq.Circuit
.
- Return type:
Tuple
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],Union
[str
,List
[int
]]]- Returns:
A randomized mirror circuit.
- mitiq.benchmarks.mirror_circuits.random_cliffords(connectivity_graph, random_state, two_qubit_gate=cirq.CNOT)[source]#
- Parameters:
connectivity_graph (
Graph
) – A graph with the edges for which the two-qubit Clifford gate is to be applied.random_state (
RandomState
) – Random state to choose Cliffords (uniformly at random).two_qubit_gate (
Gate
) – Two-qubit gate to use.
- Return type:
Circuit
- Returns:
A circuit with a two-qubit Clifford gate applied to each edge in edges, and a random single-qubit Clifford gate applied to every other qubit.
- mitiq.benchmarks.mirror_circuits.random_paulis(connectivity_graph, random_state)[source]#
Returns a circuit with randomly selected Pauli gates on each qubit.
- Parameters:
connectivity_graph (
Graph
) – Connectivity graph of device to run circuit on.random_state (
RandomState
) – Random state to select Paulis I, X, Y, Z uniformly at random.
- Return type:
Circuit
- mitiq.benchmarks.mirror_circuits.random_single_cliffords(connectivity_graph, random_state)[source]#
- Parameters:
connectivity_graph (
Graph
) – A graph with each node representing a qubit for which a random single-qubit Clifford gate is to be applied.random_state (
RandomState
) – Random state to choose Cliffords (uniformly at random).
- Return type:
Circuit
- Returns:
A circuit with a random single-qubit Clifford gate applied on each given qubit.
Randomized Benchmarking Circuits#
Functions for generating randomized benchmarking circuits.
- mitiq.benchmarks.randomized_benchmarking.generate_rb_circuits(n_qubits, num_cliffords, trials=1, return_type=None)[source]#
Returns a list of randomized benchmarking circuits, i.e. circuits that are equivalent to the identity.
- Parameters:
n_qubits (
int
) – The number of qubits. Can be either 1 or 2.num_cliffords (
int
) – The number of Clifford group elements in the random circuits. This is proportional to the depth per circuit.trials (
int
) – The number of random circuits at each num_cfd.return_type (
Optional
[str
]) – String which specifies the type of the returned circuits. See the keys ofmitiq.SUPPORTED_PROGRAM_TYPES
for options. IfNone
, the returned circuits have typecirq.Circuit
.
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]- Returns:
A list of randomized benchmarking circuits.
GHZ Circuits#
Functions for creating GHZ circuits for benchmarking purposes.
- mitiq.benchmarks.ghz_circuits.generate_ghz_circuit(n_qubits, return_type=None)[source]#
Returns a GHZ circuit ie a circuit that prepares an
n_qubits
GHZ state.- Parameters:
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]- Returns:
A GHZ circuit acting on
n_qubits
qubits.
Quantum Volume Circuits#
Functions for creating circuits of the form used in quantum volume experiments as defined in https://arxiv.org/abs/1811.12926.
Useful overview of quantum volume experiments: https://pennylane.ai/qml/demos/quantum_volume.html
Cirq implementation of quantum volume circuits: cirq-core/cirq/contrib/quantum_volume/quantum_volume.py
- mitiq.benchmarks.quantum_volume_circuits.compute_heavy_bitstrings(circuit, num_qubits)[source]#
Classically compute the heavy bitstrings of the provided circuit.
The heavy bitstrings are defined as the output bit-strings that have a greater than median probability of being generated.
- mitiq.benchmarks.quantum_volume_circuits.generate_quantum_volume_circuit(num_qubits, depth, decompose=False, seed=None, return_type=None)[source]#
Generate a quantum volume circuit with the given number of qubits and depth.
The generated circuit consists of depth layers of random qubit permutations followed by random two-qubit gates that are sampled from the Haar measure on SU(4).
- Parameters:
num_qubits (
int
) – The number of qubits in the generated circuit.depth (
int
) – The number of qubits in the generated circuit.decompose (
bool
) – Recursively decomposes the randomly sampled (numerical) unitary matrix gates into simpler gates.return_type (
Optional
[str
]) – String which specifies the type of the returned circuits. See the keys ofmitiq.SUPPORTED_PROGRAM_TYPES
for options. IfNone
, the returned circuits have typecirq.Circuit
.
- Return type:
Tuple
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],Sequence
[Union
[str
,List
[int
]]]]- Returns:
A quantum volume circuit acting on
num_qubits
qubits. A list of the heavy bitstrings for the returned circuit.
Quantum Phase Estimation Circuits#
Functions to create a QPE circuit.
- mitiq.benchmarks.qpe_circuits.generate_qpe_circuit(evalue_reg, input_gate=cirq.T, return_type=None)[source]#
Returns a circuit to create a quantum phase estimation (QPE) circuit as defined in https://en.wikipedia.org/wiki/Quantum_phase_estimation_algorithm
The unitary to estimate the phase of corresponds to a single-qubit gate (
input_gate
).The IQFT circuit defined in this method is taken from taken from Sec 7.7.4 of [53]. The notation for eigenvalue register and eigenstate register used to define this function also follows from [53].
- Parameters:
evalue_reg (
int
) – Number of qubits in the eigenvalue register. The qubits in this variable are used to estimate the phase.input_gate (
Gate
) – The unitary to estimate the phase of as a single-qubit Cirq gate. Default gate used here is cirq.T.return_type (
Optional
[str
]) – Return type of the output circuit.
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]- Returns:
A Quantum Phase Estimation circuit.
W State Circuits#
Functions for creating a linear complexity W-state benchmarking circuit as defined in [54].
- mitiq.benchmarks.w_state_circuits.generate_w_circuit(n_qubits, return_type=None)[source]#
Returns a circuit to create a
n_qubits
qubit Werner-state with linear complexity as defined in [54].- Parameters:
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]- Returns:
A W-state circuit of linear complexity acting on
n_qubits
qubits.
Circuit types and result types#
- mitiq.typing.QPROGRAM#
alias of
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]
- mitiq.typing.QuantumResult#
alias of
Union
[float
,MeasurementResult
,ndarray
]
- class mitiq.typing.MeasurementResult(result, qubit_indices=None)[source]#
Mitiq object for collecting the bitstrings sampled from a quantum computer when executing a circuit. This is one of the possible types (see
QuantumResult
) that anExecutor
can return.- Parameters:
result (
Sequence
[Union
[str
,List
[int
]]]) – The sequence of measured bitstrings.qubit_indices (
Optional
[Tuple
[int
,...
]]) – The qubit indices associated to each bit in a bitstring (from left to right). If not given, Mitiq assumes the default orderingtuple(range(self.nqubits))
, whereself.nqubits
is the bitstring length deduced fromresult
.
Note
Use caution when selecting the default option for
qubit_indices
, especially when estimating anObservable
acting on a subset of qubits. In this case Mitiq only applies measurement gates to the specific qubits and, therefore, it is essential to specify the correspondingqubit_indices
.- classmethod from_counts(counts, qubit_indices=None)[source]#
Initializes a
MeasurementResult
from a dictionary of counts.Example:
MeasurementResult.from_counts({"00": 175, "11": 177})
- classmethod from_dict(data)[source]#
Loads a
MeasurementResult
from a Python dictionary.Note: Only
data["counts"]
anddata["qubit_indices"]
are used by this method. Total shots and number of qubits are deduced.- Parameters:
- Return type:
- get_counts()[source]#
Returns a Python dictionary whose keys are the measured bitstrings and whose values are the counts.
Clifford Data Regression#
Clifford Data Regression (High-Level Tools)#
API for using Clifford Data Regression (CDR) error mitigation.
- mitiq.cdr.cdr.cdr_decorator(observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#
Decorator which adds clifford data regression (CDR) mitigation to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns the CDR estimate of the ideal expectation value associated to the input circuit.
- Parameters:
executor – Executes a circuit and returns a QuantumResult.
observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise the QuantumResult returned by executor is used to compute the expectation of the observable.simulator (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – Executes a circuit without noise and returns a QuantumResult. For CDR to be efficient, the simulator must be able to efficiently simulate near-Clifford circuits.num_training_circuits (
int
) – Number of training circuits to be used in the mitigation.fraction_non_clifford (
float
) – The fraction of non-Clifford gates to be substituted in the training circuits.fit_function (
Callable
[...
,float
]) – The function to map noisy to exact data. Takes array of noisy and data and parameters returning a float. Seecdr.linear_fit_function
for an example.num_fit_parameters (
Optional
[int
]) – The number of parameters the fit_function takes.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – scale_noise: Function for scaling the noise of a quantum circuit.scale_factors (
Sequence
[float
]) – Factors by which to scale the noise. - When 1.0 is the only scale factor, the method is known as CDR. - Note: When scale factors larger than 1.0 are provided, the method is known as “variable-noise CDR.”kwargs (
Any
) – Available keyword arguments are: - method_select (string): Specifies the method used to select the non-Clifford gates to replace when constructing the near-Clifford training circuits. Can be ‘uniform’ or ‘gaussian’. - method_replace (string): Specifies the method used to replace the selected non-Clifford gates with a Clifford when constructing the near-Clifford training circuits. Can be ‘uniform’, ‘gaussian’, or ‘closest’. - sigma_select (float): Width of the Gaussian distribution used formethod_select='gaussian'
. - sigma_replace (float): Width of the Gaussian distribution used formethod_replace='gaussian'
. - random_state (int): Seed for sampling.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Any
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Any
]],float
]]
- mitiq.cdr.cdr.execute_with_cdr(circuit, executor, observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#
Function for the calculation of an observable from some circuit of interest to be mitigated with CDR (or vnCDR) based on Ref. [15] and Ref. [2].
The circuit of interest must be compiled in the native basis of the IBM quantum computers, that is {Rz, sqrt(X), CNOT}, or such that all the non-Clifford gates are contained in the Rz rotations.
The observable/s to be calculated should be input as an array or a list of arrays representing the diagonal of the observables to be measured. Note these observables MUST be diagonal in z-basis measurements corresponding to the circuit of interest.
Returns mitigated observables list of raw observables (at noise scale factors).
This function returns the mitigated observable/s.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – Quantum program to execute with error mitigation.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – Executes a circuit and returns a QuantumResult.observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise the QuantumResult returned by executor is used to compute the expectation of the observable.simulator (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – Executes a circuit without noise and returns a QuantumResult. For CDR to be efficient, the simulator must be able to efficiently simulate near-Clifford circuits.num_training_circuits (
int
) – Number of training circuits to be used in the mitigation.fraction_non_clifford (
float
) – The fraction of non-Clifford gates to be substituted in the training circuits.fit_function (
Callable
[...
,float
]) – The function to map noisy to exact data. Takes array of noisy and data and parameters returning a float. Seecdr.linear_fit_function
for an example.num_fit_parameters (
Optional
[int
]) – The number of parameters the fit_function takes.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – scale_noise: Function for scaling the noise of a quantum circuit.scale_factors (
Sequence
[float
]) – Factors by which to scale the noise. - When 1.0 is the only scale factor, the method is known as CDR. - Note: When scale factors larger than 1.0 are provided, the method is known as “variable-noise CDR.”kwargs (
Any
) – Available keyword arguments are: - method_select (string): Specifies the method used to select the non-Clifford gates to replace when constructing the near-Clifford training circuits. Can be ‘uniform’ or ‘gaussian’. - method_replace (string): Specifies the method used to replace the selected non-Clifford gates with a Clifford when constructing the near-Clifford training circuits. Can be ‘uniform’, ‘gaussian’, or ‘closest’. - sigma_select (float): Width of the Gaussian distribution used formethod_select='gaussian'
. - sigma_replace (float): Width of the Gaussian distribution used formethod_replace='gaussian'
. - random_state (int): Seed for sampling.
- Return type:
- mitiq.cdr.cdr.mitigate_executor(executor, observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#
Returns a clifford data regression (CDR) mitigated version of the input ‘executor’.
The input executor executes a circuit with an arbitrary backend and produces an expectation value (without any error mitigation). The returned executor executes the circuit with the same backend but uses clifford data regression to produce the CDR estimate of the ideal expectation value associated to the input circuit.
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]) – Executes a circuit and returns a QuantumResult.observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise the QuantumResult returned by executor is used to compute the expectation of the observable.simulator (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – Executes a circuit without noise and returns a QuantumResult. For CDR to be efficient, the simulator must be able to efficiently simulate near-Clifford circuits.num_training_circuits (
int
) – Number of training circuits to be used in the mitigation.fraction_non_clifford (
float
) – The fraction of non-Clifford gates to be substituted in the training circuits.fit_function (
Callable
[...
,float
]) – The function to map noisy to exact data. Takes array of noisy and data and parameters returning a float. Seecdr.linear_fit_function
for an example.num_fit_parameters (
Optional
[int
]) – The number of parameters the fit_function takes.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – scale_noise: Function for scaling the noise of a quantum circuit.scale_factors (
Sequence
[float
]) – Factors by which to scale the noise. - When 1.0 is the only scale factor, the method is known as CDR. - Note: When scale factors larger than 1.0 are provided, the method is known as “variable-noise CDR.”kwargs (
Any
) – Available keyword arguments are: - method_select (string): Specifies the method used to select the non-Clifford gates to replace when constructing the near-Clifford training circuits. Can be ‘uniform’ or ‘gaussian’. - method_replace (string): Specifies the method used to replace the selected non-Clifford gates with a Clifford when constructing the near-Clifford training circuits. Can be ‘uniform’, ‘gaussian’, or ‘closest’. - sigma_select (float): Width of the Gaussian distribution used formethod_select='gaussian'
. - sigma_replace (float): Width of the Gaussian distribution used formethod_replace='gaussian'
. - random_state (int): Seed for sampling.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],float
]
Clifford Training Data#
Functions for mapping circuits to (near) Clifford circuits.
- mitiq.cdr.clifford_training_data.generate_training_circuits(circuit, num_training_circuits, fraction_non_clifford, method_select='uniform', method_replace='closest', random_state=None, **kwargs)[source]#
Returns a list of (near) Clifford circuits obtained by replacing (some) non-Clifford gates in the input circuit by Clifford gates. The way in which non-Clifford gates are selected to be replaced is determined by
method_select
andmethod_replace
. In the Clifford Data Regression (CDR) method [15], data generated from these circuits is used as a training set to learn the effect of noise.- Parameters:
circuit (
Circuit
) – A circuit of interest assumed to be compiled into the gate set {Rz, sqrt(X), CNOT}, or such that all the non-Clifford gates are contained in the Rz rotations.num_training_circuits (
int
) – Number of circuits in the returned training set.fraction_non_clifford (
float
) – The (approximate) fraction of non-Clifford gates in each returned circuit.method_select (
str
) – Method by which non-Clifford gates are selected to be replaced by Clifford gates. Options are ‘uniform’ or ‘gaussian’.method_replace (
str
) – Method by which selected non-Clifford gates are replaced by Clifford gates. Options are ‘uniform’, ‘gaussian’ or ‘closest’.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling.kwargs (
Any
) – Available keyword arguments are: - sigma_select (float): Width of the Gaussian distribution used formethod_select='gaussian'
. - sigma_replace (float): Width of the Gaussian distribution used formethod_replace='gaussian'
.
- Return type:
List
[Circuit
]
Data Regression#
The data regression portion of Clifford data regression.
- mitiq.cdr.data_regression.linear_fit_function(x_data, params)[source]#
Returns y(x) = a_1 x_1 + … + a_n x_n + b.
- Parameters:
- Return type:
- mitiq.cdr.data_regression.linear_fit_function_no_intercept(x_data, params)[source]#
Returns y(x) = a_1 x_1 + … + a_n x_n.
See Ref. :cite:Czarnik_2021_Quantum
for more details on these methods.
Mitiq - Braket#
Conversions#
- mitiq.interface.mitiq_braket.conversions.from_braket(circuit)[source]#
Returns a Cirq circuit equivalent to the input Braket circuit.
Note: The returned Cirq circuit acts on cirq.LineQubit’s with indices equal to the qubit indices of the Braket circuit.
- Parameters:
circuit (
Circuit
) – Braket circuit to convert to a Cirq circuit.- Return type:
Circuit
Mitiq - Cirq#
Cirq Utils#
Cirq utility functions.
- mitiq.interface.mitiq_cirq.cirq_utils.compute_density_matrix(circuit, noise_model=<function amplitude_damp>, noise_level=(0.01, ))[source]#
Returns the density matrix of the quantum state after the (noisy) execution of the input circuit.
- Parameters:
- Return type:
- Returns:
The final density matrix as a NumPy array.
- mitiq.interface.mitiq_cirq.cirq_utils.execute_with_depolarizing_noise(circuit, obs, noise)[source]#
Simulates a circuit with depolarizing noise and returns the expectation value of the input observable. The expectation value is deterministically computed from the final density matrix and, therefore, shot noise is absent.
- mitiq.interface.mitiq_cirq.cirq_utils.sample_bitstrings(circuit, noise_model=<function amplitude_damp>, noise_level=(0.01, ), sampler=<cirq.sim.density_matrix_simulator.DensityMatrixSimulator object>, shots=8192)[source]#
Adds noise to the input circuit. The noise is added based on a particular noise model and some value for the error rate.
- Parameters:
circuit (
Circuit
) – The input Cirq circuit.noise_model (
Union
[None
,NoiseModel
,Gate
]) – Input Cirq noise model. Default is amplitude damping.noise_level (
Tuple
[float
]) – Noise rate as a tuple of floats.sampler (
Sampler
) – Cirq simulator from which the result will be sampled from.shots (
int
) – Number of measurements.
- Return type:
- Returns:
Sampled outcome from a measurement.
Mitiq - PyQuil#
Conversions#
Functions to convert between Mitiq’s internal circuit representation and pyQuil’s circuit representation (Quil programs).
- mitiq.interface.mitiq_pyquil.conversions.from_pyquil(program)[source]#
Returns a Mitiq circuit equivalent to the input pyQuil Program.
- Parameters:
program (
Program
) – PyQuil Program to convert to a Mitiq circuit.- Return type:
Circuit
- Returns:
Mitiq circuit representation equivalent to the input pyQuil Program.
- mitiq.interface.mitiq_pyquil.conversions.from_quil(quil)[source]#
Returns a Mitiq circuit equivalent to the input Quil string.
- Parameters:
quil (
str
) – Quil string to convert to a Mitiq circuit.- Return type:
Circuit
- Returns:
Mitiq circuit representation equivalent to the input Quil string.
- mitiq.interface.mitiq_pyquil.conversions.to_pyquil(circuit)[source]#
Returns a pyQuil Program equivalent to the input Mitiq circuit.
- Parameters:
circuit (
Circuit
) – Mitiq circuit to convert to a pyQuil Program.- Return type:
Program
- Returns:
pyquil.Program object equivalent to the input Mitiq circuit.
Mitiq - Qiskit#
Conversions#
Functions to convert between Mitiq’s internal circuit representation and Qiskit’s circuit representation.
- mitiq.interface.mitiq_qiskit.conversions.from_qasm(qasm)[source]#
Returns a Mitiq circuit equivalent to the input QASM string.
- Parameters:
qasm (
str
) – QASM string to convert to a Mitiq circuit.- Return type:
Circuit
- Returns:
Mitiq circuit representation equivalent to the input QASM string.
- mitiq.interface.mitiq_qiskit.conversions.from_qiskit(circuit)[source]#
Returns a Mitiq circuit equivalent to the input Qiskit circuit.
- Parameters:
circuit (
QuantumCircuit
) – Qiskit circuit to convert to a Mitiq circuit.- Return type:
Circuit
- Returns:
Mitiq circuit representation equivalent to the input Qiskit circuit.
- mitiq.interface.mitiq_qiskit.conversions.to_qasm(circuit)[source]#
Returns a QASM string representing the input Mitiq circuit.
- Parameters:
circuit (
Circuit
) – Mitiq circuit to convert to a QASM string.- Returns:
QASM string equivalent to the input Mitiq circuit.
- Return type:
QASMType
- mitiq.interface.mitiq_qiskit.conversions.to_qiskit(circuit)[source]#
Returns a Qiskit circuit equivalent to the input Mitiq circuit. Note that the output circuit registers may not match the input circuit registers.
- Parameters:
circuit (
Circuit
) – Mitiq circuit to convert to a Qiskit circuit.- Return type:
- Returns:
Qiskit.QuantumCircuit object equivalent to the input Mitiq circuit.
Qiskit Utils#
Qiskit utility functions.
- mitiq.interface.mitiq_qiskit.qiskit_utils.compute_expectation_value_on_noisy_backend(circuit, obs, backend=None, noise_model=None, shots=10000, measure_all=False, qubit_indices=None)[source]#
Returns the noisy expectation value of the input Mitiq observable obtained from executing the input circuit on a Qiskit backend.
- Parameters:
circuit (
QuantumCircuit
) – The input Qiskit circuit.obs (
Observable
) – The Mitiq observable to compute the expectation value of.backend (
Optional
[Backend
]) – A real or fake Qiskit backend. The input circuit should be transpiled into a compatible gate set.noise_model (
Optional
[NoiseModel
]) – A valid QiskitNoiseModel
object. This option is used if and only ifbackend
isNone
. In this case a default density matrix simulator is used withoptimization_level=0
.shots (
int
) – The number of measurements.measure_all (
bool
) – If True, measurement gates are applied to all qubits.qubit_indices (
Optional
[Tuple
[int
]]) – Optional qubit indices associated to bitstrings.
- Return type:
- Returns:
The noisy expectation value.
- mitiq.interface.mitiq_qiskit.qiskit_utils.execute(circuit, obs)[source]#
Simulates a noiseless evolution and returns the expectation value of some observable.
- Parameters:
circuit (
QuantumCircuit
) – The input Qiskit circuit.obs (
ndarray
[Any
,dtype
[complex64
]]) – The observable to measure as a NumPy array.
- Return type:
- Returns:
The expectation value of obs as a float.
- mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_noise(circuit, obs, noise_model)[source]#
Simulates the evolution of the noisy circuit and returns the exact expectation value of the observable.
- Parameters:
circuit (
QuantumCircuit
) – The input Qiskit circuit.obs (
ndarray
[Any
,dtype
[complex64
]]) – The observable to measure as a NumPy array.noise_model (
NoiseModel
) – The input Qiskit noise model.
- Return type:
- Returns:
The expectation value of obs as a float.
- mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_shots(circuit, obs, shots)[source]#
Simulates the evolution of the circuit and returns the expectation value of the observable.
- mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_shots_and_noise(circuit, obs, noise_model, shots, seed=None)[source]#
Simulates the evolution of the noisy circuit and returns the statistical estimate of the expectation value of the observable.
- Parameters:
circuit (
QuantumCircuit
) – The input Qiskit circuit.obs (
ndarray
[Any
,dtype
[complex64
]]) – The observable to measure as a NumPy array.noise – The input Qiskit noise model.
shots (
int
) – The number of measurements.noise_model (
NoiseModel
) –
- Return type:
- Returns:
The expectation value of obs as a float.
- mitiq.interface.mitiq_qiskit.qiskit_utils.initialized_depolarizing_noise(noise_level)[source]#
Initializes a depolarizing noise Qiskit NoiseModel.
- Parameters:
noise_level (
float
) – The noise strength as a float, e.g., 0.01 is 0.1%.- Return type:
NoiseModel
- Returns:
A Qiskit depolarizing NoiseModel.
- mitiq.interface.mitiq_qiskit.qiskit_utils.sample_bitstrings(circuit, backend=None, noise_model=None, shots=10000, measure_all=False, qubit_indices=None)[source]#
Returns measurement bitstrings obtained from executing the input circuit on a Qiskit backend (passed as an argument). Note that the input circuit must contain measurement gates (unless
measure_all
isTrue
).- Parameters:
circuit (
QuantumCircuit
) – The input Qiskit circuit.backend (
Optional
[Backend
]) – A real or fake Qiskit backend. The input circuit should be transpiled into a compatible gate set. It may be necessary to setoptimization_level=0
when transpiling.noise_model (
Optional
[NoiseModel
]) – A valid QiskitNoiseModel
object. This option is used if and only ifbackend
isNone
. In this case a default density matrix simulator is used withoptimization_level=0
.shots (
int
) – The number of measurements.measure_all (
bool
) – If True, measurement gates are applied to all qubits.qubit_indices (
Optional
[Tuple
[int
]]) – Optional qubit indices associated to bitstrings.
- Return type:
- Returns:
The measured bitstrings casted as a Mitiq
MeasurementResult
object.
Digital Dynamical Decoupling#
Digital Dynamical Decoupling (High-Level Tools)#
High-level digital dynamical decoupling (DDD) tools.
- mitiq.ddd.ddd.ddd_decorator(observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#
Decorator which adds an error-mitigation layer based on digital dynamical decoupling (DDD) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a
QuantumResult
(e.g. an expectation value).- Parameters:
observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.rule (
Callable
[[int
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – A function that takes as main argument a slack length (i.e. the number of idle moments) of a slack window (i.e. a single-qubit idle window in a circuit) and returns the DDD sequence of gates to be applied in that window. Mitiq provides standard built-in rules that can be directly imported from mitiq.ddd.rules.rule_args (
Dict
[str
,Any
]) – An optional dictionary of keyword arguments for rule.num_trials (
int
) – The number of independent experiments to average over. A number larger than 1 can be useful to average over multiple applications of a rule returning non-deterministic DDD sequences.full_output (
bool
) – If False only the mitigated expectation value is returned. If True a dictionary containing all DDD data is returned too.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,Tuple
[float
,Dict
[str
,Any
]]]]]- Returns:
The error-mitigating decorator to be applied to an executor function.
- mitiq.ddd.ddd.execute_with_ddd(circuit, executor, observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#
Estimates the error-mitigated expectation value associated to the input circuit, via the application of digital dynamical decoupling (DDD).
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The input circuit to execute with DDD.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – A Mitiq executor that executes a circuit and returns the unmitigatedQuantumResult
(e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, theexecutor
must return an expectation value. Otherwise, theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.rule (
Callable
[[int
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – A function that takes as main argument a slack length (i.e. the number of idle moments) of a slack window (i.e. a single-qubit idle window in a circuit) and returns the DDD sequence of gates to be applied in that window. Mitiq provides standard built-in rules that can be directly imported frommitiq.ddd.rules
.rule_args (
Dict
[str
,Any
]) – An optional dictionary of keyword arguments forrule
.num_trials (
int
) – The number of independent experiments to average over. A number larger than 1 can be useful to average over multiple applications of a rule returning non-deterministic DDD sequences.full_output (
bool
) – IfFalse
only the mitigated expectation value is returned. IfTrue
a dictionary containing all DDD data is returned too.
- Return type:
- Returns:
The tuple
(ddd_value, ddd_data)
whereddd_value
is the expectation value estimated with DDD andddd_data
is a dictionary containing all the raw data involved in the DDD process (e.g. the circuit filled with DDD sequences). Iffull_output
is false, onlyddd_value
is returned.
- mitiq.ddd.ddd.mitigate_executor(executor, observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#
Returns a modified version of the input ‘executor’ which is error-mitigated with digital dynamical decoupling (DDD).
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]) – A function that executes a circuit and returns the unmitigated QuantumResult (e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.rule (
Callable
[[int
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – A function that takes as main argument a slack length (i.e. the number of idle moments) of a slack window (i.e. a single-qubit idle window in a circuit) and returns the DDD sequence of gates to be applied in that window. Mitiq provides standard built-in rules that can be directly imported from mitiq.ddd.rules.rule_args (
Dict
[str
,Any
]) – An optional dictionary of keyword arguments for rule.num_trials (
int
) – The number of independent experiments to average over. A number larger than 1 can be useful to average over multiple applications of a rule returning non-deterministic DDD sequences.full_output (
bool
) – If False only the mitigated expectation value is returned. If True a dictionary containing all DDD data is returned too.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,Tuple
[float
,Dict
[str
,Any
]]]]- Returns:
The error-mitigated version of the input executor.
Insertion#
Tools to determine slack windows in circuits and to insert DDD sequences.
- mitiq.ddd.insertion.get_slack_matrix_from_circuit_mask(mask)[source]#
Given a circuit mask matrix \(A\), e.g., the output of
_get_circuit_mask()
, returns a slack matrix \(B\), where \(B_{i,j} = t\) if the position \(A_{i,j}\) is the initial element of a sequence of \(t\) zeros (from left to right).
- mitiq.ddd.insertion.insert_ddd_sequences(circuit, rule)[source]#
Returns the circuit with DDD sequences applied according to the input rule.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The QPROGRAM circuit to be modified with DDD sequences.rule (
Callable
[[int
],Circuit
]) – The rule determining what DDD sequences should be applied. A set of built-in DDD rules can be imported frommitiq.ddd.rules
.
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]- Returns:
The circuit with DDD sequences added.
Rules#
Built-in rules determining what DDD sequence should be applied in a given slack window.
- mitiq.ddd.rules.rules.general_rule(slack_length, gates, spacing=-1)[source]#
Returns a digital dynamical decoupling sequence, based on inputs.
- Parameters:
slack_length (
int
) – Length of idle window to fill.spacing (
int
) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8, gates = [X, X] the spacing defaults to 2 and the rule returns the sequence: ──I──I──X──I──I──X──I──I── given slack_length = 9, gates [X, Y, X, Y] the spacing defaults to 1 and the rule returns the sequence: ──I──X──I──Y──I──X──I──Y──I──.gates (
List
[Gate
]) – A list of single qubit Cirq gates to build the rule. E.g. [X, X] is the xx sequence, [X, Y, X, Y] is the xyxy sequence. - Note: To repeat the sequence, specify a repeated gateset.
- Return type:
Circuit
- Returns:
A digital dynamical decoupling sequence, as a Cirq circuit.
- mitiq.ddd.rules.rules.repeated_rule(slack_length, gates)[source]#
Returns a general digital dynamical decoupling sequence that repeats until the slack is filled without spacing, up to a complete repetition.
- Parameters:
- Return type:
Circuit
- Returns:
A repeated digital dynamical decoupling sequence, as a Cirq circuit.
Note
Where
general_rule()
fills a slack window with a single sequence, this rule attempts to fill every moment with sequence repetitions (up to a complete repetition of the gate set). E.g. given slack_length = 8 and gates = [X, Y, X, Y], this rule returns the sequence: ──X──Y──X──Y──X──Y──X──Y──.
- mitiq.ddd.rules.rules.xx(slack_length, spacing=-1)[source]#
Returns an XX digital dynamical decoupling sequence, based on inputs.
- Parameters:
slack_length (
int
) – Length of idle window to fill.spacing (
int
) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8 the spacing defaults to 2 and this rule returns the sequence: ──I──I──X──I──I──X──I──I──.
- Return type:
Circuit
- Returns:
An XX digital dynamical decoupling sequence, as a Cirq circuit.
- mitiq.ddd.rules.rules.xyxy(slack_length, spacing=-1)[source]#
Returns an XYXY digital dynamical decoupling sequence, based on inputs.
- Parameters:
slack_length (
int
) – Length of idle window to fill.spacing (
int
) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 9 the spacing defaults to 1 and this rule returns the sequence: ──I──X──I──Y──I──X──I──Y──I──.
- Return type:
Circuit
- Returns:
An XYXY digital dynamical decoupling sequence, as a Cirq circuit.
- mitiq.ddd.rules.rules.yy(slack_length, spacing=-1)[source]#
Returns a YY digital dynamical decoupling sequence, based on inputs.
- Parameters:
slack_length (
int
) – Length of idle window to fill.spacing (
int
) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8 the spacing defaults to 2 and this rule returns the sequence: ──I──I──Y──I──I──Y──I──I──.
- Return type:
Circuit
- Returns:
An YY digital dynamical decoupling sequence, as a Cirq circuit.
Executors#
Defines utilities for efficiently running collections of circuits generated by error mitigation techniques to compute expectation values.
- class mitiq.executor.executor.Executor(executor, max_batch_size=75)[source]#
Tool for efficiently scheduling/executing quantum programs and storing the results.
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]]],Any
]) –max_batch_size (
int
) –
- evaluate(circuits, observable=None, force_run_all=True, **kwargs)[source]#
Returns the expectation value Tr[ρ O] for each circuit in
circuits
where O is the observable provided or implicitly defined by theexecutor
. (The observable is implicitly defined when theexecutor
returns float(s).)All executed circuits are stored in
self.executed_circuits
, and all quantum results are stored inself.quantum_results
.- Parameters:
circuits (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]]) – A single circuit of list of circuits.observable (
Optional
[Observable
]) –- Observable O in the expression Tr[ρ O]. If None,
the
executor
must return a float (which corresponds to Tr[ρ O] for a specific, fixed observable O).- force_run_all: If True, force every circuit in the input sequence
to be executed (if some are identical). Else, detects identical circuits and runs a minimal set.
force_run_all (
bool
) –kwargs (
Any
) –
- Return type:
- Returns:
List of real valued expectation values.
- static is_batched_executor(executor)[source]#
Returns True if the input function is recognized as a “batched executor”, else False.
The executor is detected as “batched” if and only if it is annotated with a return type that is one of the following:
Iterable[QuantumResult]
List[QuantumResult]
Sequence[QuantumResult]
Tuple[QuantumResult]
Otherwise, it is considered “serial”.
Batched executors can _run several quantum programs in a single call. See below.
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]]],Any
]) –A “serial executor” (1) or a “batched executor” (2).
A function which inputs a single
QPROGRAM
and outputs a singleQuantumResult
.A function which inputs a list of
QPROGRAM
objects and returns a list ofQuantumResult
instances (one for eachQPROGRAM
).
- Return type:
- Returns:
True if the executor is detected as batched, else False.
- run(circuits, force_run_all=True, **kwargs)[source]#
Runs all input circuits using the least number of possible calls to the executor.
- Parameters:
circuits (
Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Sequence of circuits to execute using the executor.force_run_all (
bool
) – If True, force every circuit in the input sequence to be executed (if some are identical). Else, detects identical circuits and runs a minimal set.kwargs (
Any
) –
- Return type:
Observables#
Observable#
- class mitiq.observable.observable.Observable(*paulis)[source]#
A quantum observable typically used to compute its mitigated expectation value.
- Parameters:
paulis (
PauliString
) –
Pauli#
- class mitiq.observable.pauli.PauliString(spec='', coeff=1.0, support=None)[source]#
A PauliString is a (tensor) product of single-qubit Pauli gates I, X, Y, and Z, with a leading (real or complex) coefficient. PauliString`s can be measured in any `mitiq.QPROGRAM.
- can_be_measured_with(other)[source]#
Returns True if the expectation value of the PauliString can be simultaneously estimated with other via single-qubit measurements.
- Parameters:
other (
PauliString
) – The PauliString to check simultaneous measurement with.- Return type:
- class mitiq.observable.pauli.PauliStringCollection(*paulis, check_precondition=True)[source]#
A collection of PauliStrings that qubit-wise commute and so can be measured with a single circuit.
- Parameters:
paulis (
PauliString
) –check_precondition (
bool
) –
Probabilistic Error Cancellation#
Probabilistic Error Cancellation (High-Level Tools)#
High-level probabilistic error cancellation tools.
- exception mitiq.pec.pec.LargeSampleWarning[source]#
Warning is raised when PEC sample size is greater than 10 ** 5
- mitiq.pec.pec.execute_with_pec(circuit, executor, observable=None, *, representations, precision=0.03, num_samples=None, force_run_all=True, random_state=None, full_output=False)[source]#
Estimates the error-mitigated expectation value associated to the input circuit, via the application of probabilistic error cancellation (PEC). [5] [38].
This function implements PEC by:
Sampling different implementable circuits from the quasi-probability representation of the input circuit;
Evaluating the noisy expectation values associated to the sampled circuits (through the “executor” function provided by the user);
Estimating the ideal expectation value from a suitable linear combination of the noisy ones.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The input circuit to execute with error-mitigation.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – A Mitiq executor that executes a circuit and returns the unmitigatedQuantumResult
(e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.representations (
Sequence
[OperationRepresentation
]) – Representations (basis expansions) of each operation in the input circuit.precision (
float
) – The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where ‘one_norm’ is related to the negativity of the quasi-probability representation [5]. If ‘num_samples’ is explicitly set by the user, ‘precision’ is ignored and has no effect.num_samples (
Optional
[int
]) – The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument ‘precision’.force_run_all (
bool
) – If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling circuits.full_output (
bool
) – If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too.
- Return type:
- Returns:
The tuple
(pec_value, pec_data)
wherepec_value
is the expectation value estimated with PEC andpec_data
is a dictionary which contains all the raw data involved in the PEC process (including the PEC estimation error). The error is estimated aspec_std / sqrt(num_samples)
, wherepec_std
is the standard deviation of the PEC samples, i.e., the square root of the mean squared deviation of the sampled values frompec_value
. Iffull_output
isTrue
, onlypec_value
is returned.
- mitiq.pec.pec.mitigate_executor(executor, observable=None, *, representations, precision=0.03, num_samples=None, force_run_all=True, random_state=None, full_output=False)[source]#
Returns a modified version of the input ‘executor’ which is error-mitigated with probabilistic error cancellation (PEC).
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]) – A function that executes a circuit and returns the unmitigated QuantumResult (e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.representations (
Sequence
[OperationRepresentation
]) – Representations (basis expansions) of each operation in the input circuit.precision (
float
) – The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where ‘one_norm’ is related to the negativity of the quasi-probability representation [5]. If ‘num_samples’ is explicitly set, ‘precision’ is ignored and has no effect.num_samples (
Optional
[int
]) – The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument ‘precision’.force_run_all (
bool
) – If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling circuits.full_output (
bool
) – If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,Tuple
[float
,Dict
[str
,Any
]]]]- Returns:
The error-mitigated version of the input executor.
- mitiq.pec.pec.pec_decorator(observable=None, *, representations, precision=0.03, num_samples=None, force_run_all=True, random_state=None, full_output=False)[source]#
Decorator which adds an error-mitigation layer based on probabilistic error cancellation (PEC) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a
QuantumResult
(e.g. an expectation value).- Parameters:
observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor function being decorated must return an expectation value. Otherwise, the QuantumResult returned by this executor is used to compute the expectation of the observable.representations (
Sequence
[OperationRepresentation
]) – Representations (basis expansions) of each operation in the input circuit.precision (
float
) – The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where ‘one_norm’ is related to the negativity of the quasi-probability representation [5]. If ‘num_samples’ is explicitly set by the user, ‘precision’ is ignored and has no effect.num_samples (
Optional
[int
]) – The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument ‘precision’.force_run_all (
bool
) – If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling circuits.full_output (
bool
) – If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,Tuple
[float
,Dict
[str
,Any
]]]]]- Returns:
The error-mitigating decorator to be applied to an executor function.
Quasi-Probability Representations#
Functions for finding optimal representations given a noisy basis.
- mitiq.pec.representations.optimal.find_optimal_representation(ideal_operation, noisy_operations, tol=1e-08, initial_guess=None)[source]#
Returns the
OperationRepresentation
of the input ideal operation which minimizes the one-norm of the associated quasi-probability distribution.More precisely, it solve the following optimization problem:
\[\min_{\eta_\alpha} \left\{\sum_\alpha |\eta_\alpha| \, : \, \mathcal G = \sum_\alpha \eta_\alpha \mathcal O_\alpha \right\}\]where \(\{\mathcal O_j\}\) is the input basis of noisy operations, and \(\mathcal{G}\) is the ideal operation to be represented.
- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal operation to represent.noisy_operations (
List
[NoisyOperation
]) – The basis in which theideal_operation
should be represented. Must be a list ofNoisyOperation
objects which are initialized with a numerical superoperator matrix.tol (
float
) – The error tolerance for each matrix element of the represented operation.initial_guess (
Optional
[ndarray
[Any
,dtype
[float64
]]]) – Optional initial guess for the coefficients \(\{ \eta_\alpha \}\).
Returns: The optimal OperationRepresentation.
- Return type:
- mitiq.pec.representations.optimal.minimize_one_norm(ideal_matrix, basis_matrices, tol=1e-08, initial_guess=None)[source]#
Returns the list of real coefficients \([x_0, x_1, \dots]\), which minimizes \(\sum_j |x_j|\) with the contraint that the following representation of the input
ideal_matrix
holds:\[\text{ideal_matrix} = x_0 A_0 + x_1 A_1 + \cdots\]where \(\{A_j\}\) are the basis matrices, i.e., the elements of the input
basis_matrices
.This function can be used to compute the optimal representation of an ideal superoperator (or Choi state) as a linear combination of real noisy superoperators (or Choi states).
- Parameters:
ideal_matrix (
ndarray
[Any
,dtype
[complex64
]]) – The ideal matrix to represent.basis_matrices (
List
[ndarray
[Any
,dtype
[complex64
]]]) – The list of basis matrices.tol (
float
) – The error tolerance for each matrix element of the represented matrix.initial_guess (
Optional
[ndarray
[Any
,dtype
[float64
]]]) – Optional initial guess for the coefficients \([x_0, x_1, \dots]\).
- Return type:
- Returns:
The list of optimal coefficients \([x_0, x_1, \dots]\).
Functions related to representations with amplitude damping noise.
- mitiq.pec.representations.damping.amplitude_damping_kraus(noise_level, num_qubits)[source]#
Returns the Kraus operators of the tensor product of local depolarizing channels acting on each qubit.
Functions related to representations with depolarizing noise.
- mitiq.pec.representations.depolarizing.global_depolarizing_kraus(noise_level, num_qubits)[source]#
Returns the kraus operators of a global depolarizing channel at a given noise level.
- mitiq.pec.representations.depolarizing.local_depolarizing_kraus(noise_level, num_qubits)[source]#
Returns the kraus operators of the tensor product of local depolarizing channels acting on each qubit.
- mitiq.pec.representations.depolarizing.represent_operation_with_global_depolarizing_noise(ideal_operation, noise_level)[source]#
As described in [5], this function maps an
ideal_operation
\(\mathcal{U}\) into its quasi-probability representation, which is a linear combination of noisy implementable operations \(\sum_\alpha \eta_{\alpha} \mathcal{O}_{\alpha}\).This function assumes a depolarizing noise model and, more precicely, that the following noisy operations are implementable \(\mathcal{O}_{\alpha} = \mathcal{D} \circ \mathcal P_\alpha \circ \mathcal{U}\), where \(\mathcal{U}\) is the unitary associated to the input
ideal_operation
acting on \(k\) qubits, \(\mathcal{P}_\alpha\) is a Pauli operation and \(\mathcal{D}(\rho) = (1 - \epsilon) \rho + \epsilon I/2^k\) is a depolarizing channel (\(\epsilon\) is a simple function ofnoise_level
).For a single-qubit
ideal_operation
, the representation is as follows:\[\mathcal{U}_{\beta} = \eta_1 \mathcal{O}_1 + \eta_2 \mathcal{O}_2 + \eta_3 \mathcal{O}_3 + \eta_4 \mathcal{O}_4\]\[ \begin{align}\begin{aligned}\eta_1 =1 + \frac{3}{4} \frac{\epsilon}{1- \epsilon}, \qquad \mathcal{O}_1 = \mathcal{D} \circ \mathcal{I} \circ \mathcal{U}\\\eta_2 =- \frac{1}{4}\frac{\epsilon}{1- \epsilon} , \qquad \mathcal{O}_2 = \mathcal{D} \circ \mathcal{X} \circ \mathcal{U}\\\eta_3 =- \frac{1}{4}\frac{\epsilon}{1- \epsilon} , \qquad \mathcal{O}_3 = \mathcal{D} \circ \mathcal{Y} \circ \mathcal{U}\\\eta_4 =- \frac{1}{4}\frac{\epsilon}{1- \epsilon} , \qquad \mathcal{O}_4 = \mathcal{D} \circ \mathcal{Z} \circ \mathcal{U}\end{aligned}\end{align} \]It was proven in [11] that, under suitable assumptions, this representation is optimal (minimum 1-norm).
- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal operation (as a QPROGRAM) to represent.noise_level (
float
) – The noise level (as a float) of the depolarizing channel.
- Return type:
- Returns:
The quasi-probability representation of the
ideal_operation
.
Note
This representation is based on the ideal assumption that one can append Pauli gates to a noisy operation without introducing additional noise. For a backend which violates this assumption, it remains a good approximation for small values of
noise_level
.Note
The input
ideal_operation
is typically a QPROGRAM with a single gate but could also correspond to a sequence of more gates. This is possible as long as the unitary associated to the input QPROGRAM, followed by a single final depolarizing channel, is physically implementable.
- mitiq.pec.representations.depolarizing.represent_operation_with_local_depolarizing_noise(ideal_operation, noise_level)[source]#
As described in [5], this function maps an
ideal_operation
\(\mathcal{U}\) into its quasi-probability representation, which is a linear combination of noisy implementable operations \(\sum_\alpha \eta_{\alpha} \mathcal{O}_{\alpha}\).This function assumes a (local) single-qubit depolarizing noise model even for multi-qubit operations. More precicely, it assumes that the following noisy operations are implementable \(\mathcal{O}_{\alpha} = \mathcal{D}^{\otimes k} \circ \mathcal P_\alpha \circ \mathcal{U}\), where \(\mathcal{U}\) is the unitary associated to the input
ideal_operation
acting on \(k\) qubits, \(\mathcal{P}_\alpha\) is a Pauli operation and \(\mathcal{D}(\rho) = (1 - \epsilon) \rho + \epsilon I/2\) is a single-qubit depolarizing channel (\(\epsilon\) is a simple function ofnoise_level
).More information about the quasi-probability representation for a depolarizing noise channel can be found in:
represent_operation_with_global_depolarizing_noise()
.- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal operation (as a QPROGRAM) to represent.noise_level (
float
) – The noise level of each depolarizing channel.
- Return type:
- Returns:
The quasi-probability representation of the
ideal_operation
.
Note
The input
ideal_operation
is typically a QPROGRAM with a single gate but could also correspond to a sequence of more gates. This is possible as long as the unitary associated to the input QPROGRAM, followed by a single final depolarizing channel, is physically implementable.
- mitiq.pec.representations.depolarizing.represent_operations_in_circuit_with_global_depolarizing_noise(ideal_circuit, noise_level)[source]#
Iterates over all unique operations of the input
ideal_circuit
and, for each of them, generates the corresponding quasi-probability representation (linear combination of implementable noisy operations).This function assumes that the same depolarizing noise channel of strength
noise_level
affects each implemented operation.This function internally calls
represent_operation_with_global_depolarizing_noise()
(more details about the quasi-probability representation can be found in its docstring).- Parameters:
ideal_circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal circuit, whose ideal operations should be represented.noise_level (
float
) – The (gate-independent) depolarizing noise level.
- Return type:
- Returns:
The list of quasi-probability representations associated to the operations of the input
ideal_circuit
.
Note
Measurement gates are ignored (not represented).
Note
The returned representations are always defined in terms of Cirq circuits, even if the input is not a
cirq.Circuit
.
- mitiq.pec.representations.depolarizing.represent_operations_in_circuit_with_local_depolarizing_noise(ideal_circuit, noise_level)[source]#
Iterates over all unique operations of the input
ideal_circuit
and, for each of them, generates the corresponding quasi-probability representation (linear combination of implementable noisy operations).This function assumes that the tensor product of
k
single-qubit depolarizing channels affects each implemented operation, wherek
is the number of qubits associated to the operation.This function internally calls
represent_operation_with_local_depolarizing_noise()
(more details about the quasi-probability representation can be found in its docstring).- Parameters:
ideal_circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal circuit, whose ideal operations should be represented.noise_level (
float
) – The (gate-independent) depolarizing noise level.
- Return type:
- Returns:
The list of quasi-probability representations associated to the operations of the input
ideal_circuit
.
Note
Measurement gates are ignored (not represented).
Note
The returned representations are always defined in terms of Cirq circuits, even if the input is not a
cirq.Circuit
.
Learning-based PEC#
Function to generate representations with biased noise.
- mitiq.pec.representations.biased_noise.represent_operation_with_local_biased_noise(ideal_operation, epsilon, eta)[source]#
This function maps an
ideal_operation
\(\mathcal{U}\) into its quasi-probability representation, which is a linear combination of noisy implementable operations \(\sum_\alpha \eta_{\alpha} \mathcal{O}_{\alpha}\).This function assumes a combined depolarizing and dephasing noise model with a bias factor \(\eta\) (see [12]) and that the following noisy operations are implementable \(\mathcal{O}_{\alpha} = \mathcal{D} \circ \mathcal P_\alpha\) where \(\mathcal{U}\) is the unitary associated to the input
ideal_operation
, \(\mathcal{P}_\alpha\) is a Pauli operation and\[\mathcal{D}(\epsilon) = (1 - \epsilon)[\mathbb{1}] + \epsilon(\frac{\eta}{\eta + 1} \mathcal{Z} + \frac{1}{3}\frac{1}{\eta + 1}(\mathcal{X} + \mathcal{Y} + \mathcal{Z}))\]is the combined (biased) dephasing and depolarizing channel acting on a single qubit. For multi-qubit operations, we use a noise channel that is the tensor product of the local single-qubit channels.
- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal operation (as a QPROGRAM) to represent.epsilon (
float
) – The local noise severity (as a float) of the combined channel.eta (
float
) – The noise bias between combined dephasing and depolarizing channels with \(\eta = 0\) describing a fully depolarizing channel and \(\eta = \infty\) describing a fully dephasing channel.
- Return type:
- Returns:
The quasi-probability representation of the
ideal_operation
.
Note
This representation is based on the ideal assumption that one can append Pauli gates to a noisy operation without introducing additional noise. For a backend which violates this assumption, it remains a good approximation for small values of
epsilon
.Note
The input
ideal_operation
is typically a QPROGRAM with a single gate but could also correspond to a sequence of more gates. This is possible as long as the unitary associated to the input QPROGRAM, followed by a single final biased noise channel, is physically implementable.
Functions to calculate parameters for depolarizing noise and biased noise models via a learning-based technique.
- mitiq.pec.representations.learning.biased_noise_loss_function(params, operations_to_mitigate, training_circuits, ideal_values, noisy_executor, pec_kwargs, pec_data=None, observable=None)[source]#
Loss function for optimizing quasi-probability representations assuming a biased noise model depending on two real parameters.
- Parameters:
params (
ndarray
[Any
,dtype
[float64
]]) – Array of optimization parameters epsilon (local noise strength) and eta (noise bias between reduced dephasing and depolarizing channels).operations_to_mitigate (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – List of ideal operations to be represented by a combination of noisy operations.training_circuits (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – List of training circuits for generating the error-mitigated expectation values.ideal_values (
ndarray
[Any
,dtype
[float64
]]) – Expectation values obtained by noiseless simulations.noisy_executor (
Executor
) – Executes the circuit with noise and returns a QuantumResult.pec_kwargs (
Dict
[str
,Any
]) – Options to pass to execute_w_pec for the error-mitigated expectation value obtained from executing the training circuits.pec_data (optional) – 3-D array of error-mitigated expection values for model training.
observable (optional) – Observable to compute the expectation value of. If None, the
executor
must return an expectation value. Otherwise theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.
- Returns: Mean squared error between the error-mitigated values and
the ideal values, over the training set.
- Return type:
- mitiq.pec.representations.learning.depolarizing_noise_loss_function(epsilon, operations_to_mitigate, training_circuits, ideal_values, noisy_executor, pec_kwargs, pec_data=None, observable=None)[source]#
Loss function for optimizing quasi-probability representations assuming a depolarizing noise model depending on one real parameter.
- Parameters:
epsilon (
ndarray
[Any
,dtype
[float64
]]) – Array of optimization parameters epsilon (local noise strength) and eta (noise bias between reduced dephasing and depolarizing channels).operations_to_mitigate (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – List of ideal operations to be represented by a combination of noisy operations.training_circuits (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – List of training circuits for generating the error-mitigated expectation values.ideal_values (
ndarray
[Any
,dtype
[float64
]]) – Expectation values obtained by noiseless simulations.noisy_executor (
Executor
) – Executes the circuit with noise and returns a QuantumResult.pec_kwargs (
Dict
[str
,Any
]) – Options to pass to execute_w_pec for the error-mitigated expectation value obtained from executing the training circuits.pec_data (optional) – 2-D array of error-mitigated expection values for model training.
observable (optional) – Observable to compute the expectation value of. If None, the
executor
must return an expectation value. Otherwise theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.
- Returns: Mean squared error between the error-mitigated values and
the ideal values, over the training set.
- Return type:
- mitiq.pec.representations.learning.learn_biased_noise_parameters(operations_to_learn, circuit, ideal_executor, noisy_executor, pec_kwargs={}, num_training_circuits=5, fraction_non_clifford=0.2, training_random_state=None, epsilon0=0.05, eta0=1, observable=None, **learning_kwargs)[source]#
This function learns the biased noise parameters epsilon and eta associated to a set of input operations. The learning process is based on the execution of a set of training circuits on a noisy backend and on a classical simulator. The training circuits are near-Clifford approximations of the input circuit. A biased noise model characterization is assumed.
- Parameters:
operations_to_learn (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – The ideal operations to learn the noise model of.circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The full quantum program as defined by the user.ideal_executor (
Executor
) – Simulates a circuit and returns a noiselessQuantumResult
.noisy_executor (
Executor
) – Executes a circuit on a noisy backend and returns aQuantumResult
.pec_kwargs (optional) – Options to pass to
execute_w_pec
for the error-mitigated expectation value obtained from executing the training circuits.num_training_circuits (
int
) – Number of near-Clifford circuits to be generated for training.fraction_non_clifford (
float
) – The (approximate) fraction of non-Clifford gates in each training circuit.training_random_state (
Optional
[RandomState
]) – Seed for sampling the training circuits.epsilon0 (
float
) – Initial guess for noise strength.eta0 (
float
) – Initial guess for noise bias.observable (optional) – Observable to compute the expectation value of. If None, the
executor
must return an expectation value. Otherwise the QuantumResult returned by executor is used to compute the expectation of the observable.learning_kwargs (optional) – Additional data and options including
method
an optimization method supported byscipy.optimize.minimize
and settings for the chosen optimization method.
- Return type:
- Returns:
A 3-tuple containing a flag indicating whether or not the optimizer exited successfully, the optimized noise strength epsilon, and the optimized noise bias, eta.
Note
Using this function may require some tuning. One of the main challenges is setting a good value of
num_samples
in the PEC optionspec_kwargs
. Setting a small value ofnum_samples
is typically necessary to obtain a reasonable execution time. On the other hand, using a number of PEC samples that is too small can result in a large statistical error, ultimately causing the optimization process to fail.
- mitiq.pec.representations.learning.learn_depolarizing_noise_parameter(operations_to_learn, circuit, ideal_executor, noisy_executor, pec_kwargs={}, num_training_circuits=5, fraction_non_clifford=0.2, training_random_state=None, epsilon0=0.05, observable=None, **learning_kwargs)[source]#
This function learns the depolarizing noise parameter (epsilon) associated to a set of input operations. The learning process is based on the execution of a set of training circuits on a noisy backend and on a classical simulator. The training circuits are near-Clifford approximations of the input circuit. A depolarizing noise model characterization is assumed.
- Parameters:
operations_to_learn (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – The ideal operations to learn the noise model of.circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The full quantum program as defined by the user.ideal_executor (
Executor
) – Simulates a circuit and returns a noiselessQuantumResult
.noisy_executor (
Executor
) – Executes a circuit on a noisy backend and returns aQuantumResult
.pec_kwargs (optional) – Options to pass to
execute_w_pec
for the error-mitigated expectation value obtained from executing the training circuits.num_training_circuits (
int
) – Number of near-Clifford circuits to be generated for training.fraction_non_clifford (
float
) – The (approximate) fraction of non-Clifford gates in each training circuit.training_random_state (
Optional
[RandomState
]) – Seed for sampling the training circuits.epsilon0 (
float
) – Initial guess for noise strength.observable (optional) – Observable to compute the expectation value of. If None, the
executor
must return an expectation value. Otherwise the QuantumResult returned by executor is used to compute the expectation of the observable.learning_kwargs (optional) – Additional data and options including
method
an optimization method supported byscipy.optimize.minimize
and settings for the chosen optimization method.
- Return type:
- Returns:
A 2-tuple containing flag indicating whether or not the optimizer exited successfully and the optimized noise strength epsilon.
Note
Using this function may require some tuning. One of the main challenges is setting a good value of
num_samples
in the PEC optionspec_kwargs
. Setting a small value ofnum_samples
is typically necessary to obtain a reasonable execution time. On the other hand, using a number of PEC samples that is too small can result in a large statistical error, ultimately causing the optimization process to fail.
Sampling from a Noisy Decomposition of an Ideal Operation#
Tools for sampling from the noisy representations of ideal operations.
- mitiq.pec.sampling.sample_circuit(ideal_circuit, representations, random_state=None, num_samples=1)[source]#
Samples a list of implementable circuits from the quasi-probability representation of the input ideal circuit. Returns the list of circuits, the corresponding list of signs and the one-norm of the quasi-probability representation (of the full circuit).
- Parameters:
ideal_circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal circuit from which an implementable circuit is sampled.representations (
Sequence
[OperationRepresentation
]) – List of representations of every operation in the input circuit. If a representation cannot be found for an operation in the circuit, a ValueError is raised.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling.num_samples (
int
) – The number of samples.
- Return type:
Tuple
[List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],List
[int
],float
]- Returns:
The tuple (
sampled_circuits
,signs
,norm
) wheresampled_circuits
are the sampled implementable circuits,signs
are the signs associated to sampled_circuits andnorm
is the one-norm of the circuit representation.- Raises:
ValueError – If a representation is not found for an operation in the circuit.
- mitiq.pec.sampling.sample_sequence(ideal_operation, representations, random_state=None, num_samples=1)[source]#
Samples a list of implementable sequences from the quasi-probability representation of the input ideal operation. Returns the list of sequences, the corresponding list of signs and the one-norm of the quasi-probability representation (of the input operation).
For example, if the ideal operation is U with representation U = a A + b B, then this function returns A with probability \(|a| / (|a| + |b|)\) and B with probability \(|b| / (|a| + |b|)\). Also returns sign(a) (sign(b)) and \(|a| + |b|\) if A (B) is sampled.
Note that the ideal operation can be a sequence of operations (circuit), for instance U = V W, as long as a representation is known. Similarly, A and B can be sequences of operations (circuits) or just single operations.
- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The ideal operation from which an implementable sequence is sampled.representations (
Sequence
[OperationRepresentation
]) – A list of representations of ideal operations in a noisy basis. If no representation is found for ideal_operation, a ValueError is raised.random_state (
Union
[int
,RandomState
,None
]) – Seed for sampling.num_samples (
int
) – The number of samples.
- Return type:
Tuple
[List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],List
[int
],float
]- Returns:
The tuple (
sequences
,signs
,norm
) wheresequences
are the sampled sequences,signs
are the signs associated to the sampledsequences
andnorm
is the one-norm of the quasi-probability distribution.- Raises:
ValueError – If no representation is found for ideal_operation.
Probabilistic Error Cancellation Types#
Types used in probabilistic error cancellation.
- class mitiq.pec.types.types.NoisyBasis(*args, **kwargs)[source]#
A set of noisy operations which a quantum computer can actually implement, assumed to form a basis of n-qubit unitary matrices.
This class has been removed since Mitiq v0.24.0.
- class mitiq.pec.types.types.NoisyOperation(circuit, channel_matrix=None)[source]#
An operation (or sequence of operations) which a noisy quantum computer can actually implement.p
- Parameters:
- property circuit: Circuit#
Returns the circuit of the NoisyOperation as a Cirq circuit.
- Return type:
Circuit
- property native_circuit: Union[Circuit, pyquil.Program, QuantumCircuit, Circuit, QuantumTape]#
Returns the circuit used to initialize the NoisyOperation.
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]
- class mitiq.pec.types.types.OperationRepresentation(ideal, noisy_operations, coeffs, is_qubit_dependent=True)[source]#
A decomposition (basis expansion) of an operation or sequence of operations in a basis of noisy, implementable operations.
- Parameters:
ideal (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) –noisy_operations (
List
[NoisyOperation
]) –is_qubit_dependent (
bool
) –
- property distribution: List[float]#
Returns the probability distribution obtained from taking the absolute value and normalizing the quasi-probability distribution.
- sample(random_state=None)[source]#
Returns a randomly sampled NoisyOperation from the basis expansion.
- Parameters:
random_state (
Optional
[RandomState
]) – Defines the seed for sampling if provided.- Return type:
Utilities for Quantum Channels#
Utilities for manipulating matrix representations of quantum channels.
- mitiq.pec.channels.choi_to_super(choi_state)[source]#
Returns the superoperator matrix corresponding to the channel defined by the input (normalized) Choi state.
Up to normalization, this is just a tensor transposition.
- mitiq.pec.channels.kraus_to_choi(kraus_ops)[source]#
Returns the normalized choi state corresponding to the channel defined by the input kraus operators.
- mitiq.pec.channels.kraus_to_super(kraus_ops)[source]#
Maps a set of Kraus operators into a single superoperator matrix acting by matrix multiplication on vectorized density matrices.
The returned matrix \(S\) is obtained with the formula:
\[S = \sum_j K_j \otimes K_j^*,\]where \(\{K_j\}\) are the Kraus operators. The mapping is based on the following isomorphism:
\[A|i \rangle\langle j|B <=> (A \otimes B^T) |i\rangle|j\rangle.\]
- mitiq.pec.channels.matrix_to_vector(density_matrix)[source]#
Reshapes a \(d \times d\) density matrix into a \(d^2\)-dimensional state vector, according to the rule: \(|i \rangle\langle j| \rightarrow |i,j \rangle\).
- mitiq.pec.channels.super_to_choi(super_operator)[source]#
Returns the normalized choi state corresponding to the channel defined by the input superoperator.
Up to normalization, this is just a tensor transposition.
- mitiq.pec.channels.tensor_product(*args)[source]#
Returns the Kronecker product of the input array-like arguments. This is a generalization of the binary function
numpy.kron(arg_a, arg_b)
to the case of an arbitrary number of arguments.
Raw#
Run experiments without error mitigation (raw results)#
Run experiments without error mitigation.
Readout-Error Mitigation#
Postselection#
- mitiq.rem.post_select.post_select(result, selector, inverted=False)[source]#
Returns only the bitstrings which satisfy the predicate in
selector
.- Parameters:
result (
MeasurementResult
) – List of bitstrings.selector (
Callable
[[Union
[str
,List
[int
]]],bool
]) –Predicate for which bitstrings to select. Examples:
selector = lambda bitstring: sum(bitstring) == k
- Select all bitstrings of Hamming weightk
.selector = lambda bitstring: sum(bitstring) <= k
- Select all bitstrings of Hamming weight at mostk
.selector = lambda bitstring: bitstring[0] == 1
- Select all bitstrings such that the the first bit is 1.
inverted (
bool
) – Invert the selector predicate so that bitstrings which obeyselector(bitstring) == False
are selected and returned.
- Return type:
REM Technique#
Readout Confusion Inversion.
- mitiq.rem.rem.execute_with_rem(circuit, executor, observable, *, inverse_confusion_matrix)[source]#
Returns the readout error mitigated expectation value utilizing an inverse confusion matrix.
- Parameters:
executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],MeasurementResult
]]) – A Mitiq executor that executes a circuit and returns the unmitigatedMeasurementResult
.observable (
Observable
) – Observable to compute the expectation value of (required).inverse_confusion_matrix (
ndarray
[Any
,dtype
[float64
]]) – The inverse confusion matrix to apply to the probability vector estimated with noisy measurement results.circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) –
- Return type:
- Returns:
The expectation value estimated with REM.
- mitiq.rem.rem.mitigate_executor(executor, *, inverse_confusion_matrix)[source]#
Returns a modified version of the input ‘executor’ which is error-mitigated with readout confusion inversion (RCI). The type of the output executor will be equal to the type of the input executor: an
Executor
object or a Python callable.- Parameters:
executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],MeasurementResult
]]) – A Mitiq executor that executes a circuit and returns the unmitigatedMeasurementResult
.inverse_confusion_matrix (
ndarray
[Any
,dtype
[float64
]]) – The inverse confusion matrix to apply to the probability vector estimated with noisy measurement results.
- Return type:
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],MeasurementResult
]]- Returns:
The error-mitigated version of the input executor.
- mitiq.rem.rem.rem_decorator(*, inverse_confusion_matrix)[source]#
Decorator which adds an error-mitigation layer based on readout confusion inversion (RCI) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a
MeasurementResult
.- Parameters:
inverse_confusion_matrix (
ndarray
[Any
,dtype
[float64
]]) – The inverse confusion matrix to apply to the probability vector estimated with noisy measurement results (required).- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],MeasurementResult
]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],MeasurementResult
]]- Returns:
The error-mitigating decorator to be applied to an executor function.
Zero Noise Extrapolation#
Zero Noise Extrapolation (High-Level Tools)#
High-level zero-noise extrapolation tools.
- mitiq.zne.zne.execute_with_zne(circuit, executor, observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#
Estimates the error-mitigated expectation value associated to the input circuit, via the application of zero-noise extrapolation (ZNE).
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The input circuit to execute with ZNE.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – A Mitiq executor that executes a circuit and returns the unmitigatedQuantumResult
(e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. IfNone
, theexecutor
must return an expectation value. Otherwise, theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.factory (
Optional
[Factory
]) –Factory
object that determines the zero-noise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – The function for scaling the noise of a quantum circuit. A list of built-in functions can be found inmitiq.zne.scaling
.num_to_average (
int
) – Number of times expectation values are computed by the executor after each call toscale_noise
, then averaged.
- Return type:
- Returns:
The expectation value estimated with ZNE.
- mitiq.zne.zne.mitigate_executor(executor, observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#
Returns a modified version of the input ‘executor’ which is error-mitigated with zero-noise extrapolation (ZNE).
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]) – A function that executes a circuit and returns the unmitigated QuantumResult (e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.factory (
Optional
[Factory
]) – Factory object determining the zero-noise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Function for scaling the noise of a quantum circuit.num_to_average (
int
) – Number of times expectation values are computed by the executor after each call to scale_noise, then averaged.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],float
]- Returns:
The error-mitigated version of the input executor.
- mitiq.zne.zne.zne_decorator(observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#
Decorator which adds an error-mitigation layer based on zero-noise extrapolation (ZNE) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a
QuantumResult
(e.g. an expectation value).- Parameters:
observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor being decorated must return an expectation value. Otherwise, the QuantumResult returned by the executor is used to compute the expectation of the observable.factory (
Optional
[Factory
]) – Factory object determining the zero-noise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Function for scaling the noise of a quantum circuit.num_to_average (
int
) – Number of times expectation values are computed by the executor after each call to scale_noise, then averaged.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],float
]]- Returns:
The error-mitigating decorator to be applied to an executor function.
Inference and Extrapolation: Factories#
Classes corresponding to different zero-noise extrapolation methods.
- class mitiq.zne.inference.AdaExpFactory(steps, scale_factor=2.0, asymptote=None, avoid_log=False, max_scale_factor=6.0)[source]#
Factory object implementing an adaptive zero-noise extrapolation algorithm assuming an exponential ansatz y(x) = a + b * exp(-c * x), with c > 0.
The noise scale factors are are chosen adaptively at each step, depending on the history of collected results.
If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.
If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a linear model by logarithmic transformation.
- Parameters:
steps (
int
) – The number of optimization steps. At least 3 are necessary.scale_factor (
float
) – The second noise scale factor (the first is always 1.0). Further scale factors are adaptively determined.asymptote (
Optional
[float
]) – The infinite-noise limit y(x->inf) (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.max_scale_factor (
float
) – Maximum noise scale factor. Default is 6.0.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- static extrapolate(scale_factors, exp_values, asymptote=None, avoid_log=False, eps=1e-06, full_output=False)[source]#
Static method which evaluates the extrapolation to the zero-noise limit assuming an exponential ansatz y(x) = a + b * exp(-c * x), with c > 0.
If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.
If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a linear model by a logarithmic transformation.
- Parameters:
scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.asymptote (
Optional
[float
]) – The infinite-noise limit y(x->inf) (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.eps (
float
) – Epsilon to regularize log(sign(scale_factors - asymptote)) when the argument is to close to zero or negative.full_output (
bool
) – If False (default), only the zero-noise limit is returned. If True, additional results are returned too.
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ValueError – If the arguments are not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- is_converged()[source]#
Returns True if all the needed expectation values have been computed, else False.
- Return type:
- class mitiq.zne.inference.AdaptiveFactory[source]#
Abstract class designed to adaptively produce a new noise scaling parameter based on a historical stack of previous noise scale parameters (“self._instack”) and previously estimated expectation values (“self._outstack”).
Specific zero-noise extrapolation algorithms which are adaptive are derived from this class.
- abstract is_converged()[source]#
Returns True if all needed expectation values have been computed, else False.
- Return type:
- run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1, max_iterations=100)[source]#
Evaluates a sequence of expectation values by executing quantum circuits until enough data is collected (or iterations reach “max_iterations”).
- Parameters:
qp (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – Circuit to mitigate.executor (
Union
[Executor
,Callable
[...
,Union
[float
,MeasurementResult
,ndarray
]]]) – Amitiq.Executor
or a function which inputs a (list of) quantum circuits and outputs a (list of)mitiq.QuantumResult
s.observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Function that scales the noise level of a quantum circuit.num_to_average (
int
) – Number of times expectation values are computed by the executor after each call to scale_noise, then averaged.max_iterations (
int
) – Maximum number of iterations (optional).
- Return type:
- run_classical(scale_factor_to_expectation_value, max_iterations=100)[source]#
Evaluates a sequence of expectation values until enough data is collected (or iterations reach “max_iterations”).
- Parameters:
- Raises:
ConvergenceWarning – If iteration loop stops before convergence.
- Return type:
- class mitiq.zne.inference.BatchedFactory(scale_factors, shot_list=None)[source]#
Abstract class of a non-adaptive Factory initialized with a pre-determined set of scale factors.
Specific (non-adaptive) extrapolation algorithms are derived from this class by defining the reduce method.
- abstract static extrapolate(*args, **kwargs)[source]#
Returns the extrapolation to the zero-noise limit.
- reduce()[source]#
Evaluates the zero-noise limit found by fitting according to the factory’s extrapolation method.
- Return type:
- Returns:
The zero-noise limit.
- run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#
Computes the expectation values at each scale factor and stores them in the factory. If the executor returns a single expectation value, the circuits are run sequentially. If the executor is batched and returns a list of expectation values (one for each circuit), then the circuits are sent to the backend as a single job. To detect if an executor is batched, it must be annotated with a return type that is one of the following:
Iterable[float]
List[float]
Sequence[float]
Tuple[float]
numpy.ndarray
- Parameters:
qp (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – Quantum circuit to run.executor (
Union
[Executor
,Callable
[...
,Union
[float
,MeasurementResult
,ndarray
]]]) – Amitiq.Executor
or a function which inputs a (list of) quantum circuits and outputs a (list of)mitiq.QuantumResult
s.observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Noise scaling function.num_to_average (
int
) – The number of circuits executed for each noise scale factor. This parameter can be used to increase the precision of the “executor” or to average the effect of a non-deterministic “scale_noise” function.
- Return type:
- run_classical(scale_factor_to_expectation_value)[source]#
Computes expectation values by calling the input function at each scale factor.
- exception mitiq.zne.inference.ConvergenceWarning[source]#
Warning raised by
Factory
objects when their run_classical method fails to converge.
- class mitiq.zne.inference.ExpFactory(scale_factors, asymptote=None, avoid_log=False, shot_list=None)[source]#
Factory object implementing a zero-noise extrapolation algorithm assuming an exponential ansatz y(x) = a + b * exp(-c * x), with c > 0.
If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.
If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a linear model by a logarithmic transformation.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.asymptote (
Optional
[float
]) – Infinite-noise limit (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- static extrapolate(scale_factors, exp_values, asymptote=None, avoid_log=False, eps=1e-06, full_output=False)[source]#
Static method which evaluates the extrapolation to the zero-noise limit assuming an exponential ansatz y(x) = a + b * exp(-c * x), with c > 0.
If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.
If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a linear model by a logarithmic transformation.
- Parameters:
scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.asymptote (
Optional
[float
]) – The infinite-noise limit y(x->inf) (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.eps (
float
) – Epsilon to regularize log(sign(scale_factors - asymptote)) when the argument is to close to zero or negative.full_output (
bool
) – If False (default), only the zero-noise limit is returned. If True, additional information about the extrapolated limit is returned too.
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ValueError – If the arguments are not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- exception mitiq.zne.inference.ExtrapolationError[source]#
Error raised by
Factory
objects when the extrapolation fit fails.
- exception mitiq.zne.inference.ExtrapolationWarning[source]#
Warning raised by
Factory
objects when the extrapolation fit is ill-conditioned.
- class mitiq.zne.inference.Factory[source]#
Abstract base class which performs the classical parts of zero-noise extrapolation. This minimally includes:
scaling circuits,
sending jobs to execute,
collecting the results,
fitting the collected data,
Extrapolating to the zero-noise limit.
If all scale factors are set a priori, the jobs can be batched. This is handled by a BatchedFactory.
If the next scale factor depends on the previous history of results, jobs are run sequentially. This is handled by an AdaptiveFactory.
- get_extrapolation_curve()[source]#
Returns the extrapolation curve, i.e., a function which inputs a noise scale factor and outputs the associated expectation value. This function is the solution of the regression problem used to evaluate the zero-noise extrapolation.
- get_optimal_parameters()[source]#
Returns the optimal model parameters produced by the extrapolation fit.
- get_parameters_covariance()[source]#
Returns the covariance matrix of the model parameters produced by the extrapolation fit.
- get_scale_factors()[source]#
Returns the scale factors at which the factory has computed expectation values.
- get_zero_noise_limit()[source]#
Returns the last evaluation of the zero-noise limit computed by the factory. To re-evaluate its value, the method ‘reduce’ should be called first.
- Return type:
- get_zero_noise_limit_error()[source]#
Returns the extrapolation error representing the uncertainty affecting the zero-noise limit. It is deduced by error propagation from the covariance matrix associated to the fit parameters.
- Note: this quantity is only related to the ability of the model
to fit the measured data. Therefore, it may underestimate the actual error existing between the zero-noise limit and the true ideal expectation value.
- Return type:
- plot_data()[source]#
Returns a figure which is a scatter plot of (x, y) data where x are scale factors at which expectation values have been computed, and y are the associated expectation values.
- Returns:
A 2D scatter plot described above.
- Return type:
fig
- plot_fit()[source]#
Returns a figure which plots the experimental data as well as the best fit curve.
- Returns:
A figure which plots the best fit curve as well as the data.
- Return type:
fig
- push(instack_val, outstack_val)[source]#
Appends “instack_val” to “self._instack” and “outstack_val” to “self._outstack”. Each time a new expectation value is computed this method should be used to update the internal state of the Factory.
- abstract run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#
Calls the executor function on noise-scaled quantum circuit and stores the results.
- Parameters:
qp (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – Quantum circuit to scale noise in.executor (
Union
[Executor
,Callable
[...
,Union
[float
,MeasurementResult
,ndarray
]]]) – Amitiq.Executor
or a function which inputs a (list of) quantum circuits and outputs a (list of)mitiq.QuantumResult
s.observable (
Optional
[Observable
]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]) – Function which inputs a quantum circuit and outputs a noise-scaled quantum circuit.num_to_average (
int
) – Number of times the executor function is called on each noise-scaled quantum circuit.
- Return type:
- class mitiq.zne.inference.FakeNodesFactory(scale_factors, shot_list=None)[source]#
Factory object implementing a modified version [De2020polynomial] of Richardson extrapolation. In this version the original set of scale factors is mapped to a new set of fake nodes, known as Chebyshev-Lobatto points. This method may give a better interpolation for particular types of curves and if the number of scale factors is large (> 10). One should be aware that, in many other cases, the fake nodes extrapolation method is usually not superior to standard Richardson extrapolation.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
[De2020polynomial]: S.De Marchia. F. Marchetti, E.Perracchionea and D.Poggialia, “Polynomial interpolation via mapped bases without resampling,” Journ of Comp. and App. Math. 364, 112347 (2020), (https://www.sciencedirect.com/science/article/abs/pii/S0377042719303449).
- class mitiq.zne.inference.LinearFactory(scale_factors, shot_list=None)[source]#
Factory object implementing zero-noise extrapolation based on a linear fit.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- static extrapolate(scale_factors, exp_values, full_output=False)[source]#
Static method which evaluates the linear extrapolation to the zero-noise limit.
- Parameters:
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- class mitiq.zne.inference.PolyExpFactory(scale_factors, order, asymptote=None, avoid_log=False, shot_list=None)[source]#
Factory object implementing a zero-noise extrapolation algorithm assuming an (almost) exponential ansatz with a non linear exponent y(x) = a + sign * exp(z(x)), where z(x) is a polynomial of a given order.
The parameter “sign” is a sign variable which can be either 1 or -1, corresponding to decreasing and increasing exponentials, respectively. The parameter “sign” is automatically deduced from the data.
If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.
If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a polynomial model by logarithmic transformation.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.order (
int
) – Extrapolation order (degree of the polynomial z(x)). It cannot exceed len(scale_factors) - 1. If asymptote is None, order cannot exceed len(scale_factors) - 2.asymptote (
Optional
[float
]) – The infinite-noise limit y(x->inf) (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- static extrapolate(scale_factors, exp_values, order, asymptote=None, avoid_log=False, eps=1e-06, full_output=False)[source]#
Static method which evaluates the extrapolation to the zero-noise limit with an exponential ansatz (whose exponent is a polynomial of degree “order”).
The exponential ansatz is y(x) = a + sign * exp(z(x)) where z(x) is a polynomial and “sign” is either +1 or -1 corresponding to decreasing and increasing exponentials, respectively. The parameter “sign” is automatically deduced from the data.
It is also assumed that z(x–>inf) = -inf, such that y(x–>inf) –> a.
If asymptote is None, the ansatz y(x) is fitted with a non-linear optimization.
If asymptote is given and avoid_log=False, a linear fit with respect to z(x) := log[sign * (y(x) - asymptote)] is performed.
- Parameters:
scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.asymptote (
Optional
[float
]) – The infinite-noise limit y(x->inf) (optional argument).order (
int
) – The degree of the polynomial z(x).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.eps (
float
) – Epsilon to regularize log(sign(scale_factors - asymptote)) when the argument is to close to zero or negative.full_output (
bool
) – If False (default), only the zero-noise limit is returned. If True, additional information about the extrapolated limit is returned too.
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ValueError – If the arguments are not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- class mitiq.zne.inference.PolyFactory(scale_factors, order, shot_list=None)[source]#
Factory object implementing a zero-noise extrapolation algorithm based on a polynomial fit.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.order (
int
) – Extrapolation order (degree of the polynomial fit). It cannot exceed len(scale_factors) - 1.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
RichardsonFactory and LinearFactory are special cases of PolyFactory.
- static extrapolate(scale_factors, exp_values, order, full_output=False)[source]#
Static method which evaluates a polynomial extrapolation to the zero-noise limit.
- Parameters:
scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.order (
int
) – The extrapolation order (degree of the polynomial fit).full_output (
bool
) – If False (default), only the zero-noise limit is returned. If True, additional information about the extrapolated limit is returned too.
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- class mitiq.zne.inference.RichardsonFactory(scale_factors, shot_list=None)[source]#
Factory object implementing Richardson extrapolation.
- Parameters:
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.shot_list (
Optional
[List
[int
]]) – Optional sequence of integers corresponding to the number of samples taken for each expectation value. If this argument is explicitly passed to the factory, it must have the same length of scale_factors and the executor function must accept “shots” as a valid keyword argument.
- Raises:
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- static extrapolate(scale_factors, exp_values, full_output=False)[source]#
- Static method which evaluates the Richardson extrapolation to the
zero-noise limit.
- Parameters:
- Return type:
Union
[float
,Tuple
[float
,Optional
[float
],List
[float
],Optional
[ndarray
],Callable
[[float
],float
]]]- Returns:
The extrapolated zero-noise limit. If full_output is True, also returns * standard deviation of the extrapolated zero-noise limit, * optimal parameters of the best-fit model, * parameter covariance matrix of best-fit model, * best-fit model as a Callable[[float], float] function.
- Raises:
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Note
This static method computes the zero-noise limit from input parameters. To compute the zero-noise limit from the Factory parameters, use the
reduce
method.
- mitiq.zne.inference.mitiq_curve_fit(ansatz, scale_factors, exp_values, init_params=None)[source]#
Fits the ansatz to the (scale factor, expectation value) data using
scipy.optimize.curve_fit
, returning the optimal parameters and covariance matrix of the parameters.- Parameters:
ansatz (
Callable
[...
,float
]) – The model function used for zero-noise extrapolation. The first argument is the noise scale variable, the remaining arguments are the parameters to fit.scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.init_params (
Optional
[List
[float
]]) – Initial guess for the parameters. If None, the initial values are set to 1.
- Return type:
- Returns:
The array of optimal parameters and the covariance matrix of the parameters. If the fit is ill-conditioned, the covariance matrix may contain np.inf elements.
- Raises:
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
- mitiq.zne.inference.mitiq_polyfit(scale_factors, exp_values, deg, weights=None)[source]#
Fits the ansatz to the (scale factor, expectation value) data using
numpy.polyfit
, returning the optimal parameters and covariance matrix of the parameters.- Parameters:
scale_factors (
Sequence
[float
]) – The array of noise scale factors.exp_values (
Sequence
[float
]) – The array of expectation values.deg (
int
) – The degree of the polynomial fit.weights (
Optional
[Sequence
[float
]]) – Optional array of weights for each sampled point. This is used to make a weighted least squares fit.
- Return type:
- Returns:
The optimal parameters and covariance matrix of the parameters. If there is not enough data to estimate the covariance matrix, it is returned as None.
- Raises:
ExtrapolationWarning – If the extrapolation fit is ill-conditioned.
Noise Scaling: Unitary Folding#
Functions for local and global unitary folding on supported circuits.
- mitiq.zne.scaling.folding.fold_all(circuit, scale_factor, exclude=frozenset({}))[source]#
Returns a circuit with all gates folded locally.
- Parameters:
circuit (
Circuit
) – Circuit to fold.scale_factor (
float
) –Approximate factor by which noise is scaled in the circuit. Each gate is folded round((scale_factor - 1.0) / 2.0) times. For example:
scale_factor | num_folds ------------------------ 1.0 | 0 3.0 | 1 5.0 | 2
Do not fold these gates. Supported gate keys are listed in the following table.:
Gate key | Gate ------------------------- "H" | Hadamard "X" | Pauli X "Y" | Pauli Y "Z" | Pauli Z "I" | Identity "S" | Phase gate "T" | T gate "rx" | X-rotation "ry" | Y-rotation "rz" | Z-rotation "CNOT" | CNOT "CZ" | CZ gate "SWAP" | Swap "ISWAP" | Imaginary swap "CSWAP" | CSWAP "TOFFOLI" | Toffoli gate "single" | All single qubit gates "double" | All two-qubit gates "triple" | All three-qubit gates
- Return type:
Circuit
- mitiq.zne.scaling.folding.fold_gates_at_random(circuit, scale_factor, seed=None, **kwargs)[source]#
Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the right (end) of the circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [7].
- Parameters:
- Keyword Arguments:
fidelities (Dict[str, float]) –
Dictionary of gate fidelities. Each key is a string which specifies the gate and each value is the fidelity of that gate. When this argument is provided, folded gates contribute an amount proportional to their infidelity (1 - fidelity) to the total noise scaling. Fidelity values must be in the interval (0, 1]. Gates not specified have a default fidelity of 0.99**n where n is the number of qubits the gates act on.
Supported gate keys are listed in the following table.:
Gate key | Gate ------------------------- "H" | Hadamard "X" | Pauli X "Y" | Pauli Y "Z" | Pauli Z "I" | Identity "S" | Phase gate "T" | T gate "rx" | X-rotation "ry" | Y-rotation "rz" | Z-rotation "CNOT" | CNOT "CZ" | CZ gate "SWAP" | Swap "ISWAP" | Imaginary swap "CSWAP" | CSWAP "TOFFOLI" | Toffoli gate "single" | All single qubit gates "double" | All two-qubit gates "triple" | All three-qubit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all single-qubit gates except Hadamard to have fidelity one.
squash_moments (bool) – If True, all gates (including folded gates) are placed as early as possible in the circuit. If False, new moments are created for folded gates. This option only applies to QPROGRAM types which have a “moment” or “time” structure. Default is True.
return_mitiq (bool) – If True, returns a Mitiq circuit instead of the input circuit type (if different). Default is False.
- Returns:
The folded quantum circuit as a QPROGRAM.
- Return type:
folded
- mitiq.zne.scaling.folding.fold_gates_from_left(circuit, scale_factor, **kwargs)[source]#
Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the left (beginning) of the circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [7].
- Parameters:
- Keyword Arguments:
fidelities (Dict[str, float]) –
Dictionary of gate fidelities. Each key is a string which specifies the gate and each value is the fidelity of that gate. When this argument is provided, folded gates contribute an amount proportional to their infidelity (1 - fidelity) to the total noise scaling. Fidelity values must be in the interval (0, 1]. Gates not specified have a default fidelity of 0.99**n where n is the number of qubits the gates act on.
Supported gate keys are listed in the following table.:
Gate key | Gate ------------------------- "H" | Hadamard "X" | Pauli X "Y" | Pauli Y "Z" | Pauli Z "I" | Identity "S" | Phase gate "T" | T gate "rx" | X-rotation "ry" | Y-rotation "rz" | Z-rotation "CNOT" | CNOT "CZ" | CZ gate "SWAP" | Swap "ISWAP" | Imaginary swap "CSWAP" | CSWAP "TOFFOLI" | Toffoli gate "single" | All single qubit gates "double" | All two-qubit gates "triple" | All three-qubit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all single-qubit gates except Hadamard to have fidelity one.
squash_moments (bool) – If True, all gates (including folded gates) are placed as early as possible in the circuit. If False, new moments are created for folded gates. This option only applies to QPROGRAM types which have a “moment” or “time” structure. Default is True.
return_mitiq (bool) – If True, returns a Mitiq circuit instead of the input circuit type (if different). Default is False.
- Returns:
The folded quantum circuit as a QPROGRAM.
- Return type:
folded
- mitiq.zne.scaling.folding.fold_gates_from_right(circuit, scale_factor, **kwargs)[source]#
Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the right (end) of the circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [7].
- Parameters:
- Keyword Arguments:
fidelities (Dict[str, float]) –
Dictionary of gate fidelities. Each key is a string which specifies the gate and each value is the fidelity of that gate. When this argument is provided, folded gates contribute an amount proportional to their infidelity (1 - fidelity) to the total noise scaling. Fidelity values must be in the interval (0, 1]. Gates not specified have a default fidelity of 0.99**n where n is the number of qubits the gates act on.
Supported gate keys are listed in the following table.:
Gate key | Gate ------------------------- "H" | Hadamard "X" | Pauli X "Y" | Pauli Y "Z" | Pauli Z "I" | Identity "S" | Phase gate "T" | T gate "rx" | X-rotation "ry" | Y-rotation "rz" | Z-rotation "CNOT" | CNOT "CZ" | CZ gate "SWAP" | Swap "ISWAP" | Imaginary swap "CSWAP" | CSWAP "TOFFOLI" | Toffoli gate "single" | All single qubit gates "double" | All two-qubit gates "triple" | All three-qubit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all single-qubit gates except Hadamard to have fidelity one.
squash_moments (bool) – If True, all gates (including folded gates) are placed as early as possible in the circuit. If False, new moments are created for folded gates. This option only applies to QPROGRAM types which have a “moment” or “time” structure. Default is True.
return_mitiq (bool) – If True, returns a Mitiq circuit instead of the input circuit type (if different). Default is False.
- Returns:
The folded quantum circuit as a QPROGRAM.
- Return type:
folded
- mitiq.zne.scaling.folding.fold_global(circuit, scale_factor, **kwargs)[source]#
Returns a new circuit obtained by folding the global unitary of the input circuit.
The returned folded circuit has a number of gates approximately equal to scale_factor * len(circuit).
- Parameters:
- Keyword Arguments:
return_mitiq (bool) – If True, returns a Mitiq circuit instead of the input circuit type (if different). Default is False.
- Returns:
the folded quantum circuit as a QPROGRAM.
- Return type:
folded
Noise Scaling: Identity Insertion Scaling#
Functions for scaling supported circuits by inserting layers of identity gates.
- mitiq.zne.scaling.identity_insertion.insert_id_layers(input_circuit, scale_factor)[source]#
Returns a scaled version of the input circuit by inserting layers of identities.
- Parameters:
input_circuit (
Circuit
) – Cirq Circuit to be scaledscale_factor (
float
) – Noise scaling factor as a float
- Returns:
Scaled quantum circuit via identity layer insertions
- Return type:
scaled_circuit
Noise Scaling: Layerwise Folding#
Functions for layer-wise unitary folding on supported circuits.
- mitiq.zne.scaling.layer_scaling.get_layer_folding(layer_index)[source]#
Return function to perform folding. The function return can be used as an argument to define the noise scaling within the execute_with_zne function.
- Parameters:
layer_index (
int
) – The layer of the circuit to apply folding to.- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]- Returns:
The function for folding the ith layer.
Noise Scaling: Parameter Calibration#
- mitiq.zne.scaling.parameter.compute_parameter_variance(executor, gate, qubit, depth=100)[source]#
Given an executor and a gate, determines the effective variance in the control parameter that can be used as the
base_variance
argument inmitiq.zne.scaling.scale_parameters
.Note: Only works for one qubit gates for now.
- Parameters:
executor (
Callable
[...
,float
]) – A function that takes in a quantum circuit and returns an expectation value.gate (
EigenGate
) – The quantum gate that you wish to profile.qubit (
Qid
) – The index of the qubit you wish to profile.depth (
int
) – The number of operations you would like to use to profile your gate.
- Return type:
- Returns:
The estimated variance of the control parameter.
- mitiq.zne.scaling.parameter.scale_parameters(circuit, scale_factor, base_variance, seed=None)[source]#
Applies parameter-noise scaling to the input circuit, assuming that each gate has the same base level of noise.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The circuit to scale as a QPROGRAM. All measurements should be in the last moment of the circuit.scale_factor (
float
) – The amount to scale the base noise level by.base_variance (
float
) – The base level (variance) of parameter noise, assumed to be the same for each gate of the circuit.seed (
Optional
[int
]) – Optional seed for random number generator.
- Return type:
Circuit
- Returns:
The parameter noise scaled circuit.
Pauli Twirling#
- mitiq.pt.pt.execute_with_pauli_twirling(circuit, executor, observable=None, *, num_circuits=10)[source]#
Estimates the expectation value of the input circuit by averaging expectation values obtained from Pauli twirled circuits.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The input circuit to execute with twirling.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – A Mitiq executor that executes a circuit and returns the unmitigatedQuantumResult
(e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. IfNone
, theexecutor
must return an expectation value (float). Otherwise, theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.num_circuits (
int
) – Number of circuits to be twirled, and averaged.
- Return type:
- Returns:
The expectation value estimated with Pauli twirling.
- mitiq.pt.pt.twirl_CNOT_gates(circuit, num_circuits)[source]#
Generate a list of circuits using Pauli twirling on CNOT gates.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The circuit to generate twirled versions ofnum_circuits (
int
) – The number of sampled circuits to return
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]
- mitiq.pt.pt.twirl_CZ_gates(circuit, num_circuits)[source]#
Generate a list of circuits using Pauli twirling on CZ gates.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The circuit to generate twirled versions ofnum_circuits (
int
) – The number of sampled circuits to return
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]]
Calibration#
- class mitiq.calibration.calibrator.Calibrator(executor, *, frontend, settings=<mitiq.calibration.settings.Settings object>, ideal_executor=None)[source]#
An object used to orchestrate experiments for calibrating optimal error mitigation strategies.
- Parameters:
executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – An unmitigated executor returning aMeasurementResult
.settings (
Settings
) – ASettings
object which specifies the type and amount of circuits/error mitigation methods to run.frontend (
str
) – The executor frontend as a string. For a list of supported frontends seemitiq.SUPPORTED_PROGRAM_TYPES.keys()
,ideal_executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]],None
]) – An optional simulated executor returning the idealMeasurementResult
without noise.
- best_strategy()[source]#
Finds the best strategy by using the parameters that had the smallest error.
- property cirq_executor: Executor#
Returns an executor which is able to run Cirq circuits by converting them and calling self.executor.
- Parameters:
executor – Executor which takes as input QPROGRAM circuits.
- Return type:
- Returns:
Executor which takes as input a Cirq circuits.
- execute_with_mitigation(circuit, expval_executor, observable=None)[source]#
See
execute_with_mitigation()
for signature and details.- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) –expval_executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) –observable (
Optional
[Observable
]) –
- Return type:
- class mitiq.calibration.calibrator.ExperimentResults(num_strategies, num_problems)[source]#
Class to store calibration experiment data, and provide helper methods for computing results based on it.
- add_result(strategy, problem, *, ideal_val, noisy_val, mitigated_val, log=False)[source]#
Add a single result from a (Strategy, BenchmarkProblem) pair and store the results.
- best_strategy_id()[source]#
Returns the stategy id that corresponds to the strategy that maintained the smallest error across all
BenchmarkProblem
instances.- Return type:
- ensure_full()[source]#
Check to ensure all expected data is collected. All mitigated, noisy and ideal values must be nonempty for this to pass and return True.
- Return type:
- mitiq.calibration.calibrator.convert_to_expval_executor(executor, bitstring)[source]#
Constructs a new executor returning an expectation value given by the probability that the circuit outputs the most likely state according to the ideal distribution.
- Parameters:
executor (
Executor
) – Executor which returns aMeasurementResult
(bitstrings).bitstring (
str
) – The bitstring to measure the probability of. Defaults to ground state bitstring “00…0”.
- Return type:
- Returns:
A tuple containing an executor returning expectation values and, the most likely bitstring, according to the passed
distribution
- mitiq.calibration.calibrator.execute_with_mitigation(circuit, executor, observable=None, *, calibrator)[source]#
Estimates the error-mitigated expectation value associated to the input circuit, via the application of the best mitigation strategy, as determined by calibration.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]) – The input circuit to execute.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]],Union
[float
,MeasurementResult
,ndarray
]]]) – A Mitiq executor that executes a circuit and returns the unmitigatedQuantumResult
(e.g. an expectation value).observable (
Optional
[Observable
]) – Observable to compute the expectation value of. IfNone
, theexecutor
must return an expectation value. Otherwise, theQuantumResult
returned byexecutor
is used to compute the expectation of the observable.calibrator (
Calibrator
) –Calibrator
object with which to determine the error mitigation strategy to execute the circuit.
- Return type:
- Returns:
The error mitigated expectation expectation value.
- class mitiq.calibration.settings.BenchmarkProblem(id, circuit, type, ideal_distribution)[source]#
A dataclass containing information for instances of problems that will be run during the calibrations process.
- Parameters:
- converted_circuit(circuit_type)[source]#
Adds measurements to all qubits and convert to the input frontend type.
- Parameters:
circuit_type (
str
) – The circuit type as a string. For supported circuit types see mitiq.SUPPORTED_PROGRAM_TYPES.- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
]- Returns:
The converted circuit with final measurements.
- class mitiq.calibration.settings.MitigationTechnique(value)[source]#
Simple enum type for handling validation, and providing helper functions when accessing mitigation techniques.
- class mitiq.calibration.settings.Settings(benchmarks, strategies)[source]#
A class to store the configuration settings of a
Calibrator
.- Parameters:
benchmarks (
List
[Dict
[str
,Any
]]) –A list where each element is a dictionary of parameters for generating circuits to be used in calibration experiments. The dictionary keys include
circuit_type
,num_qubits
,circuit_depth
, and in the case of mirror circuits, a random seedcircuit_seed
. An example of input tobenchmarks
is:[ { "circuit_type": "rb", "num_qubits": 2, "circuit_depth": 7, }, { "circuit_type": "mirror", "num_qubits": 2, "circuit_depth": 7, "circuit_seed": 1, } ]
strategies (
List
[Dict
[str
,Any
]]) – A specification of the methods/parameters to be used in calibration experiments.
- make_problems()[source]#
Generate the benchmark problems for the calibration experiment. :rtype:
List
[BenchmarkProblem
] :returns: A list ofBenchmarkProblem
objects
- class mitiq.calibration.settings.Strategy(id, technique, technique_params)[source]#
A dataclass which describes precisely an error mitigation approach by specifying a technique and the associated options.
- Parameters:
id (
int
) – A unique numerical id.technique (
MitigationTechnique
) – One of Mitiq’s support error mitigation strategies, specified as aMitigationTechnique
.technique_params (
Dict
[str
,Any
]) – A dictionary of options to pass to the mitigation method specified in technique.