# API-doc¶

## Benchmarks¶

### MaxCut¶

Methods for benchmarking zero-noise extrapolation on MaxCut-QAOA.

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
Return type
Returns

(ansatz_eval, ansatz_maker, cost_obs) as a triple where

• 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.run_maxcut(graph, x0, noise=0, scale_noise=None, factory=None, optimizer='Nelder-Mead', verbose=False)[source]

Optimizes MaxCut cost function on the given graph using QAOA.

Parameters
Return type
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.

>>> from mitiq.benchmarks.maxcut import run_maxcut
>>> graph = [(0, 1), (1, 2), (2, 3), (3, 0)]
>>> x0 = [1.0, 1.1, 1.4, 0.7]
>>> fun, x, traj = run_maxcut(graph, x0, verbose=True)
Optimization terminated successfully.
Current function value: -4.000000
Iterations: 108
Function evaluations: 188


### 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 zero-noise extrapolation method and noise scaling executor by running on randomly sampled quantum circuits.

Parameters
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 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
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 $$\left|11\right\rangle$$ state.

### Randomized Benchmarking¶

Functions for generating randomized benchmarking circuits.

mitiq.benchmarks.randomized_benchmarking.generate_rb_circuits(n_qubits, num_cliffords, trials=1, return_type=None)[source]

Returns a list of randomized benchmarking circuits, i.e. circuits that are equivalent to the identity.

Parameters
• n_qubits (int) – The number of qubits. Can be either 1 or 2.

• num_cliffords (int) – The number of Clifford group elements in the random circuits. This is proportional to the depth per circuit.

• trials (int) – The number of random circuits at each num_cfd.

• return_type (Optional[str]) – String which specifies the type of the returned circuits. See the keys of mitiq.SUPPORTED_PROGRAM_TYPES for options. If None, the returned circuits have type cirq.Circuit.

Return type

List[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]

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.

## Clifford Data Regression¶

Functions for mapping circuits to (near) Clifford circuits.

mitiq.cdr.clifford_training_data.count_non_cliffords(circuit)[source]

Returns the number of non-Clifford operations in the circuit. Assumes the circuit consists of only Rz, Rx, and CNOT operations.

Parameters

circuit (Circuit) – Circuit to count the number of non-Clifford operations in.

Return type

int

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

In the Clifford Data Regression (CDR) method [Czarnik2020], 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'.

Czarnik2020

