# API-doc¶

## 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, int], 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

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=None, op_density=0.99, silent=True, seed=None)[source]

Benchmarks a zero-noise 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 (Factory) – The Factory giving the extrapolation method.

• scale_noise (Callable[[Union[ForwardRef, ForwardRef, ForwardRef], float], Union[ForwardRef, ForwardRef, ForwardRef]]) – The method for scaling noise, e.g. fold_gates_at_random

• op_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

Tuple[ndarray, ndarray, ndarray]

Returns

The triple (exacts, unmitigateds, mitigateds) where each is a list whose values are the expectations of that trial in noiseless, noisy, and error-mitigated 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 qubits

• seed (Union[None, int, RandomState]) – Optional seed for random number generator. It can be an integer or a numpy.random.RandomState object.

Return type

ndarray

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)[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 2

• num_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.

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 as Program.

• noise (float) – Noise constant for depolarizing channel.

Returns

Return type

pq

mitiq.mitiq_pyquil.pyquil_utils.measure(circuit, qid)[source]

Parameters
• circuit – Quantum circuit as Program.

• qid – position of the measurement in the circuit.

Returns

mitiq.mitiq_pyquil.pyquil_utils.random_identity_circuit(depth=None)[source]

Returns a single-qubit 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 as Program.

• 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 as Program.

• noise (float) – Noise constant for depolarizing channel.

• shots (int) – Number of shots the circuit is run.

Returns

Expectation value.

Return type

expval

mitiq.mitiq_pyquil.pyquil_utils.scale_noise(pq, param)[source]

Returns a circuit rescaled by the depolarizing noise parameter.

Parameters
• pq (Program) – Quantum circuit as Program.

• param (float) – noise scaling.

Return type

Program

Returns

## 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 single-qubit 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 single-qubit 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 back-end.

• 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 back-end.

• 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 back-end.

• param (float) –

Returns

quantum circuit as a qiskit.QuantumCircuit object.

Return type

pq

## Utils¶

Utility functions.

## Zero Noise Extrapolation¶

### Zero Noise Extrapolation (High-Level Tools)¶

High-level zero-noise 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 zero-noise extrapolated expectation value that is computed by running the quantum program qp with the executor function.

Parameters
• qp (Union[ForwardRef, ForwardRef, ForwardRef]) – Quantum program to execute with error mitigation.

• executor (Callable[[Union[ForwardRef, ForwardRef, ForwardRef]], float]) – Executes a circuit and returns an expectation value.

• factory (Factory) – Factory object that determines the zero-noise extrapolation method.

• scale_noise (Callable[[Union[ForwardRef, ForwardRef, ForwardRef], float], Union[ForwardRef, ForwardRef, ForwardRef]]) – 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 error-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 zero-noise extrapolation to produce a mitigated expectation value.

Parameters
• executor (Callable[[Union[ForwardRef, ForwardRef, ForwardRef]], float]) – Executes a circuit and returns an expectation value.

• factory (Factory) – Factory object determining the zero-noise extrapolation method.

• scale_noise (Callable[[Union[ForwardRef, ForwardRef, ForwardRef], float], Union[ForwardRef, ForwardRef, ForwardRef]]) – 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[ForwardRef, ForwardRef, ForwardRef]], 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 (Factory) – Factory object determining the zero-noise extrapolation method.

• scale_noise (Callable[[Union[ForwardRef, ForwardRef, ForwardRef], float], Union[ForwardRef, ForwardRef, ForwardRef]]) – 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[ForwardRef, ForwardRef, ForwardRef]], float]

### 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 (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 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.

is_converged()[source]

Returns True if all the needed expectation values have been computed, else False.

Return type

bool

next()[source]

Returns a dictionary of parameters to execute a circuit at.

Return type

float

reduce()[source]

Returns the zero-noise limit.

Return type

float

class mitiq.zne.inference.BatchedFactory(scale_factors, shot_list=None)[source]

Abstract class of a non-adaptive 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 non-adaptive way. Convergence is achieved when all the correpsonding expectation values have been measured.

Specific (non-adaptive) zero-noise 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.

