APIdoc¶
Benchmarks¶
MaxCut¶
This module contains methods for benchmarking mitiq error extrapolation against a standard QAOA for MAXCUT.

mitiq.benchmarks.maxcut.
make_maxcut
(graph, noise=0, scale_noise=None, factory=None)[source]¶ Makes an executor that evaluates the QAOA ansatz at a given beta and gamma parameters.
 Parameters
graph (
List
[Tuple
[int
,int
]]) – The MAXCUT graph as a list of edges with integer labelled nodes.noise (
float
) – The level of depolarizing noise.scale_noise (
Optional
[Callable
]) – The noise scaling method for ZNE.factory (
Optional
[Factory
]) – The factory to use for ZNE.
 Return type
Tuple
[Callable
[[ndarray
],float
],Callable
[[ndarray
],Circuit
],ndarray
] Returns
 (ansatz_eval, ansatz_maker, cost_obs) as a triple. Here
 ansatz_eval: function that evalutes the maxcut ansatz on
the noisy cirq backend.
ansatz_maker: function that returns an ansatz circuit. cost_obs: the cost observable as a dense matrix.

mitiq.benchmarks.maxcut.
make_noisy_backend
(noise, obs)[source]¶ Helper function to match mitiq’s backend type signature.
 Parameters
noise (
float
) – The level of depolarizing noise.obs (
ndarray
) – The observable that the backend should measure.
 Return type
Callable
[[Circuit
],float
] Returns
A mitiq backend function.

mitiq.benchmarks.maxcut.
run_maxcut
(graph, x0, noise=0, scale_noise=None, factory=None, verbose=True)[source]¶  Solves MAXCUT using QAOA on a cirq wavefunction simulator using a
NelderMead optimizer.
 Parameters
graph (
List
[Tuple
[int
,int
]]) – The MAXCUT graph as a list of edges with integer labelled nodes.x0 (
ndarray
) – The initial parameters for QAOA [betas, gammas]. The size of x0 determines the number of p steps.noise (
float
) – The level of depolarizing noise.scale_noise (
Optional
[Callable
]) – The noise scaling method for ZNE.factory (
Optional
[Factory
]) – The factory to use for ZNE.
 Return type
Tuple
[float
,ndarray
,List
] Returns
A triple of the minimum cost, the values of beta and gamma that obtained that cost, and a list of costs at each iteration step.
Example
Run MAXCUT with 2 steps such that betas = [1.0, 1.1] and gammas = [1.4, 0.7] on a graph with four edges and four nodes.
>>> graph = [(0, 1), (1, 2), (2, 3), (3, 0)] >>> fun,x,traj = run_maxcut(graph, x0=[1.0, 1.1, 1.4, 0.7]) Optimization terminated successfully. Current function value: 4.000000 Iterations: 108 Function evaluations: 188
 Parameters
verbose (
bool
) –
Random Circuits¶
Contains methods used for testing mitiq’s performance on random circuits.

mitiq.benchmarks.random_circuits.
rand_circuit_zne
(n_qubits, depth, trials, noise, fac=None, scale_noise=<function fold_gates_at_random>, op_density=0.99, silent=True, seed=None)[source]¶ Benchmarks a zeronoise extrapolation method and noise scaling executor by running on randomly sampled quantum circuits.
 Parameters
n_qubits (
int
) – The number of qubits.depth (
int
) – The depth in moments of the random circuits.trials (
int
) – The number of random circuits to average over.noise (
float
) – The noise level of the depolarizing channel for simulation.fac (
Optional
[Factory
]) – The Factory giving the extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
]]) – The method for scaling noise, e.g. fold_gates_at_randomop_density (
float
) – The expected proportion of qubits that are acted on in any moment.silent (
bool
) – If False will print out statements every tenth trial to track progress.seed (
Optional
[int
]) – Optional seed for random number generator.
 Return type
 Returns
The triple (exacts, unmitigateds, mitigateds) where each is a list whose values are the expectations of that trial in noiseless, noisy, and errormitigated runs respectively.

mitiq.benchmarks.random_circuits.
sample_projector
(n_qubits, seed=None)[source]¶ Constructs a projector on a random computational basis state of n_qubits.
 Parameters
n_qubits (
int
) – A number of qubitsseed (
Union
[None
,int
,RandomState
]) – Optional seed for random number generator. It can be an integer or a numpy.random.RandomState object.
 Return type
 Returns
A random computational basis projector on n_qubits. E.g., for two qubits this could be np.diag([0, 0, 0, 1]), corresponding to the projector on the 11> state.
Randomized Benchmarking¶
Contains methods used for testing mitiq’s performance on randomized benchmarking circuits.