: Piotr Czarnik, Andrew Arramsmith, Patrick Coles, Lukasz Cincio, “Error mitigation with Clifford quantum circuit data,” (https://arxiv.org/abs/2005.10189).

Return type

List[Circuit]

mitiq.cdr.clifford_training_data.is_clifford(circuit)[source]

Returns True if the input argument is Clifford, else False.

Parameters

circuit (Circuit) – A single operation, list of operations, or circuit.

Return type

bool

See Ref. [28] for more details on these methods.

## Mitiq - Braket¶

### Conversions¶

mitiq.interface.mitiq_braket.conversions.from_braket(circuit)[source]

Returns a Cirq circuit equivalent to the input Braket circuit.

Note: The returned Cirq circuit acts on cirq.LineQubit’s with indices equal to the qubit indices of the Braket circuit.

Parameters

circuit (Circuit) – Braket circuit to convert to a Cirq circuit.

Return type

Circuit

mitiq.interface.mitiq_braket.conversions.to_braket(circuit)[source]

Returns a Braket circuit equivalent to the input Cirq circuit.

Parameters

circuit (Circuit) – Cirq circuit to convert to a Braket circuit.

Return type

Circuit

## Mitiq - Cirq¶

### Cirq Utils¶

Cirq utility functions.

mitiq.interface.mitiq_cirq.cirq_utils.execute(circuit, obs)[source]

Simulates noiseless wavefunction evolution and returns the expectation value of some observable.

Parameters
• circuit (Circuit) – The input Cirq circuit.

• obs (ndarray) – The observable to measure as a NumPy array.

Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_cirq.cirq_utils.execute_with_depolarizing_noise(circuit, obs, noise)[source]

Simulates a circuit with depolarizing noise at level noise.

Parameters
• circuit (Circuit) – The input Cirq circuit.

• obs (ndarray) – The observable to measure as a NumPy array.

• noise (float) – The depolarizing noise as a float, i.e. 0.001 is 0.1% noise.

Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_cirq.cirq_utils.execute_with_shots(circuit, obs, shots)[source]

Simulates noiseless wavefunction evolution and returns the expectation value of a PauliString observable.

Parameters
Return type
Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_cirq.cirq_utils.execute_with_shots_and_depolarizing_noise(circuit, obs, noise, shots)[source]

Simulates a circuit with depolarizing noise at level noise.

Parameters
Return type
Returns

The expectation value of obs as a float.

## Mitiq - PyQuil¶

### Conversions¶

Functions to convert between Mitiq’s internal circuit representation and pyQuil’s circuit representation (Quil programs).

mitiq.interface.mitiq_pyquil.conversions.from_pyquil(program)[source]

Returns a Mitiq circuit equivalent to the input pyQuil Program.

Parameters

program (Program) – PyQuil Program to convert to a Mitiq circuit.

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input pyQuil Program.

mitiq.interface.mitiq_pyquil.conversions.from_quil(quil)[source]

Returns a Mitiq circuit equivalent to the input Quil string.

Parameters

quil (str) – Quil string to convert to a Mitiq circuit.

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input Quil string.

mitiq.interface.mitiq_pyquil.conversions.to_pyquil(circuit)[source]

Returns a pyQuil Program equivalent to the input Mitiq circuit.

Parameters

circuit (Circuit) – Mitiq circuit to convert to a pyQuil Program.

Return type

Program

Returns

pyquil.Program object equivalent to the input Mitiq circuit.

mitiq.interface.mitiq_pyquil.conversions.to_quil(circuit)[source]

Returns a Quil string representing the input Mitiq circuit.

Parameters

circuit (Circuit) – Mitiq circuit to convert to a Quil string.

Returns

Quil string equivalent to the input Mitiq circuit.

Return type

QuilType

## Mitiq - Qiskit¶

### Conversions¶

Functions to convert between Mitiq’s internal circuit representation and Qiskit’s circuit representation.

mitiq.interface.mitiq_qiskit.conversions.from_qasm(qasm)[source]

Returns a Mitiq circuit equivalent to the input QASM string.

Parameters

qasm (str) – QASM string to convert to a Mitiq circuit.

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input QASM string.

mitiq.interface.mitiq_qiskit.conversions.from_qiskit(circuit)[source]

Returns a Mitiq circuit equivalent to the input Qiskit circuit.

Parameters

circuit (QuantumCircuit) – Qiskit circuit to convert to a Mitiq circuit.

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input Qiskit circuit.

mitiq.interface.mitiq_qiskit.conversions.to_qasm(circuit)[source]

Returns a QASM string representing the input Mitiq circuit.

Parameters

circuit (Circuit) – Mitiq circuit to convert to a QASM string.

Returns

QASM string equivalent to the input Mitiq circuit.

Return type

QASMType

mitiq.interface.mitiq_qiskit.conversions.to_qiskit(circuit)[source]

Returns a Qiskit circuit equivalent to the input Mitiq circuit. Note that the output circuit registers may not match the input circuit registers.

Parameters

circuit (Circuit) – Mitiq circuit to convert to a Qiskit circuit.

Return type

QuantumCircuit

Returns

Qiskit.QuantumCircuit object equivalent to the input Mitiq circuit.

### Qiskit Utils¶

Qiskit utility functions.

mitiq.interface.mitiq_qiskit.qiskit_utils.execute(circ, obs)[source]

Simulates noiseless wavefunction evolution and returns the expectation value of some observable.

Parameters
• circ (QuantumCircuit) – The input Qiskit circuit.

• obs (ndarray) – The observable to measure as a NumPy array.

Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_noise(circ, obs, noise_model)[source]

Simulates the evolution of the noisy circuit and returns the expectation value of the observable.

Parameters
• circ (QuantumCircuit) – The input Qiskit circuit.

• obs (ndarray) – The observable to measure as a NumPy array.

• noise_model (NoiseModel) – The input Qiskit noise model.

Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_shots(circ, obs, shots)[source]

Simulates the evolution of the circuit and returns the expectation value of the observable.

Parameters
• circ (QuantumCircuit) – The input Qiskit circuit.

• obs (ndarray) – The observable to measure as a NumPy array.

• shots (int) – The number of measurements.

Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_qiskit.qiskit_utils.execute_with_shots_and_noise(circ, obs, noise_model, shots, seed=None)[source]

Simulates the evolution of the noisy circuit and returns the expectation value of the observable.

Parameters
Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_qiskit.qiskit_utils.initialized_depolarizing_noise(noise)[source]

Initializes a depolarizing noise Qiskit NoiseModel.

Parameters

noise (float) – The depolarizing noise strength as a float, i.e. 0.001 is 0.1%.

Return type

NoiseModel

Returns

A Qiskit depolarizing NoiseModel.

## Probabilistic Error Cancellation¶

### Probabilistic Error Cancellation (High-Level Tools)¶

High-level probabilistic error cancellation tools.

exception mitiq.pec.pec.LargeSampleWarning[source]

Warning is raised when PEC sample size is greater than 10 ** 5

mitiq.pec.pec.execute_with_pec(circuit, executor, observable=None, *, representations, precision=0.03, num_samples=None, force_run_all=True, random_state=None, full_output=False)[source]

Evaluates the expectation value associated to the input circuit using probabilistic error cancellation (PEC) [Temme2017] [Endo2018].

This function implements PEC by:

1. Sampling different implementable circuits from the quasi-probability representation of the input circuit;

2. Evaluating the noisy expectation values associated to the sampled circuits (through the “executor” function provided by the user);

3. Estimating the ideal expectation value from a suitable linear combination of the noisy ones.

Parameters
• circuit (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The input circuit to execute with error-mitigation.

• executor (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], Union[float, MeasurementResult, ndarray]]) – Executes a circuit and returns a QuantumResult.

• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.

• 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 [Temme2017]. 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.

Returns

The PEC estimate of the ideal expectation value associated

to the input circuit.

pec_data: A dictionary which contains all the raw data involved in the

PEC process (including the PEC estimation error). The error is estimated as pec_std / sqrt(num_samples), where ‘pec_std’ is the standard deviation of the PEC samples, i.e., the square root of the mean squared deviation of the sampled values from ‘pec_value’. This is returned only if full_output is True.

Return type

pec_value

Endo2018

: Suguru Endo, Simon C. Benjamin, Ying Li, “Practical Quantum Error Mitigation for Near-Future Applications” Phys. Rev. **X 8*, 031027 (2018), (https://arxiv.org/abs/1712.09271).

Takagi2020

: Ryuji Takagi, “Optimal resource cost for error mitigation,” (https://arxiv.org/abs/2006.12509).

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 probabilistic error cancellation (PEC) 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 probabilistic error cancellation to produce the PEC estimate of the ideal expectation value associated to the input circuit as well as A dictionary which contains all the raw data involved in the PEC process.

Parameters
Return type

Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], Union[float, Tuple[float, Dict[str, Any]]]]

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 probabilistic error cancellation (PEC) mitigation to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns the PEC estimate of the ideal expectation value associated to the input circuit as well as A dictionary which contains all the raw data involved in the PEC process.

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 [Temme2017]. 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, Any]], Union[float, MeasurementResult, ndarray]]], Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape, Any]], Union[float, Tuple[float, Dict[str, Any]]]]]

### Quasi-Probability Representations¶

Functions for finding optimal representations given a noisy basis.

mitiq.pec.representations.optimal.find_optimal_representation(ideal_operation, noisy_basis, tol=1e-08, initial_guess=None)[source]

Returns the OperationRepresentaiton of the input ideal operation which minimizes the one-norm of the associated quasi-probability distribution.

More precicely, it solve the following optimization problem:

$\min_{{\eta_\alpha}} = \sum_\alpha |\eta_\alpha|, \text{ such that } \mathcal G = \sum_\alpha \eta_\alpha \mathcal O_\alpha,$

where $$\{\mathcal O_j\}$$ is the input basis of noisy operations.

Parameters
• ideal_operation (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The ideal operation to represent.

• noisy_basis (NoisyBasis) – The NoisyBasis in which the ideal_operation should be represented. It must contain NoisyOperation 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]) – Optional initial guess for the coefficients $$\{ \eta_\alpha \}$$.

Returns: The optimal OperationRepresentation.

Return type

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

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
Return type

ndarray

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.

Parameters
Return type

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.

Parameters
Return type
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.

Parameters
Return type
mitiq.pec.representations.depolarizing.represent_operation_with_global_depolarizing_noise(ideal_operation, noise_level)[source]

As described in [Temme2017], 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 of noise_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 [Takagi2020] that, under suitable assumptions, this representation is optimal (minimum 1-norm).

