API-doc#
Error-Mitigation Techniques#
Classical Shadows#
Classical Shadows (High-Level Tools)#
Classical shadow estimation for quantum circuits.
- mitiq.shadows.shadows.classical_post_processing(shadow_outcomes, calibration_results=None, observables=None, k_shadows=None, state_reconstruction=False)[source]#
Executes a circuit with classical shadows. This function can be used for state reconstruction or expectation value estimation of observables.
- Parameters:
shadow_outcomes (
Tuple
[List
[str
],List
[str
]]) – The output of function shadow_quantum_processing.calibration_results (
Optional
[Dict
[str
,float
]]) – The output of function pauli_twirling_calibrate.observables (
Optional
[List
[PauliString
]]) – The set of observables to measure.k_shadows (
Optional
[int
]) – Number of groups of “median of means” used for shadow estimation of expectation values.state_reconstruction (
Optional
[bool
]) – Whether to reconstruct the state or estimate the expectation value of the observables.
- Returns:
rewrite this. If state_reconstruction is True: state tomography matrix in \(\mathbb{M}_{2^n}(\mathbb{C})\) if use_calibration is False, otherwise state tomography vector in \(\mathbb{C}^{4^d}\). If observables is given: estimated expectation values of observables.
- Return type:
TODO
- mitiq.shadows.shadows.pauli_twirling_calibrate(k_calibration=1, locality=None, zero_state_shadow_outcomes=None, qubits=None, executor=None, num_total_measurements_calibration=20000)[source]#
This function returns the dictionary of the median of means estimation of Pauli fidelities: \(\{\)“b”: \(f_{b}\}_{b\in\{0,1\}^n}\). The number of \(f_b\) is \(2^n\), or \(\sum_{i=1}^d C_n^i\) if the locality \(d\) is given.
In the notation of arXiv:2011.09636, this function estimates the coefficient \(f_b\), which are expansion coefficients of the twirled channel \(\mathcal{M}=\sum_b f_b\Pi_b\).
In practice, the output of this function can be used as calibration data for performing the classical shadows protocol in a way which is more robust to noise.
- Parameters:
k_calibration (
int
) – Number of groups of “median of means” used to solve for Pauli fidelity.locality (
Optional
[int
]) – The locality of the operator, whose expectation value is going to be estimated by the classical shadow. e.g. if operator is Ising model Hamiltonian with nearest neighbor interaction, then locality = 2.zero_state_shadow_outcomes (
Optional
[Tuple
[List
[str
],List
[str
]]]) – The output of functionshadow_quantum_processing()
of zero calibrate state.qubits (
Optional
[List
[Qid
]]) – The qubits to measure, needs to specify when the zero_state_shadow_outcomes is None.executor (
Optional
[Callable
[[Circuit
],MeasurementResult
]]) – The function to use to do quantum measurement, must be same as executor in shadow_quantum_processing. Needs to specify when the zero_state_shadow_outcomes is None.num_total_measurements_calibration (
Optional
[int
]) – Number of shots per group of “median of means” used for calibration. Needs to specify when the zero_state_shadow_outcomes is None.
- Return type:
- Returns:
A dictionary containing the calibration outcomes.
- mitiq.shadows.shadows.shadow_quantum_processing(circuit, executor, num_total_measurements_shadow, random_seed=None, qubits=None)[source]#
This function returns the bit strings and Pauli strings corresponding to the executor measurement outcomes for a given circuit, rotated by unitaries randomly sampled from a fixed unitary ensemble \(\mathcal{G}\).
In the current implementation, the unitaries are sampled from the local Clifford group for \(n\) qubits, i.e., \(\mathcal{G} = \mathrm{Cl}_2^n\).
In practice, the output of this function provides the raw experimental data necessary to perform the classical shadows protocol.
- Parameters:
circuit (
Circuit
) – The circuit to execute.executor (
Callable
[[Circuit
],MeasurementResult
]) – The function to use to do quantum measurement, must be same as executor in pauli_twirling_calibrate.num_total_measurements_shadow (
int
) – Total number of shots for shadow estimation.random_seed (
Optional
[int
]) – The random seed to use for the shadow measurements.
- Return type:
- Returns:
A dictionary containing the bit strings, the Pauli strings bit_strings: Circuit qubits computational basis e.g. “01..”\(:=|0\rangle|1\rangle..\). pauli_strings: The local Pauli measurement performed on each qubit. e.g.”XY..” means perform local X-basis measurement on the 1st qubit, local Y-basis measurement the 2ed qubit in the circuit, etc.
Quantum Processing#
Quantum processing functions for classical shadows.
- mitiq.shadows.quantum_processing.generate_random_pauli_strings(num_qubits, num_strings)[source]#
Generate a list of random Pauli strings.
- mitiq.shadows.quantum_processing.get_rotated_circuits(circuit, pauli_strings, add_measurements=True, qubits=None)[source]#
Returns a list of circuits that are identical to the input circuit, except that each one has single-qubit Clifford gates followed by measurement gates that are designed to measure the input Pauli strings in the Z basis.
- Parameters:
- Return type:
List
[Circuit
]- Returns:
The list of circuits with rotation and measurement gates appended.
- mitiq.shadows.quantum_processing.random_pauli_measurement(circuit, n_total_measurements, executor, qubits=None)[source]#
This function performs random Pauli measurements on a given circuit and returns the outcomes. These outcomes are represented as a tuple of two lists of strings.
- Parameters:
circuit (
Circuit
) – A Cirq circuit.n_total_measurements (
int
) – The number of snapshots.executor (
Callable
[[Circuit
],MeasurementResult
]) – A callable that runs a circuit and returns a single bitstring.qubits (
Optional
[List
[Qid
]]) – The qubits in the circuit to be measured. If None, all qubits in the circuit will be measured.
Warning
The
executor
must return aMeasurementResult
for a single shot, i.e., a single bitstring.- Return type:
- Returns:
Tuple containing two lists of strings, each of length equal to
n_total_measurements
. Strings in the first list are sequences of 0’s and 1’s, which represent qubit measurements outcomes in the computational basis (e.g. “01001”). Strings in the second list are sequences of Pauli-measurement performed on each qubit (e.g. “XZZYY”).
Classical Post-Processing#
Classical post-processing process of classical shadows.
- mitiq.shadows.classical_postprocessing.classical_snapshot(bitstring, paulistring, fidelities=None)[source]#
Implement a single snapshot state reconstruction with calibration of the noisy quantum channel.
- Parameters:
- Return type:
- Returns:
Reconstructed classical snapshot in terms of nparray.
- mitiq.shadows.classical_postprocessing.expectation_estimation_shadow(measurement_outcomes, pauli, num_batches, fidelities=None)[source]#
Calculate the expectation value of an observable from classical shadows. Use median of means to ameliorate the effects of outliers.
- Parameters:
measurement_outcomes (
Tuple
[List
[str
],List
[str
]]) – A shadow tuple obtained from z_basis_measurement.pauli_str – Single mitiq observable consisting of Pauli operators.
num_batches (
int
) – Number of batches to process measurement outcomes in.f_est – The estimated Pauli fidelities to use for calibration if available.
pauli (
PauliString
)
- Return type:
- Returns:
Float corresponding to the estimate of the observable expectation value.
- mitiq.shadows.classical_postprocessing.get_pauli_fidelities(calibration_outcomes, num_batches, locality=None)[source]#
Calculate Pauli fidelities for the calibration circuit. In the notation of arXiv:2011.09636, this function estimates the coefficients \(f_b\), which characterize the (noisy) classical shadow channel \(\mathcal{M}=\sum_b f_b \Pi_b\).
- Parameters:
calibration_measurement_outcomes – The random_Pauli_measurement outcomes for the state \(|0\rangle^{\otimes n}\)}` .
num_batches (
int
) – The number of batches in the median of means estimator.locality (
Optional
[int
]) – The locality of the operator, whose expectation value is going to be estimated by the classical shadow. E.g., if the operator is the Ising model Hamiltonian with nearest neighbor interactions, then locality = 2.
- Return type:
- Returns:
A \(2^n\)-dimensional dictionary of Pauli fidelities \(f_b\) for \(b = \{0,1\}^{n}\)
- mitiq.shadows.classical_postprocessing.get_single_shot_pauli_fidelity(bitstring, paulistring, locality=None)[source]#
Calculate Pauli fidelity \(f_b\) for a single shot measurement of the calibration circuit for b= bit_string.
In the notation of arXiv:2011.09636, this function estimates the coefficient \(f_b\), which characterizes the (noisy) classical shadow channel.
The locality is realized on the assumption that the noisy channel \(\Lambda\) is local \(\Lambda \equiv \bigotimes_i^n\Lambda_i\).
- Parameters:
bit_string – The bitstring corresponding to a computational basis state. E.g., ‘01…0’\(:=|0\rangle|1\rangle...|0\rangle\).
pauli_string – The local Pauli measurement performed on each qubit. e.g.’XY…Z’ means perform local X-basis measurement on the 1st qubit, local Y-basis measurement the 2ed qubit, local Z-basis measurement the last qubit in the circuit.
locality (
Optional
[int
]) – The locality of the operator, whose expectation value is going to be estimated by the classical shadow. E.g., if the operator is the Ising model Hamiltonian with nearest neighbor interactions, then locality = 2.bitstring (
str
)paulistring (
str
)
- Returns:
\(\{{f}_b\}\). If the locality is \(w < n\), then derive the output’s keys from the bit_string. Ensure that the number of 1s in the keys is less than or equal to w. The corresponding Pauli fidelity is the product of local Pauli fidelity where the associated locus in the keys are ‘1’.
- Return type:
A dictionary of Pauli fidelity bit_string
- mitiq.shadows.classical_postprocessing.shadow_state_reconstruction(shadow_measurement_outcomes, fidelities=None)[source]#
Reconstruct a state approximation as an average over all snapshots.
- Parameters:
- Return type:
- Returns:
The state reconstructed from classical shadow protocol
Utility Functions#
Defines utility functions for classical shadows protocol.
- mitiq.shadows.shadows_utils.batch_calibration_data(data, num_batches)[source]#
Batch calibration into chunks of size batch_size.
- mitiq.shadows.shadows_utils.create_string(str_len, loc_list)[source]#
This function returns a string of length
str_len
with 1s at the locations specified byloc_list
and 0s elsewhere.- Parameters:
- Return type:
- Returns:
A bitstring constructed as above.
Example
A basic example:
create_string(5, [1, 3]) >>> "01010"
- mitiq.shadows.shadows_utils.fidelity(sigma, rho)[source]#
Calculate the fidelity between two states.
- mitiq.shadows.shadows_utils.local_clifford_shadow_norm(obs)[source]#
Calculate shadow norm of an operator with random unitary sampled from local Clifford group.
- Parameters:
obs (
PauliString
) – A self-adjoint operator, i.e. mitiq.PauliString with real coffe.- Return type:
- Returns:
Shadow norm when unitary ensemble is local Clifford group.
- mitiq.shadows.shadows_utils.n_measurements_opts_expectation_bound(error, observables, failure_rate)[source]#
This function returns the minimum number of classical shadows required and the number of groups “k” into which we need to split the shadows for achieving the desired accuracy and failure rate in operator expectation value estimation.
- Parameters:
error (
float
) – The error on the estimator.observables (
List
[PauliString
]) – List of mitiq.PauliString corresponding to the observables we intend to measure.failure_rate (
float
) – Rate of failure for the bound to hold.
- Return type:
- Returns:
Integers quantifying the number of snapshots required to satisfy the shadow bound and the chunk size required to attain the specified failure rate.
- mitiq.shadows.shadows_utils.n_measurements_tomography_bound(epsilon, num_qubits)[source]#
This function returns the minimum number of classical shadows required for state reconstruction for achieving the desired accuracy.
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
,Circuit
]],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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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 for
method_select='gaussian'
.sigma_replace (float): Width of the Gaussian distribution used for
method_replace='gaussian'
.random_state (int): Seed for sampling.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
,Any
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
,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. [19] and Ref. [6].
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
,Circuit
]) – Quantum program to execute with error mitigation.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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
,Circuit
]],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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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 for
method_select='gaussian'
.sigma_replace (float): Width of the Gaussian distribution used for
method_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
,Circuit
]],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
,Circuit
]],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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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 for
method_select='gaussian'
.sigma_replace (float): Width of the Gaussian distribution used for
method_replace='gaussian'
.random_state (int): Seed for sampling.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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 [19], 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 for
method_select='gaussian'
.sigma_replace (float): Width of the Gaussian distribution used for
method_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 + \cdots + 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 + \cdots + a_n x_n\).
See Ref. [19] for more details on these methods.
Digital Dynamical Decoupling#
Digital Dynamical Decoupling (High-Level Tools)#
High-level digital dynamical decoupling (DDD) tools.
- mitiq.ddd.ddd.combine_results(results)[source]#
Averages over the DDD results to get the expectation value from using DDD.
- 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
,Circuit
]]) – 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
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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
,Circuit
]) – The input circuit to execute with DDD.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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
,Circuit
]]) – 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.generate_circuits_with_ddd(circuit, rule, rule_args={}, num_trials=1)[source]#
Generates a list of circuits with DDD sequences inserted.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – The quantum circuit to be modified with DD.rule (
Callable
[[int
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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.rule_args (
Dict
[str
,Any
]) – An optional dictionary of keyword arguments forrule
.num_trials (
int
) – The number of circuits to generate with DDD insertions.
- Return type:
list
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
A list of circuits with DDD inserted.
- 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
,Circuit
]],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
,Circuit
]]) – 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
,Circuit
]],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
,Circuit
]) – 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
,Circuit
]- 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.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.
Example
When
slack_length = 8
andgates = [X, X]
the spacing defaults to 2 and the rule returns the sequence:──I──I──X──I──I──X──I──I──
When
slack_length = 9
andgates [X, Y, X, Y]
the spacing defaults to 1 and the rule returns the sequence:──I──X──I──Y──I──X──I──Y──I──
- 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.
Warning
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. givenslack_length = 8
andgates = [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.
Layerwise Richardson Extrapolation#
Extrapolation methods for Layerwise Richardson Extrapolation (LRE)
- mitiq.lre.lre.execute_with_lre(input_circuit, executor, degree, fold_multiplier, folding_method=<function fold_gates_at_random>, num_chunks=None)[source]#
Defines the executor required for Layerwise Richardson Extrapolation as defined in [30].
Note that this method only works for the multivariate extrapolation methods. It does not allows a user to choose which layers in the input circuit will be scaled.
See also
If you would prefer to choose the layers for unitary folding, use
mitiq.zne.scaling.layer_scaling.get_layer_folding()
instead.- Parameters:
input_circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – Circuit to be scaled.executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]) – Executes a circuit and returns a floatdegree (
int
) – Degree of the multivariate polynomial.fold_multiplier (
int
) – Scaling gap value required for unitary folding which is used to generate the scale factor vectors.folding_method (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – Unitary folding method. Default isfold_gates_at_random()
.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.
- Return type:
- Returns:
Error-mitigated expectation value
- mitiq.lre.lre.lre_decorator(degree, fold_multiplier, folding_method=<function fold_gates_at_random>, num_chunks=None)[source]#
Decorator which adds an error-mitigation layer based on layerwise richardson extrapolation (LRE).
- Parameters:
input_circuit – Circuit to be scaled.
executor – Executes a circuit and returns a float
degree (
int
) – Degree of the multivariate polynomial.which (fold_multiplier Scaling gap value required for unitary folding) – is used to generate the scale factor vectors.
folding_method (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – Unitary folding method. Default isfold_gates_at_random()
.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.fold_multiplier (
int
)
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]]- Returns:
Error-mitigated decorator.
- mitiq.lre.lre.mitigate_executor(executor, degree, fold_multiplier, folding_method=<function fold_gates_at_random>, num_chunks=None)[source]#
Returns a modified version of the input executor which is error-mitigated with layerwise richardson extrapolation (LRE).
- Parameters:
input_circuit – Circuit to be scaled.
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]) – Executes a circuit and returns a floatdegree (
int
) – Degree of the multivariate polynomial.which (fold_multiplier Scaling gap value required for unitary folding) – is used to generate the scale factor vectors.
folding_method (
Callable
[[Any
,float
],Any
]) – Unitary folding method. Default isfold_gates_at_random()
.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.fold_multiplier (
int
)
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]- Returns:
Error-mitigated version of the circuit executor.
Functions for layerwise folding of input circuits to allow for multivariate extrapolation as defined in [30].
- mitiq.lre.multivariate_scaling.layerwise_folding.get_scale_factor_vectors(input_circuit, degree, fold_multiplier, num_chunks=None)[source]#
Returns the patterned scale factor vectors required for multivariate extrapolation.
- Args:
input_circuit: Quantum circuit to be scaled. degree: Degree of the multivariate polynomial. fold_multiplier: Scaling gap required by unitary folding. num_chunks: Number of desired approximately equal chunks.
- Returns:
- scale_factor_vectors: A vector of scale factors where each
component in the vector corresponds to the layer in the input circuit.
- mitiq.lre.multivariate_scaling.layerwise_folding.multivariate_layer_scaling(input_circuit, degree, fold_multiplier, num_chunks=None, folding_method=<function fold_gates_at_random>)#
Defines the noise scaling function required for Layerwise Richardson Extrapolation as defined in [30].
Note that this method only works for the multivariate extrapolation methods. It does not allows a user to choose which layers in the input circuit will be scaled.
See also
If you would prefer to choose the layers for unitary folding, use
mitiq.zne.scaling.layer_scaling.get_layer_folding()
instead.- Parameters:
input_circuit (
Circuit
) – Circuit to be scaled.degree (
int
) – Degree of the multivariate polynomial.fold_multiplier (
int
) – Scaling gap required by unitary folding.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.folding_method (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – Unitary folding method. Default isfold_gates_at_random()
.
- Return type:
List
[Circuit
]- Returns:
Multiple folded variations of the input circuit.
- Raises:
ValueError – When the degree for the multinomial is not greater than or equal to 1; when the fold multiplier to scale the circuit is greater than/equal to 1; when the number of chunks for a large circuit is 0 or when the number of chunks in a circuit is greater than the number of layers in the input circuit.
Functions for multivariate richardson extrapolation as defined in [30].
- mitiq.lre.inference.multivariate_richardson.multivariate_richardson_coefficients(input_circuit, degree, fold_multiplier, num_chunks=None)[source]#
Defines the function to find the linear combination coefficients from the sample matrix as required for multivariate extrapolation (defined in [30]).
We use the sample matrix to find the constants of linear combination $c = (c_1, c_2, …, c_M)$ associated with a known vector of noisy expectation values \(z = (\langle O(λ_1)\rangle, \langle O(λ_2)\rangle, ..., \langle O(λ_M)\rangle)^T\).
The coefficients are found through the ratio of the determinants of $M_i$ and the sample matrix. The new matrix $M_i$ is defined by replacing the ith row of the sample matrix with $e_1 = (1, 0, 0,…, 0)$.
- Parameters:
input_circuit (
Circuit
) – Circuit to be scaled.degree (
int
) – Degree of the multivariate polynomial.fold_multiplier (
int
) – Scaling gap required by unitary folding.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.
- Return type:
- Returns:
- List of the evaluated monomial basis terms using the scale factor
vectors.
- mitiq.lre.inference.multivariate_richardson.sample_matrix(input_circuit, degree, fold_multiplier, num_chunks=None)[source]#
Defines the square sample matrix required for multivariate extrapolation as defined in [30].
The number of monomial terms should be equal to the number of scale factor vectors such that the monomial terms define the rows and the scale factor vectors define the columns.
- Parameters:
input_circuit (
Circuit
) – Quantum circuit to be scaled.degree (
int
) – Degree of the multivariate polynomial.fold_multiplier (
int
) – Scaling gap required by unitary folding.num_chunks (
Optional
[int
]) – Number of desired approximately equal chunks. When the number of chunks is the same as the layers in the input circuit, the input circuit is unchanged.
- Return type:
- Returns:
- Matrix of the evaluated monomial basis terms from the scale factor
vectors.
- Raises:
ValueError – When the degree for the multinomial is not greater than or equal to 1; when the fold multiplier to scale the circuit is greater than/equal to 1; when the number of chunks for a large circuit is 0 or when the number of chunks in a circuit is greater than the number of layers in the input circuit.
Pauli Twirling#
- mitiq.pt.pt.add_noise_to_two_qubit_gates(circuit, noise_name, **kwargs)[source]#
Add noise to CNOT and CZ gates on pre-twirled circuits.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – Pre-twirled circuitnoise_name (
str
) – name of noise operator to apply after CNOT and CZ gateskwargs (
float
)
- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]
- mitiq.pt.pt.generate_pauli_twirl_variants(circuit, num_circuits=10, noise_name=None, **kwargs)[source]#
Return the Pauli twirled versions of the input circuit.
Only the $mathrm{CZ}$ and $mathrm{CNOT}$ gates in an input circuit are Pauli twirled as specified in [38].
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – The input circuit on which twirling is applied.num_circuits (
int
) – Number of twirled variants of the circuits.noise_name (
Optional
[str
]) – Name of the noisy operator acting on CNOT and CZ gates. This is useful if the user requires a noisy circuit after twirling. Values allowed: [“bit-flip”, “depolarize”]kwargs (
float
)
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
A list of num_circuits twirled versions of circuit
- 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
,Circuit
]) – 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
,Circuit
]]
- 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
,Circuit
]) – 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
,Circuit
]]
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.combine_results(results, norm, signs)[source]#
Combine expectation values coming from probabilistically sampled circuits.
Warning
The
results
must be in the same order as the circuits were generated.- Parameters:
- Return type:
- Returns:
The PEC estimate of the expectation value.
- 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). [9] [52].
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
,Circuit
]) – The input circuit to execute with error-mitigation.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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 [9]. 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
isFalse
, onlypec_value
is returned.
- mitiq.pec.pec.generate_sampled_circuits(circuit, representations, precision=0.03, num_samples=None, random_state=None, full_output=False)[source]#
Generates a list of sampled circuits based on the given quasi-probability representations.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – The quantum circuit to be sampled.representations (
Sequence
[OperationRepresentation
]) – The quasi-probability representations of the circuit operations.precision (
float
) – The desired precision for the sampling process. Default is 0.03.num_samples (
int
|None
) – The number of samples to generate. If None, the number of samples is deduced based on the precision. Default is None.random_state (
int
|RandomState
|None
) – The random state or seed for reproducibility.full_output (
bool
) – If True, returns the signs and the norm along with the sampled circuits. Default is False.
- Return type:
list
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]] |tuple
[list
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],list
[int
],float
]- Returns:
A list of sampled circuits. If
full_output
is True, also returns a list of signs, the norm.- Raises:
ValueError – If the precision is not within the interval (0, 1].
- 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
,Circuit
]],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 [9]. 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
,Circuit
]],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 [9]. 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
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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, is_qubit_dependent=True)[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
,Circuit
]) – 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 \}\).is_qubit_dependent (
bool
) – If True, the representation corresponds to the operation on the specific qubits defined in ideal_operation. If False, the representation is valid for the same gate even if acting on different qubits from those specified in ideal_operation.
- Return type:
Returns: The optimal OperationRepresentation.
- 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, is_qubit_dependent=True)[source]#
As described in [9], 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 [15] that, under suitable assumptions, this representation is optimal (minimum 1-norm).
- Parameters:
ideal_operation (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – The ideal operation (as a QPROGRAM) to represent.noise_level (
float
) – The noise level (as a float) of the depolarizing channel.is_qubit_dependent (
bool
) – If True, the representation corresponds to the operation on the specific qubits defined in ideal_operation. If False, the representation is valid for the same gate even if acting on different qubits from those specified in ideal_operation.
- 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, is_qubit_dependent=True)[source]#
As described in [9], 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
,Circuit
]) – The ideal operation (as a QPROGRAM) to represent.noise_level (
float
) – The noise level of each depolarizing channel.is_qubit_dependent (
bool
) – If True, the representation corresponds to the operation on the specific qubits defined in ideal_operation. If False, the representation is valid for the same gate even if acting on different qubits from those specified in ideal_operation.
- 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
,Circuit
]) – 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
,Circuit
]) – 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, is_qubit_dependent=True)[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 [16]) 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
,Circuit
]) – 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.is_qubit_dependent (
bool
) – If True, the representation corresponds to the operation on the specific qubits defined in ideal_operation. If False, the representation is valid for the same gate even if acting on different qubits from those specified in ideal_operation.
- 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
,Circuit
]]) – List of ideal operations to be represented by a combination of noisy operations.training_circuits (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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.
- Return type:
- Returns: Mean squared error between the error-mitigated values and
the ideal values, over the training set.
- 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
,Circuit
]]) – List of ideal operations to be represented by a combination of noisy operations.training_circuits (
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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.
- Return type:
- Returns: Mean squared error between the error-mitigated values and
the ideal values, over the training set.
- 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
,Circuit
]]) – The ideal operations to learn the noise model of.circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – 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
,Circuit
]]) – The ideal operations to learn the noise model of.circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – 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
,Circuit
]) – 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
,Circuit
]],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
,Circuit
]) – 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
,Circuit
]],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.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – A short circuit which, when executed on a given noisy quantum computer, generates a noisy channel. It typically contains a single-gate or a short sequence of gates.channel_matrix (
Optional
[ndarray
[Any
,dtype
[complex64
]]]) – Superoperator representation of the noisy channel which is generated when executing the inputcircuit
on the noisy quantum computer.
- Raises:
TypeError – If
ideal
is not aQPROGRAM
.
- property circuit: Circuit#
Returns the circuit of the NoisyOperation as a Cirq circuit.
- property native_circuit: Circuit | pyquil.Program | QuantumCircuit | Circuit | QuantumTape | Circuit#
Returns the circuit used to initialize the NoisyOperation.
- 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
,Circuit
]) – The ideal operation desired to be implemented.basis_expansion – Representation of the ideal operation in a basis of
NoisyOperation
objects.is_qubit_dependent (
bool
) – If True, the representation corresponds to the operation on the specific qubits defined inideal
. If False, the representation is valid for the same gate even if acting on different qubits from those specified inideal
.noisy_operations (
List
[NoisyOperation
])
- Raises:
TypeError – If all keys of
basis_expansion
are not instances ofNoisyOperation
objects.
- property distribution: List[float]#
Returns the probability distribution obtained from taking the absolute value and normalizing the quasi-probability distribution.
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.\]
Quantum Subspace Expansion#
High-level Quantum Susbapce Expansion tools.
- mitiq.qse.qse.execute_with_qse(circuit, executor, check_operators, code_hamiltonian, observable, pauli_string_to_expectation_cache={})[source]#
Function for the calculation of an observable from some circuit of interest to be mitigated with quantum subspace expansion (QSE).
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – Quantum program to execute with error mitigation.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]]) – Executes a circuit and returns a QuantumResult.check_operators (
Sequence
[PauliString
]) – List of check operators that define the stabilizer code space.code_hamiltonian (
Observable
) – Hamiltonian of the code space.observable (
Observable
) – Observable to compute the mitigated expectation value of.pauli_string_to_expectation_cache (
Dict
[PauliString
,complex
]) – Cache for expectation values of Pauli strings used to compute the projector and the observable.
- Return type:
- Returns:
The expectation value estimated with QSE.
- mitiq.qse.qse.mitigate_executor(executor, check_operators, code_hamiltonian, observable, pauli_string_to_expectation_cache={})[source]#
Returns a modified version of the input ‘executor’ which is error-mitigated with quantum subspace expansion (QSE).
- Parameters:
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]) – Executes a circuit and returns a QuantumResult.check_operators (
Sequence
[PauliString
]) – List of check operators that define the stabilizer code space.code_hamiltonian (
Observable
) – Hamiltonian of the code space.observable (
Observable
) – Observable to compute the mitigated expectation value for.pauli_string_to_expectation_cache (
Dict
[PauliString
,complex
]) – Cache for expectation values of Pauli strings used to compute the projector and the observable.
- Return type:
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]- Returns:
The error-mitigated version of the input executor.
- mitiq.qse.qse.qse_decorator(check_operators, code_hamiltonian, observable, pauli_string_to_expectation_cache={})[source]#
Decorator which adds an error-mitigation layer based on quantum subspace expansion (QSE) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a
QuantumResult
.- Parameters:
check_operators (
Sequence
[PauliString
]) – List of check operators that define the stabilizer code space.code_hamiltonian (
Observable
) – Hamiltonian of the code space.observable (
Observable
) – Observable to compute the mitigated expectation value of.pauli_string_to_expectation_cache (
Dict
[PauliString
,complex
]) – Cache for expectation values of Pauli strings used to compute the projector and the observable.
- Return type:
Callable
[[Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],float
]]- Returns:
The error-mitigating decorator to be applied to an executor function.
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
,Circuit
]],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
,Circuit
])
- 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
,Circuit
]],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
,Circuit
]],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
,Circuit
]],MeasurementResult
]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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.combine_results(scale_factors, results, extrapolation_method)[source]#
Computes the error-mitigated expectation value associated to the input results from executing the scaled circuits, via the application of zero-noise extrapolation (ZNE).
- Parameters:
scale_factors (
Sequence
[float
]) – An array of noise scale factors.results (
Sequence
[float
]) – An array storing the results of running the scaled circuits.extrapolation_method (
Callable
[[Sequence
[float
],Sequence
[float
]],float
]) – The function for scaling the noise of a quantum circuit. A list of built-in functions can be found inmitiq.zne.scaling
.
- Return type:
- Returns:
The expectation value estimated with ZNE.
- 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
,Circuit
]) – The input circuit to execute with ZNE.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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
,Circuit
]],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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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
,Circuit
]],float
]- Returns:
The error-mitigated version of the input executor.
- mitiq.zne.zne.scaled_circuits(circuit, scale_factors, scale_method)[source]#
- Given a circuit, scale_factors and a scale_method, outputs a list
of circuits that will be used in ZNE.
- Parameters:
circuit (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]) – The input circuit to execute with ZNE.scale_factors (
list
[float
]) – An array of noise scale factors.scale_method (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – The function for scaling the noise of a quantum circuit. A list of built-in functions can be found inmitiq.zne.scaling
.
- Return type:
list
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
The scaled circuits using the scale_method.
- 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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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
]) – 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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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.
- 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 the number of scale factors is less than 2.
TypeError – If shot_list is provided and has any non-integer values.
- 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
,Circuit
]) – 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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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.
- Return type:
- 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.
- 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
,Circuit
]) – 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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]) – 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, different indices randomly sampled without replacement.
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 [11].
- 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
,Circuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
The function for folding the ith layer.
- mitiq.zne.scaling.layer_scaling.layer_folding(circuit, layers_to_fold)[source]#
Applies a variable amount of folding to select layers of a circuit.
Note that this method only works for the univariate extrapolation methods. It allows a user to choose which layers in the input circuit will be scaled.
See also
If you would prefer to use a multivariate extrapolation method for unitary folding, use
mitiq.lre.multivariate_scaling.layerwise_folding()
instead.The layerwise folding required for multivariate extrapolation is different as the layers in the input circuit have to be scaled in a specific pattern. The required specific pattern for multivariate extrapolation does not allow a user to provide a choice of which layers to fold.
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
,Circuit
]) – 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.
Tools For Error Mitigation#
Benchmarks#
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
,Circuit
]- Returns:
A GHZ circuit acting on
n_qubits
qubits.
Mirror Circuits#
Functions for creating mirror circuits as defined in [1] 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
,Circuit
],Union
[str
,List
[int
]]]- Returns:
A randomized mirror circuit and the bitstring corresponding to a noise free result.
- 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.
Mirror Quantum Volume Circuits#
Functions to create a Mirror Quantum Volume Benchmarking circuit as defined in https://arxiv.org/abs/2303.02108.
- mitiq.benchmarks.mirror_qv_circuits.generate_mirror_qv_circuit(num_qubits, depth, decompose=False, seed=None, return_type=None)[source]#
Generate a mirror quantum volume circuit with the given number of qubits and depth as defined in [3].
The generated circuit consists of a quantum volume circuit up to depth/2 layers followed by an inverse of the quantum volume portion up to depth/2 when depth is an even number.
When depth is odd, the layers will be changed to depth+1.
The ideal output bit-string is a string of zeroes.
- Parameters:
num_qubits (
int
) – The number of qubits in the generated circuit.depth (
int
) – The number of layers 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:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]- Returns:
A quantum volume circuit acting on
num_qubits
qubits.
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 [78]. The notation for eigenvalue register and eigenstate register used to define this function also follows from [78].
- 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
,Circuit
]- Returns:
A Quantum Phase Estimation circuit.
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
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 layers 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
,Circuit
],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.
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, seed=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
.seed (
Optional
[int
]) – A seed for generating randomized benchmarking circuits.
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
A list of randomized benchmarking circuits.
Rotated Randomized Benchmarking Circuits#
Functions for generating rotated randomized benchmarking circuits.
- mitiq.benchmarks.rotated_randomized_benchmarking.generate_rotated_rb_circuits(n_qubits, num_cliffords, theta=None, trials=1, return_type=None, seed=None)[source]#
Generates a list of “rotated” randomized benchmarking circuits. This benchmarking method enables testing QEM techniques in more general scenarios, closer to real-world applications in which expectation values can take arbitrary values.
Rotated randomized bencmarking circuits are randomized benchmarking circuits with an \(R_z(\theta)\) rotation inserted in the middle, such that:
\[C(\theta) = G_n \dots G_{n/2 +1} R_z(\theta)G_{n/2} \dots G_2 G_1\]where \(G_j\) are Clifford elements or Clifford gates.
For most values of the seed, the probability of the zero state is a sinusoidal function of \(\theta\). For some values of the seed the probability of the zero state is 1 for all \(\theta\).
Since (up to factors of 2) we have \(R_z(\theta) =cos(\theta) I + i \ sin(\theta) Z\), the rotated Clifford circuit \(C(\theta)\) can be written as a linear combination of just two Clifford circuits, and therefore it is still easy to classically simulate.
- 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.theta (
Optional
[float
]) – The rotation angle about the \(Z\) axis.trials (
int
) – The number of random circuits to return.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
.seed (
Optional
[int
]) – A seed for generating radomzed benchmarking circuits.
- Return type:
List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]- Returns:
A list of rotated randomized benchmarking circuits.
Randomized Clifford+T Circuits#
- mitiq.benchmarks.randomized_clifford_t_circuit.generate_random_clifford_t_circuit(num_qubits, num_oneq_cliffords, num_twoq_cliffords, num_t_gates, return_type=None, seed=None)[source]#
Generate a random quantum circuit with the given number of qubits, number of one-qubit Cliffords, number of two-qubit Cliffords and number of T gates.
- Parameters:
num_qubits (
int
) – The number of qubits in the generated circuit.num_oneq_cliffords (
int
) – Number of one-qubit Cliffords to be used.num_twoq_cliffords (
int
) – Number of two-qubit Cliffords to be used.num_t_gates (
int
) – Number of T gates to be used.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:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]- Returns:
A quantum circuit acting on
num_qubits
qubits.
W State Circuits#
Functions for creating a linear complexity W-state benchmarking circuit as defined in [4].
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
,Circuit
]],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
,Circuit
]],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.
- 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
,Circuit
])expval_executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],Union
[float
,MeasurementResult
,ndarray
]]])observable (
Optional
[Observable
])
- Return type:
- get_cost()[source]#
Returns the expected number of noisy and ideal expectation values required for calibration.
- run(log=None)[source]#
Runs all the circuits required for calibration.
- Parameters:
log (
Optional
[OutputForm
]) – If set, detailed results of each experiment run by the calibrator are printed. The value corresponds to the format of the information and can be set to “flat” or “cartesian”.- Return type:
- class mitiq.calibration.calibrator.ExperimentResults(strategies, problems)[source]#
Class to store calibration experiment data, and provide helper methods for computing results based on it.
- Parameters:
problems (
List
[BenchmarkProblem
])
- add_result(strategy, problem, *, ideal_val, noisy_val, mitigated_val)[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:
- is_missing_data()[source]#
Method to check if there is any missing data that was expected from the calibration experiments.
- Return type:
- log_results_cartesian()[source]#
Prints the results of the calibrator in cartesian form:
┌──────────────────────────────┬────────────────────────────┬────────────────────────────┐ │ strategy\benchmark │ Type: rb │ Type: ghz │ │ │ Num qubits: 2 │ Num qubits: 2 │ │ │ Circuit depth: 337 │ Circuit depth: 2 │ │ │ Two qubit gate count: 80 │ Two qubit gate count: 1 │ ├──────────────────────────────┼────────────────────────────┼────────────────────────────┤ │ Technique: ZNE │ ✔ │ ✘ │ │ Factory: Richardson │ Noisy error: 0.1128 │ Noisy error: 0.0117 │ │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0501 │ Mitigated error: 0.0439 │ │ Scale method: fold_global │ Improvement factor: 2.2515 │ Improvement factor: 0.2665 │ ├──────────────────────────────┼────────────────────────────┼────────────────────────────┤ │ Technique: ZNE │ ✔ │ ✘ │ │ Factory: Richardson │ Noisy error: 0.1128 │ Noisy error: 0.0117 │ │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0408 │ Mitigated error: 0.0171 │ │ Scale method: fold_global │ Improvement factor: 2.7672 │ Improvement factor: 0.6852 │ └──────────────────────────────┴────────────────────────────┴────────────────────────────┘
- Return type:
- log_results_flat()[source]#
Prints the results of the calibrator in flat form:
┌──────────────────────────┬──────────────────────────────┬────────────────────────────┐ │ benchmark │ strategy │ performance │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: rb │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.101 │ │ Circuit depth: 323 │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0294 │ │ Two qubit gate count: 77 │ Scale method: fold_global │ Improvement factor: 3.4398 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: rb │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.101 │ │ Circuit depth: 323 │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0501 │ │ Two qubit gate count: 77 │ Scale method: fold_global │ Improvement factor: 2.016 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: ghz │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.0128 │ │ Circuit depth: 2 │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0082 │ │ Two qubit gate count: 1 │ Scale method: fold_global │ Improvement factor: 1.561 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: ghz │ Technique: ZNE │ ✘ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.0128 │ │ Circuit depth: 2 │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0137 │ │ Two qubit gate count: 1 │ Scale method: fold_global │ Improvement factor: 0.9369 │ └──────────────────────────┴──────────────────────────────┴────────────────────────────┘
- Return type:
- class mitiq.calibration.calibrator.OutputForm(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
- 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
,Circuit
]) – The input circuit to execute.executor (
Union
[Executor
,Callable
[[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]],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 (
SUPPORTED_PROGRAM_TYPES
) – The circuit type as a string. For supported circuit types see mitiq.SUPPORTED_PROGRAM_TYPES.- Return type:
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]- Returns:
The converted circuit with final measurements.
- class mitiq.calibration.settings.MitigationTechnique(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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.
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
,Circuit
,Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]]],Any
]) – A function which inputs a program and outputs amitiq.QuantumResult
, or inputs a sequence of programs and outputs a sequence ofmitiq.QuantumResult
s.max_batch_size (
int
) – Maximum number of programs that can be sent in a single batch (if the executor is batched).
- 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
,Circuit
,List
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]]) – A single circuit or list of circuits.observable (
Optional
[Observable
]) – Observable O in the expression Tr[ρ O]. If None, theexecutor
must return a float (which corresponds to Tr[ρ O] for a specific, fixed observable O).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:
- 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
,Circuit
,Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]]],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 (
Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
,Sequence
[Union
[Circuit
,Program
,QuantumCircuit
,Circuit
,QuantumTape
,Circuit
]]]) – Circuit or sequence thereof to execute with 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
) – PauliStrings used to define the observable.
Pauli Observable#
- 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
objects can be measured in anymitiq.QPROGRAM
.- Parameters:
Examples
>>> PauliString(spec="IXY") # X(1)*Y(2) >>> PauliString(spec="ZZ", coeff=-0.5) # -0.5*Z(0)*Z(1) >>> PauliString(spec="XZ", support=(10, 17)) # X(10)*Z(17)
- 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
) – PauliStrings to add to the collection.check_precondition (
bool
) – If True, raises an error if some of thePauliString
objects do not qubit-wise commute.
Example
>>> pcol = PauliStringCollection( >>> PauliString(spec="X"), >>> PauliString(spec="IZ", coeff=-2.2) >>> ) >>> print(pcol) # X(0) + (-2.2+0j)*Z(1) >>> print(pcol.support()) # {0, 1} >>> >>> # XZ qubit-wise commutes with X(0) and Z(1), so can be added. >>> print(pcol.can_add(PauliString(spec="XZ"))) # True. >>> pcol.add(PauliString(spec="XZ")) >>> print(pcol) # X(0) + (-2.2+0j)*Z(1) + X(0)*Z(1) >>> >>> # Z(0) doesn't qubit-wise commute with X(0), so can't be added. >>> print(pcol.can_add(PauliString(spec="Z"))) # False.
Raw#
Run experiments without error mitigation (raw results)#
Run experiments without error mitigation.
Core Utilities#
Circuit types and result types#
- mitiq.typing.QPROGRAM#
alias of
Circuit
|Program
|QuantumCircuit
|Circuit
|QuantumTape
|Circuit
- mitiq.typing.QuantumResult#
alias of
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
.
Example
>>> mr = MeasurementResult(["001", "010", "001"]) >>> mr.get_counts() {'001': 2, '010': 1}
Warning
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
.