mitiq.benchmarks.randomized_benchmarking.
rb_circuits
(n_qubits, num_cliffords, trials, qubit_labels=None)[source]¶ Generates a set 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 2num_cliffords (
List
[int
]) – A list of numbers of Clifford group elements in the random circuits. This is proportional to the eventual depth per circuit.trials (
int
) – The number of random circuits at each num_cfd.qubit_labels (
Optional
[List
[int
]]) –
 Return type
List
[Circuit
] Returns
A list of randomized benchmarking circuits.
Utils¶
Utility functions for benchmarking.

mitiq.benchmarks.utils.
noisy_simulation
(circ, noise, obs)[source]¶ Simulates a circuit with depolarizing noise at level NOISE.
 Parameters
circ (
Circuit
) – The quantum program as a cirq object.noise (
float
) – The level of depolarizing noise.obs (
ndarray
) – The observable that the backend should measure.
 Return type
float
 Returns
The observable’s expectation value.
Mitiq  PyQuil¶
PyQuil Utils¶
pyQuil utitility functions.

mitiq.mitiq_pyquil.pyquil_utils.
add_depolarizing_noise
(pq, noise)[source]¶ Returns a quantum program with depolarizing channel noise.
 Parameters
pq (
Program
) – Quantum program asProgram
.noise (
float
) – Noise constant for depolarizing channel.
 Returns
Quantum program with added noise.
 Return type
pq

mitiq.mitiq_pyquil.pyquil_utils.
measure
(circuit, qid)[source]¶ Returns a circuit adding a register for readout results.
 Parameters
circuit – Quantum circuit as
Program
.qid – position of the measurement in the circuit.
 Returns
Quantum program with added measurement.

mitiq.mitiq_pyquil.pyquil_utils.
random_identity_circuit
(depth=None)[source]¶ Returns a singlequbit identity circuit based on Pauli gates.

mitiq.mitiq_pyquil.pyquil_utils.
run_program
(pq, shots=500)[source]¶ Returns the expectation value of a circuit run several times.
 Parameters
pq (
Program
) – Quantum circuit asProgram
.shots (
int
) – (Default: 500) Number of shots the circuit is run.
 Returns
Expectation value.
 Return type
expval

mitiq.mitiq_pyquil.pyquil_utils.
run_with_noise
(circuit, noise, shots)[source]¶ Returns the expectation value of a circuit run several times with noise.
 Parameters
circuit (
Program
) – Quantum circuit asProgram
.noise (
float
) – Noise constant for depolarizing channel.shots (
int
) – Number of shots the circuit is run.
 Returns
Expectation value.
 Return type
expval
Mitiq  Qiskit¶
Conversions¶
Functions to convert between Mitiq’s internal circuit representation and Qiskit’s circuit representation.

mitiq.mitiq_qiskit.conversions.
from_qasm
(qasm)[source]¶ Returns a Mitiq circuit equivalent to the input QASM string.
 Parameters
qasm (
str
) – QASM string to convert to a Mitiq circuit. Return type
Circuit
 Returns
Mitiq circuit representation equivalent to the input QASM string.

mitiq.mitiq_qiskit.conversions.
from_qiskit
(circuit)[source]¶ Returns a Mitiq circuit equivalent to the input Qiskit circuit.
 Parameters
circuit (
QuantumCircuit
) – Qiskit circuit to convert to a Mitiq circuit. Return type
Circuit
 Returns
Mitiq circuit representation equivalent to the input Qiskit circuit.

mitiq.mitiq_qiskit.conversions.
to_qasm
(circuit)[source]¶ Returns a QASM string representing the input Mitiq circuit.
 Parameters
circuit (
Circuit
) – Mitiq circuit to convert to a QASM string. Returns
QASM string equivalent to the input Mitiq circuit.
 Return type
QASMType

mitiq.mitiq_qiskit.conversions.
to_qiskit
(circuit)[source]¶ Returns a Qiskit circuit equivalent to the input Mitiq circuit.
 Parameters
circuit (
Circuit
) – Mitiq circuit to convert to a Qiskit circuit. Return type
QuantumCircuit
 Returns
Qiskit.QuantumCircuit object equivalent to the input Mitiq circuit.
Qiskit Utils¶
Qiskit utility functions.

mitiq.mitiq_qiskit.qiskit_utils.
random_one_qubit_identity_circuit
(num_cliffords)[source]¶ Returns a singlequbit identity circuit.
 Parameters