Parameters
• ideal_operation (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The ideal operation (as a QPROGRAM) to represent.

• noise_level (float) – The noise level (as a float) of the depolarizing channel.

Return type

OperationRepresentation

Returns

The quasi-probability representation of the ideal_operation.

Note

This representation is based on the ideal assumption that one can append Pauli gates to a noisy operation without introducing additional noise. For a backend which violates this assumption, it remains a good approximation for small values of noise_level.

Note

The input ideal_operation is typically a QPROGRAM with a single gate but could also correspond to a sequence of more gates. This is possible as long as the unitary associated to the input QPROGRAM, followed by a single final depolarizing channel, is physically implementable.

mitiq.pec.representations.depolarizing.represent_operation_with_local_depolarizing_noise(ideal_operation, noise_level)[source]

As described in [Temme2017], 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 of noise_level).

More information about the quasi-probability representation for a depolarizing noise channel can be found in: represent_operation_with_global_depolarizing_noise().

Parameters
• ideal_operation (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The ideal operation (as a QPROGRAM) to represent.

• noise_level (float) – The noise level of each depolarizing channel.

Return type

OperationRepresentation

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.

Temme2017(1,2,3,4,5,6)

: Kristan Temme, Sergey Bravyi, Jay M. Gambetta, “Error mitigation for short-depth quantum circuits,” Phys. Rev. Lett. 119, 180509 (2017), (https://arxiv.org/abs/1612.02058).

mitiq.pec.representations.depolarizing.represent_operations_in_circuit_with_global_depolarizing_noise(ideal_circuit, noise_level)[source]

Iterates over all unique operations of the input ideal_circuit and, for each of them, generates the corresponding quasi-probability representation (linear combination of implementable noisy operations).

This function assumes that the same depolarizing noise channel of strength noise_level affects each implemented operation.

This function internally calls represent_operation_with_global_depolarizing_noise() (more details about the quasi-probability representation can be found in its docstring).

Parameters
• ideal_circuit (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The ideal circuit, whose ideal operations should be represented.

• noise_level (float) – The (gate-independent) depolarizing noise level.

Return type
Returns

The list of quasi-probability representations associated to the operations of the input ideal_circuit.

Note

Measurement gates are ignored (not represented).

Note

The returned representations are always defined in terms of Cirq circuits, even if the input is not a cirq.Circuit.

mitiq.pec.representations.depolarizing.represent_operations_in_circuit_with_local_depolarizing_noise(ideal_circuit, noise_level)[source]

Iterates over all unique operations of the input ideal_circuit and, for each of them, generates the corresponding quasi-probability representation (linear combination of implementable noisy operations).

This function assumes that the tensor product of k single-qubit depolarizing channels affects each implemented operation, where k is the number of qubits associated to the operation.

This function internally calls represent_operation_with_local_depolarizing_noise() (more details about the quasi-probability representation can be found in its docstring).

Parameters
• ideal_circuit (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The ideal circuit, whose ideal operations should be represented.

• noise_level (float) – The (gate-independent) depolarizing noise level.

Return type
Returns

The list of quasi-probability representations associated to the operations of the input ideal_circuit.

Note

Measurement gates are ignored (not represented).

Note

The returned representations are always defined in terms of Cirq circuits, even if the input is not a cirq.Circuit.

### 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
Return type

Tuple[List[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], List[int], float]

Returns

The tuple (sampled_circuits, signs, norm) where sampled_circuits are the sampled implementable circuits, signs are the signs associated to sampled_circuits and norm 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
Return type

Tuple[List[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], List[int], float]

Returns

The tuple (sequences, signs, norm) where sequences are the sampled sequences, signs are the signs associated to the sampled sequences and norm 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(*basis_elements)[source]

A set of noisy operations which a quantum computer can actually implement, assumed to form a basis of n-qubit unitary matrices.

Parameters

basis_elements (NoisyOperation) –

add(*basis_elements)[source]

Parameters

basis_elements (Sequence[NoisyOperation]) – Sequence of basis elements as NoisyOperation’s to add to the current basis elements.

Return type

None

all_qubits()[source]

Returns the set of qubits that basis elements act on.

Return type

Set[Qid]

extend_to(qubits)[source]

Extends each basis element to act on the provided qubits.

Parameters

qubits (Sequence[List[Qid]]) – Additional qubits for each basis element to act on.

Return type

None

get_sequences(length)[source]

Returns a list of all implementable NoisyOperation’s of the given length.

Example: If the ideal operations of the noisy basis elements are {I, X}

and length = 2, then this method returns the four NoisyOperations whose ideal operations are {II, IX, XI, XX}.

Parameters

length (int) – Number of NoisyOperation’s in each element of the returned list.

Return type
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(return_type=None)[source]

Returns the circuit of the NoisyOperation.

Parameters

return_type (Optional[str]) – Type of the circuit to return. If not specified, the returned type is the same type as the circuit used to initialize the NoisyOperation.

Return type

Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]

copy()[source]

Returns a copy of the NoisyOperation.

Return type

NoisyOperation

static on_each(circuit, qubits, channel_matrix=None)[source]

Returns a NoisyOperation(circuit, channel_matrix) on each qubit in qubits.

Parameters
• circuit (Union[Circuit, Gate, Operation, OpTree]) – A gate, operation, sequence of operations, or circuit.

• channel_matrix (Optional[ndarray]) – Superoperator representation of the noisy channel which is generated when executing the input circuit on the noisy quantum computer.

• qubits (Sequence[List[Qid]]) – The qubits to implement circuit on.

Raises
• If qubits is not iterable. * If qubits is not an iterable of cirq.Qid’s or a sequence of lists of cirq.Qid’s of the same length.

Return type
transform_qubits(qubits)[source]

Changes the qubit(s) that the noisy operation acts on.

Parameters

qubits (Union[Qid, Sequence[Qid]]) – Qubit(s) that the noisy operation will act on.

Raises

ValueError – If the number of qubits does not match that of the noisy operation.

Return type

None

with_qubits(qubits)[source]

Returns the noisy operation acting on the input qubits.

Parameters

qubits (Sequence[Qid]) – Qubits that the returned noisy operation will act on.

Raises

ValueError – If the number of qubits does not match that of the noisy operation.

Return type

NoisyOperation

class mitiq.pec.types.types.OperationRepresentation(ideal, basis_expansion)[source]

A decomposition (basis expansion) of an operation or sequence of operations in a basis of noisy, implementable operations.

Parameters
coeff_of(noisy_op)[source]

Returns the coefficient of the noisy operation in the basis expansion.

Parameters

noisy_op (NoisyOperation) – NoisyOperation to get the coefficient of.

Raises

ValueError – If noisy_op doesn’t appear in the basis expansion.

Return type

float

distribution()[source]

Returns the Quasi-Probability Representation (QPR) of the decomposition. The QPR is the normalized magnitude of each coefficient in the basis expansion.

Return type

ndarray

property norm

Returns the L1 norm of the basis expansion coefficients.

Return type

float

sample(random_state=None)[source]

Returns a randomly sampled NoisyOperation from the basis expansion.

Parameters

random_state (Optional[RandomState]) – Defines the seed for sampling if provided.

Return type
sign_of(noisy_op)[source]

Returns the sign of the noisy operation in the basis expansion.

Parameters

noisy_op (NoisyOperation) – NoisyOperation to get the sign of.

Raises

ValueError – If noisy_op doesn’t appear in the basis expansion.

Return type

float

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

Parameters

choi_state (ndarray) –

Return type

ndarray

mitiq.pec.channels.kraus_to_choi(kraus_ops)[source]

Returns the normalized choi state corresponding to the channel defined by the input kraus operators.

Parameters

kraus_ops (List[ndarray]) –

Return type

ndarray

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

kraus_ops (List[ndarray]) –

Return type

ndarray

mitiq.pec.channels.matrix_to_vector(density_matrix)[source]

Reshapes a $$d \times d$$ density matrix into a $$d^2$$-dimensional state vector, according to the rule: $$|i \rangle\langle j| \rightarrow |i,j \rangle$$.

Parameters

density_matrix (ndarray) –

Return type

ndarray

mitiq.pec.channels.super_to_choi(super_operator)[source]

Returns the normalized choi state corresponding to the channel defined by the input superoperator.

Up to normalization, this is just a tensor transposition.

Parameters

super_operator (ndarray) –

Return type

ndarray

mitiq.pec.channels.tensor_product(*args)[source]

Returns the Kronecker product of the input array-like arguments. This is a generalization of the binary function numpy.kron(arg_a, arg_b) to the case of an arbitrary number of arguments.

Parameters

args (ndarray) –

Return type

ndarray

mitiq.pec.channels.vector_to_matrix(vector)[source]

Reshapes a $$d^2$$-dimensional state vector into a $$d \times d$$ density matrix, according to the rule: $$|i,j \rangle \rightarrow |i \rangle\langle j|$$.

Parameters

vector (ndarray) –

Return type

ndarray

## Zero Noise Extrapolation¶

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

High-level zero-noise extrapolation tools.

mitiq.zne.zne.execute_with_zne(qp, executor, observable=None, *, 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[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – Quantum program to execute with error mitigation.

• executor (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], Union[float, MeasurementResult, ndarray]]) – Executes a circuit and returns a QuantumResult.

• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.

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

• scale_noise (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape], float], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – 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, observable=None, *, 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
Return type

Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], float]