is_converged()[source]

Returns True if all needed expectation values have been computed, else False.

Return type

bool

next()[source]

Returns a dictionary of parameters to execute a circuit at.

Return type

float

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

reduce()[source]

Returns the zero-noise limit

Return type

float

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 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, adaptive or non-adaptive, 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

ndarray

get_scale_factors()[source]

Returns the scale factors at which the factory has computed expectation values.

Return type

ndarray

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], 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

Factory

abstract next()[source]

Returns a dictionary of parameters to execute a circuit at.

Return type

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

abstract reduce()[source]

Returns the extrapolation to the zero-noise limit.

Return type

float

reset()[source]

Resets the instack and outstack of the Factory to empty values.

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[ForwardRef, ForwardRef, ForwardRef]) – Circuit to mitigate.

• executor (Callable[[Union[ForwardRef, ForwardRef, ForwardRef]], 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[ForwardRef, ForwardRef, ForwardRef], float], Union[ForwardRef, ForwardRef, ForwardRef]]) – 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

Factory

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.

Example

>>> NOISE_LEVELS = [1.0, 2.0, 3.0]
>>> fac = LinearFactory(NOISE_LEVELS)

reduce()[source]

Determines, with a least squared method, the line of best fit associated to the data points. The intercept is returned.

Return type

float

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, 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 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]) – 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.

reduce()[source]

Returns the zero-noise limit.

Return type

float

static static_reduce(instack, exp_values, asymptote, order, avoid_log=False, eps=1e-06)[source]

Determines the zero-noise limit, assuming an exponential ansatz: y(x) = a + sign * exp(z(x)), where z(x) is a polynomial.

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.

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.

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 non-linear 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 zero-noise-limit 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 ill-conditioned.

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.

reduce()[source]

Determines with a least squared method, the polynomial of degree equal to “self.order” which optimally fits the input data. The zero-noise limit is returned.

Return type

float

static static_reduce(instack, exp_values, order)[source]

Determines with a least squared method, the polynomial of degree equal to ‘order’ which optimally fits the input data. The zero-noise limit is returned.

This static method is equivalent to the “self.reduce” method of PolyFactory, but can be called also by other factories which are particular cases of PolyFactory, e.g., LinearFactory and RichardsonFactory.

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.

• order (int) – Extrapolation order (degree of the polynomial fit). It cannot exceed len(scale_factors) - 1.

Raises
• ValueError – If data is not consistent with the extrapolation model.

• ExtrapolationWarning – If the extrapolation fit is ill-conditioned.

Return type

float

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 ill-conditioned.

reduce()[source]

Returns the Richardson’s extrapolation to the zero-noise limit.

Return type

float

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 non-linear fit.

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 (List[float]) – The array of noise scale factors.

• exp_values (List[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
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 (List[float]) – The array of noise scale factors.

• exp_values (List[float]) – The array of expectation values.

• deg (int) – The degree of the polynomial fit.

• weights (Optional[List[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 ill-conditioned.

### Noise Scaling: Unitary Folding¶

Functions for local and global unitary folding on supported circuits.

exception mitiq.zne.scaling.UnfoldableCircuitError[source]
exception mitiq.zne.scaling.UnfoldableGateError[source]
exception mitiq.zne.scaling.UnsupportedCircuitError[source]
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[ForwardRef, ForwardRef, ForwardRef]

mitiq.zne.scaling.convert_to_mitiq(circuit)[source]

Converts any valid input circuit to a mitiq circuit.

Parameters

circuit (Union[ForwardRef, ForwardRef, ForwardRef]) – 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[ForwardRef, ForwardRef, ForwardRef]) – 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 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.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[ForwardRef, ForwardRef, ForwardRef]) – 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 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.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[ForwardRef, ForwardRef, ForwardRef]) – 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 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.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[ForwardRef, ForwardRef, ForwardRef]) – 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

mitiq.zne.scaling.squash_moments(circuit)[source]

Returns a copy of the input circuit with all gates squashed into as few moments as possible.

Parameters

circuit (Circuit) – Circuit to squash moments of.

Return type

Circuit