num_cliffords (int) – Number of cliffords used to generate the circuit.
 Returns
Quantum circuit as a
qiskit.QuantumCircuit
object. Return type
circuit

mitiq.mitiq_qiskit.qiskit_utils.
run_program
(pq, shots=100, seed=None)[source]¶ Runs a singlequbit circuit for multiple shots and returns the expectation value of the ground state projector.
 Parameters
pq (
QuantumCircuit
) – Quantum circuit.shots (
int
) – Number of shots to run the circuit on the backend.seed (
Optional
[int
]) – Optional seed for qiskit simulator.
 Returns
expected value.
 Return type
expval

mitiq.mitiq_qiskit.qiskit_utils.
run_with_noise
(circuit, noise, shots, seed=None)[source]¶ Runs the quantum circuit with a depolarizing channel noise model.
 Parameters
circuit (
QuantumCircuit
) – Ideal quantum circuit.noise (
float
) – Noise constant going into depolarizing_error.shots (
int
) – The Number of shots to run the circuit on the backend.seed (
Optional
[int
]) – Optional seed for qiskit simulator.
 Returns
expected values.
 Return type
expval

mitiq.mitiq_qiskit.qiskit_utils.
scale_noise
(pq, param)[source]¶ Scales the noise in a quantum circuit of the factor param.
 Parameters
pq (
QuantumCircuit
) – Quantum circuit.noise – Noise constant going into depolarizing_error.
shots – Number of shots to run the circuit on the backend.
param (
float
) –
 Returns
quantum circuit as a
qiskit.QuantumCircuit
object. Return type
pq
Utils¶
Utility functions.
Zero Noise Extrapolation¶
Zero Noise Extrapolation (HighLevel Tools)¶
Highlevel zeronoise extrapolation tools.

mitiq.zne.zne.
execute_with_zne
(qp, executor, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]¶ Returns the zeronoise extrapolated expectation value that is computed by running the quantum program qp with the executor function.
 Parameters
qp (
Union
[Circuit
,Program
,QuantumCircuit
]) – Quantum program to execute with error mitigation.executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
]],float
]) – Executes a circuit and returns an expectation value.factory (
Optional
[Factory
]) – Factory object that determines the zeronoise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
]]) – 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
float

mitiq.zne.zne.
mitigate_executor
(executor, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]¶ Returns an errormitigated 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 zeronoise extrapolation to produce a mitigated expectation value.
 Parameters
executor (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
]],float
]) – Executes a circuit and returns an expectation value.factory (
Optional
[Factory
]) – Factory object determining the zeronoise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
]]) – 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
]],float
]

mitiq.zne.zne.
zne_decorator
(factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]¶ Decorator which adds error mitigation to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns an expectation value.
 Parameters
factory (
Optional
[Factory
]) – Factory object determining the zeronoise extrapolation method.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
]]) – 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
]],float
]],Callable
[[Union
[Circuit
,Program
,QuantumCircuit
]],float
]]
Inference and Extrapolation: Factories¶
Classes corresponding to different zeronoise 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 zeronoise 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 nonlinear 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 (if known) of the expectation value. Default is None.avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a nonlinear 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 illconditioned.

is_converged
()[source]¶ Returns True if all the needed expectation values have been computed, else False.
 Return type
bool

class
mitiq.zne.inference.
BatchedFactory
(scale_factors, shot_list=None)[source]¶ Abstract class of a nonadaptive Factory.
This is initialized with a given batch of “scale_factors”. The “self.next” method trivially iterates over the elements of “scale_factors” in a nonadaptive way. Convergence is achieved when all the correpsonding expectation values have been measured.
Specific (nonadaptive) zeronoise extrapolation algorithms can be derived from this class by overriding the “self.reduce” and (if necessary) the “__init__” 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.
IndexError – If an iteration step fails.

exception
mitiq.zne.inference.
ConvergenceWarning
[source]¶ Warning raised by
Factory
objects when their iterate method fails to converge.

class
mitiq.zne.inference.
ExpFactory
(scale_factors, asymptote=None, avoid_log=False, shot_list=None)[source]¶ Factory object implementing a zeronoise 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 nonlinear optimization.
If y(x>inf) is given and avoid_log=False, the exponential model is mapped into a linear model by logarithmic transformation.
 Parameters