mitiq.zne.zne.zne_decorator(observable=None, *, 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
• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor being decorated must return an expectation value. Otherwise, the QuantumResult returned by the executor is used to compute the expectation of the observable.

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

• scale_noise (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape], float], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – Function for scaling the noise of a quantum circuit.

• num_to_average (int) – Number of times expectation values are computed by the executor after each call to scale_noise, then averaged.

Return type

Callable[[Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], Union[float, MeasurementResult, ndarray]]], Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], float]]

### 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
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
Return type
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

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

bool

next()[source]

Returns a dictionary of parameters to execute a circuit at.

Return type
reduce()[source]

Returns the zero-noise limit found by fitting an exponential model to the internal data stored in the factory.

Return type

float

Returns

The zero-noise limit.

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

bool

abstract next()[source]

Returns a dictionary of parameters to execute a circuit at.

Return type
abstract reduce()[source]

Returns the extrapolation to the zero-noise limit.

Return type

float

run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1, max_iterations=100)[source]

Evaluates a sequence of expectation values by executing quantum circuits until enough data is collected (or iterations reach “max_iterations”).

Parameters
• qp (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – Circuit to mitigate.

• executor (Callable[…, Union[float, MeasurementResult, ndarray]]) – executor: Function which executes a circuit and returns a mitiq.QuantumResult. If the factory was initialized with a shot_list, then “shot” must be an additional argument of the executor.

• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.

• scale_noise (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape], float], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – Function that scales the noise level of a quantum circuit.

• num_to_average (int) – Number of times expectation values are computed by the executor after each call to scale_noise, then averaged.

• max_iterations (int) – Maximum number of iterations (optional).

Return type

AdaptiveFactory

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
• scale_factor_to_expectation_value (Callable[…, float]) – Function mapping a noise scale factor to an expectation value. If shot_list is not None, “shots” must be an argument of this function.

• max_iterations (int) – Maximum number of iterations (optional). Default: 100.

Raises

ConvergenceWarning – If iteration loop stops before convergence.

Return type

AdaptiveFactory

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
abstract static extrapolate(*args, **kwargs)[source]

Returns the extrapolation to the zero-noise limit.

Parameters
Return type
reduce()[source]

Evaluates the zero-noise limit found by fitting according to the factory’s extrapolation method.

Return type

float

Returns

The zero-noise limit.

run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]

Computes the expectation values at each scale factor and stores them in the factory. If the executor returns a single expectation value, the circuits are run sequentially. If the executor is batched and returns a list of expectation values (one for each circuit), then the circuits are sent to the backend as a single job. To detect if an executor is batched, it must be annotated with a return type that is one of the following:

• Iterable[float]

• List[float]

• Sequence[float]

• Tuple[float]

• numpy.ndarray

Parameters
• qp (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – Quantum circuit to run.

• executor (Callable[…, Union[float, MeasurementResult, ndarray]]) – A “single executor” (1) or a “batched executor” (2). (1) A function which inputs a single circuit and outputs a single mitiq.QuantumResult. (2) A function which inputs a list of circuits and outputs a list of mitiq.QuantumResult s (one for each circuit). A batched executor can also take an optional “kwargs_list” argument to set a list of keyword arguments (one for each circuit). This is necessary only if the factory is initialized using the optional “shot_list” parameter.

• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.

• scale_noise (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape], float], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – Noise scaling function.

• num_to_average (int) – The number of circuits executed for each noise scale factor. This parameter can be used to increase the precision of the “executor” or to average the effect of a non-deterministic “scale_noise” function.

Return type

BatchedFactory

run_classical(scale_factor_to_expectation_value)[source]

Computes expectation values by calling the input function at each scale factor.

Parameters