scale_factors (
Sequence
[float
]) – Sequence of noise scale factors at which expectation values should be measured.asymptote (
Optional
[float
]) – Infinitenoise limit (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a nonlinear 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 illconditioned.

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 illconditioned.

class
mitiq.zne.inference.
Factory
[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 zeronoise extrapolation algorithms, adaptive or nonadaptive, are derived from this class.
A Factory object is not supposed to directly perform any quantum computation, only the classical results of quantum experiments are processed by it.

get_expectation_values
()[source]¶ Returns the expectation values computed by the factory.
 Return type

get_scale_factors
()[source]¶ Returns the scale factors at which the factory has computed expectation values.
 Return type

abstract
is_converged
()[source]¶ Returns True if all needed expectation values have been computed, else False.
 Return type
bool

iterate
(noise_to_expval, max_iterations=100)[source]¶ Evaluates a sequence of expectation values until enough data is collected (or iterations reach “max_iterations”).
 Parameters
noise_to_expval (
Callable
[…,float
]) – Function mapping a noise scale factor to an expectation value. If shot_list is not None, “shot” must be an argument of the function.max_iterations (
int
) – Maximum number of iterations (optional). Default: 100.
 Raises
ConvergenceWarning – If iteration loop stops before convergence.
 Return type

abstract
next
()[source]¶ Returns a dictionary of parameters to execute a circuit at.
 Return type
Dict
[str
,float
]

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.
 Parameters
instack_val (
dict
) –outstack_val (
float
) –
 Return type
None

reset
()[source]¶ Resets the instack, outstack, and optimal parameters of the Factory to empty lists.
 Return type
None

run
(qp, executor, scale_noise, 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 to mitigate.executor (
Callable
[…,float
]) – Function executing a circuit; returns an expectation value. If shot_list is not None, then “shot” must be an additional argument of the executor.scale_noise (
Callable
[[Union
[Circuit
,Program
,QuantumCircuit
],float
],Union
[Circuit
,Program
,QuantumCircuit
]]) – 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


class
mitiq.zne.inference.
LinearFactory
(scale_factors, shot_list=None)[source]¶ Factory object implementing zeronoise 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 illconditioned.
Example
>>> NOISE_LEVELS = [1.0, 2.0, 3.0] >>> fac = LinearFactory(NOISE_LEVELS)

class
mitiq.zne.inference.
PolyExpFactory
(scale_factors, order, asymptote=None, avoid_log=False, shot_list=None)[source]¶ Factory object implementing a zeronoise extrapolation algorithm assuming an (almost) exponential ansatz with a non linear exponent, i.e.:
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 nonlinear 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
]) – Infinitenoise limit (optional argument).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a nonlinear 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 illconditioned.

reduce
()[source]¶ Returns the zeronoise limit found by fitting the ansatz.
Stores the optimal parameters for the fit in self.opt_params.
 Return type
float

static
static_reduce
(instack, exp_values, asymptote, order, avoid_log=False, eps=1e06)[source]¶ Determines the zeronoise limit assuming an exponential ansatz.
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 nonlinear optimization.
If asymptote is given and avoid_log=False, a linear fit with respect to z(x) := log[sign * (y(x)  asymptote)] is performed.
This static method is equivalent to the “self.reduce” method of PolyExpFactory, but can be called also by other factories which are related to PolyExpFactory, e.g., ExpFactory, AdaExpFactory.
 Parameters
instack (
List
[dict
]) – The array of input dictionaries, where each dictionary is supposed to have the key “scale_factor”.exp_values (
List
[float
]) – The array of expectation values.asymptote (
Optional
[float
]) – y(x>inf).order (
int
) – Extrapolation order (degree of the polynomial z(x)).avoid_log (
bool
) – If set to True, the exponential model is not linearized with a logarithm and a nonlinear fit is applied even if asymptote is not None. The default value is False.eps (
float
) – Epsilon to regularize log(sign (instack  asymptote)) when the argument is to close to zero or negative.
 Returns
 Where “znl” is the zeronoiselimit and “params”
are the optimal fitting parameters.
 Return type
(znl, params)
 Raises
ValueError – If data is not consistent with the extrapolation model.
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is illconditioned.

class
mitiq.zne.inference.
PolyFactory
(scale_factors, order, shot_list=None)[source]¶ Factory object implementing a zeronoise 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 illconditioned.
Note
RichardsonFactory and LinearFactory are special cases of PolyFactory.

class
mitiq.zne.inference.
RichardsonFactory
(scale_factors, shot_list=None)[source]¶ Factory object implementing Richardson’s 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 illconditioned.

mitiq.zne.inference.
mitiq_curve_fit
(ansatz, scale_factors, exp_values, init_params=None)[source]¶ This is a wrapping of the scipy.optimize.curve_fit function with custom errors and warnings. It is used to make a nonlinear fit.
 Parameters
ansatz (
Callable
[…,float
]) – The model function used for zeronoise 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.
 Returns
The array of optimal parameters.
 Return type
opt_params
 Raises
ExtrapolationError – If the extrapolation fit fails.
ExtrapolationWarning – If the extrapolation fit is illconditioned.

mitiq.zne.inference.
mitiq_polyfit
(scale_factors, exp_values, deg, weights=None)[source]¶ This is a wrapping of the numpy.polyfit function with custom warnings. It is used to make a polynomial fit.
 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.
 Returns
The array of optimal parameters.
 Return type
opt_params
 Raises
ExtrapolationWarning – If the extrapolation fit is illconditioned.
Noise Scaling: Unitary Folding¶
Functions for local and global unitary folding on supported circuits.

mitiq.zne.scaling.
convert_from_mitiq
(circuit, conversion_type)[source]¶ Converts a mitiq circuit to a type specificed by the conversion type.
 Parameters
circuit (
Circuit
) – Mitiq circuit to convert.conversion_type (
str
) – String specifier for the converted circuit type.
 Return type
Union
[Circuit
,Program
,QuantumCircuit
]

mitiq.zne.scaling.
convert_to_mitiq
(circuit)[source]¶ Converts any valid input circuit to a mitiq circuit.
 Parameters
circuit (
Union
[Circuit
,Program
,QuantumCircuit
]) – Any quantum circuit object supported by mitiq. See mitiq.SUPPORTED_PROGRAM_TYPES. Raises
UnsupportedCircuitError – If the input circuit is not supported.
 Returns
Mitiq circuit equivalent to input circuit. input_circuit_type: Type of input circuit represented by a string.
 Return type
circuit

mitiq.zne.scaling.
converter
(fold_method)[source]¶ Decorator for handling conversions.
 Parameters
fold_method (
Callable
) – Return type
Callable

mitiq.zne.scaling.
fold_gates_at_random
(circuit, scale_factor, seed=None, **kwargs)[source]¶ Returns a folded circuit by applying the map G > G G^dag G to a random subset of gates in the input circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
 Parameters
circuit (
Union
[Circuit
,Program
,QuantumCircuit
]) – Circuit to fold.scale_factor (
float
) – Factor to scale the circuit by. Any real number >= 1.seed (
Optional
[int
]) – [Optional] Integer seed for random number generator.
 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.
“H”  Hadamard “X”  Pauli X “Y”  Pauli Y “Z”  Pauli Z “I”  Identity “CNOT”  CNOT “CZ”  CZ gate “TOFFOLI”  Toffoli gate “single”  All single qubit gates “double”  All twoqubit gates “triple”  All threequbit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all singlequbit 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.
fold_gates_from_left
(circuit, scale_factor, **kwargs)[source]¶ Returns a new folded circuit by applying the map G > G G^dag G to a subset of gates of the input circuit, starting with gates at the left (beginning) of the circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
 Parameters
circuit (
Union
[Circuit
,Program
,QuantumCircuit
]) – Circuit to fold.scale_factor (
float
) – Factor to scale the circuit by. Any real number >= 1.
 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.
“H”  Hadamard “X”  Pauli X “Y”  Pauli Y “Z”  Pauli Z “I”  Identity “CNOT”  CNOT “CZ”  CZ gate “TOFFOLI”  Toffoli gate “single”  All single qubit gates “double”  All twoqubit gates “triple”  All threequbit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all singlequbit 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.
fold_gates_from_right
(circuit, scale_factor, **kwargs)[source]¶ Returns a new folded circuit by applying the map G > G G^dag G to a subset of gates of the input circuit, starting with gates at the right (end) of the circuit.
The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.
 Parameters
circuit (
Union
[Circuit
,Program
,QuantumCircuit
]) – Circuit to fold.scale_factor (
float
) – Factor to scale the circuit by. Any real number >= 1.
 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.
“H”  Hadamard “X”  Pauli X “Y”  Pauli Y “Z”  Pauli Z “I”  Identity “CNOT”  CNOT “CZ”  CZ gate “TOFFOLI”  Toffoli gate “single”  All single qubit gates “double”  All twoqubit gates “triple”  All threequbit gates
Keys for specific gates override values set by “single”, “double”, and “triple”.
For example, fidelities = {“single”: 1.0, “H”, 0.99} sets all singlequbit 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.
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
circuit (
Union
[Circuit
,Program
,QuantumCircuit
]) – Circuit to fold.scale_factor (
float
) – Factor to scale the circuit by.
 Keyword Arguments
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