scale_factor_to_expectation_value (Callable[…, float]) – Function mapping a noise scale factor to an expectation value. If shot_list is not None, “shots” must be an argument of this function.

Return type

BatchedFactory

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
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
Return type
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

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_expectation_values()[source]

Returns the expectation values computed by the factory.

Return type

ndarray

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.

Return type
get_optimal_parameters()[source]

Returns the optimal model parameters produced by the extrapolation fit.

Return type

ndarray

get_parameters_covariance()[source]

Returns the covariance matrix of the model parameters produced by the extrapolation fit.

Return type

ndarray

get_scale_factors()[source]

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

Return type

ndarray

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

float

get_zero_noise_limit_error()[source]

Returns the extrapolation error representing the uncertainty affecting the zero-noise limit. It is deduced by error propagation from the covariance matrix associated to the fit parameters.

Note: this quantity is only related to the ability of the model

to fit the measured data. Therefore, it may underestimate the actual error existing between the zero-noise limit and the true ideal expectation value.

Return type

float

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.

Parameters
Return type

Factory

reset()[source]

Resets the internal state of the Factory.

Return type

Factory

abstract run(qp, executor, observable=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]

Calls the executor function on noise-scaled quantum circuit and stores the results.

Parameters
• qp (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – Quantum circuit to scale noise in.

• executor (Callable[…, Union[float, MeasurementResult, ndarray]]) – Function which inputs a (list of) quantum circuits and outputs a (list of) mitiq.QuantumResult s.

• observable (Optional[Observable]) – Observable to compute the expectation value of. If None, the executor must return an expectation value. Otherwise, the QuantumResult returned by executor is used to compute the expectation of the observable.

• scale_noise (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape], float], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – Function which inputs a quantum circuit and outputs a noise-scaled quantum circuit.

• num_to_average (int) – Number of times the executor function is called on each noise-scaled quantum circuit.

Return type

Factory

abstract run_classical(scale_factor_to_expectation_value)[source]

Calls the function scale_factor_to_expectation_value at each scale factor of the factory, and stores the results.

Parameters

scale_factor_to_expectation_value (Callable[…, float]) – A function which inputs a scale factor and outputs an expectation value. This does not have to involve a quantum processor making this a “classical analogue” of the run method.

Return type

Factory

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

static extrapolate(scale_factors, exp_values, full_output=False)[source]

Returns the extrapolation to the zero-noise limit.

Parameters
Return type
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
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
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
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
Return type
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

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

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

exception mitiq.zne.scaling.folding.UnfoldableCircuitError[source]
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


• exclude (FrozenSet[Any]) –

Do not fold these gates. Supported gate keys are listed in the following table.:

Gate key    | Gate
-------------------------
"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


Return type

Circuit

mitiq.zne.scaling.folding.fold_gates_at_random(circuit, scale_factor, seed=None, **kwargs)[source]

Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the right (end) of the circuit.

The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.

For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [2].

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
-------------------------
"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.folding.fold_gates_from_left(circuit, scale_factor, **kwargs)[source]

Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the left (beginning) of the circuit.

The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.

For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [2].

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
-------------------------
"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.folding.fold_gates_from_right(circuit, scale_factor, **kwargs)[source]

Returns a new folded circuit by applying the map G -> G G^dag G to a subset of gates of the input circuit, starting with gates at the right (end) of the circuit.

The folded circuit has a number of gates approximately equal to scale_factor * n where n is the number of gates in the input circuit.

For equal gate fidelities, this function reproduces the local unitary folding method defined in equation (5) of [2].

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

### Noise Scaling: Parameter Calibration¶

exception mitiq.zne.scaling.parameter.CircuitMismatchException[source]
exception mitiq.zne.scaling.parameter.GateTypeException[source]
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 in mitiq.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

float

Returns

The estimated variance of the control parameter.

mitiq.zne.scaling.parameter.scale_parameters(circuit, scale_factor, base_variance, seed=None)[source]

Applies parameter-noise scaling to the input circuit, assuming that each gate has the same base level of noise.

Parameters
• circuit (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The circuit to scale as a QPROGRAM. All measurements should be in the last moment of the circuit.

• scale_factor (float) – The amount to scale the base noise level by.

• base_variance (float) – The base level (variance) of parameter noise, assumed to be the same for each gate of the circuit.

• seed (Optional[int]) – Optional seed for random number generator.

Return type

Circuit

Returns

The parameter noise scaled circuit.