# API-doc#

## Benchmarks#

### Mirror Circuits#

Functions for creating mirror circuits as defined in [41] for benchmarking quantum computers (with error mitigation).

mitiq.benchmarks.mirror_circuits.edge_grab(two_qubit_gate_prob, connectivity_graph, random_state)[source]#
Parameters
• two_qubit_gate_prob (float) – Probability of an edge being chosen from the set of candidate edges.

• connectivity_graph (Graph) – The connectivity graph for the backend on which the circuit will be run.

• random_state (RandomState) – Random state to select edges (uniformly at random).

Return type

Graph

Returns

Returns a set of edges for which two qubit gates are to be applied given a two qubit gate density and the connectivity graph that must be satisfied.

mitiq.benchmarks.mirror_circuits.generate_mirror_circuit(nlayers, two_qubit_gate_prob, connectivity_graph, two_qubit_gate_name='CNOT', seed=None, return_type=None)[source]#
Parameters
• nlayers (int) – The number of random Clifford layers to be generated.

• two_qubit_gate_prob (float) – Probability of a two-qubit gate being applied.

• connectivity_graph (Graph) – The connectivity graph of the backend on which the mirror circuit will be run. This is used to make sure 2-qubit gates are only applied to connected qubits.

• two_qubit_gate_name (str) – Name of two-qubit gate to use. Options are “CNOT” and “CZ”.

• seed (Optional[int]) – Seed for generating randomized mirror circuit.

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

Return type

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

Returns

A randomized mirror circuit.

mitiq.benchmarks.mirror_circuits.random_cliffords(connectivity_graph, random_state, two_qubit_gate=cirq.CNOT)[source]#
Parameters
• connectivity_graph (Graph) – A graph with the edges for which the two-qubit Clifford gate is to be applied.

• random_state (RandomState) – Random state to choose Cliffords (uniformly at random).

• two_qubit_gate (Gate) – Two-qubit gate to use.

Return type

Circuit

Returns

A circuit with a two-qubit Clifford gate applied to each edge in edges, and a random single-qubit Clifford gate applied to every other qubit.

mitiq.benchmarks.mirror_circuits.random_paulis(connectivity_graph, random_state)[source]#

Returns a circuit with randomly selected Pauli gates on each qubit.

Parameters
• connectivity_graph (Graph) – Connectivity graph of device to run circuit on.

• random_state (RandomState) – Random state to select Paulis I, X, Y, Z uniformly at random.

Return type

Circuit

mitiq.benchmarks.mirror_circuits.random_single_cliffords(connectivity_graph, random_state)[source]#
Parameters
• connectivity_graph (Graph) – A graph with each node representing a qubit for which a random single-qubit Clifford gate is to be applied.

• random_state (RandomState) – Random state to choose Cliffords (uniformly at random).

Return type

Circuit

Returns

A circuit with a random single-qubit Clifford gate applied on each given qubit.

### Randomized Benchmarking Circuits#

Functions for generating randomized benchmarking circuits.

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

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

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

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

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

• return_type (Optional[str]) – String which specifies the type of the returned circuits. See the keys 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.

### GHZ Circuits#

Functions for creating GHZ circuits for benchmarking purposes.

mitiq.benchmarks.ghz_circuits.generate_ghz_circuit(n_qubits, return_type=None)[source]#

Returns a GHZ circuit ie a circuit that prepares an n_qubits GHZ state.

Parameters
• n_qubits (int) – The number of qubits in the circuit.

• 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

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

Returns

A GHZ circuit acting on n_qubits qubits.

### Quantum Volume Circuits#

Functions for creating circuits of the form used in quantum volume experiments as defined in https://arxiv.org/abs/1811.12926.

Useful overview of quantum volume experiments: https://pennylane.ai/qml/demos/quantum_volume.html

Cirq implementation of quantum volume circuits: cirq-core/cirq/contrib/quantum_volume/quantum_volume.py

mitiq.benchmarks.quantum_volume_circuits.compute_heavy_bitstrings(circuit, num_qubits)[source]#

Classically compute the heavy bitstrings of the provided circuit.

The heavy bitstrings are defined as the output bit-strings that have a greater than median probability of being generated.

Parameters
• circuit (Circuit) – The circuit to classically simulate.

• num_qubits (int) –

Return type
Returns

A list containing the heavy bitstrings.

mitiq.benchmarks.quantum_volume_circuits.generate_quantum_volume_circuit(num_qubits, depth, decompose=False, seed=None, return_type=None)[source]#

Generate a quantum volume circuit with the given number of qubits and depth.

The generated circuit consists of depth layers of random qubit permutations followed by random two-qubit gates that are sampled from the Haar measure on SU(4).

Parameters
• num_qubits (int) – The number of qubits in the generated circuit.

• depth (int) – The number of qubits in the generated circuit.

• decompose (bool) – Recursively decomposes the randomly sampled (numerical) unitary matrix gates into simpler gates.

• seed (Optional[int]) – Seed for generating random circuit.

• 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

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

Returns

A quantum volume circuit acting on num_qubits qubits. A list of the heavy bitstrings for the returned circuit.

## Clifford Data Regression#

### Clifford Data Regression (High-Level Tools)#

API for using Clifford Data Regression (CDR) error mitigation.

mitiq.cdr.cdr.cdr_decorator(observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#

Decorator which adds clifford data regression (CDR) mitigation to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns the CDR estimate of the ideal expectation value associated to the input circuit.

Parameters
• executor – Executes a circuit and returns a QuantumResult.

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

• simulator (Union[Executor, Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]], Union[float, MeasurementResult, ndarray]]]) – Executes a circuit without noise and returns a QuantumResult. For CDR to be efficient, the simulator must be able to efficiently simulate near-Clifford circuits.

• num_training_circuits (int) – Number of training circuits to be used in the mitigation.

• fraction_non_clifford (float) – The fraction of non-Clifford gates to be substituted in the training circuits.

• fit_function (Callable[…, float]) – The function to map noisy to exact data. Takes array of noisy and data and parameters returning a float. See cdr.linear_fit_function for an example.

• num_fit_parameters (Optional[int]) – The number of parameters the fit_function takes.

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

• scale_factors (Sequence[float]) – Factors by which to scale the noise. - When 1.0 is the only scale factor, the method is known as CDR. - Note: When scale factors larger than 1.0 are provided, the method is known as “variable-noise CDR.”

• kwargs (Any) – Available keyword arguments are: - method_select (string): Specifies the method used to select the non-Clifford gates to replace when constructing the near-Clifford training circuits. Can be ‘uniform’ or ‘gaussian’. - method_replace (string): Specifies the method used to replace the selected non-Clifford gates with a Clifford when constructing the near-Clifford training circuits. Can be ‘uniform’, ‘gaussian’, or ‘closest’. - sigma_select (float): Width of the Gaussian distribution used for method_select='gaussian'. - sigma_replace (float): Width of the Gaussian distribution used for method_replace='gaussian'. - random_state (int): Seed for sampling.

Return type

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

mitiq.cdr.cdr.execute_with_cdr(circuit, executor, observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#

Function for the calculation of an observable from some circuit of interest to be mitigated with CDR (or vnCDR) based on Ref. [11] and Ref. [2].

The circuit of interest must be compiled in the native basis of the IBM quantum computers, that is {Rz, sqrt(X), CNOT}, or such that all the non-Clifford gates are contained in the Rz rotations.

The observable/s to be calculated should be input as an array or a list of arrays representing the diagonal of the observables to be measured. Note these observables MUST be diagonal in z-basis measurements corresponding to the circuit of interest.

Returns mitigated observables list of raw observables (at noise scale factors).

This function returns the mitigated observable/s.

Parameters
Return type

float

mitiq.cdr.cdr.mitigate_executor(executor, observable=None, *, simulator, num_training_circuits=10, fraction_non_clifford=0.1, fit_function=<function linear_fit_function>, num_fit_parameters=None, scale_factors=(1, ), scale_noise=<function fold_gates_at_random>, **kwargs)[source]#

Returns a clifford data regression (CDR) mitigated version of the input ‘executor’.

The input executor executes a circuit with an arbitrary backend and produces an expectation value (without any error mitigation). The returned executor executes the circuit with the same backend but uses clifford data regression to produce the CDR estimate of the ideal expectation value associated to the input circuit.

Parameters
Return type

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

### Clifford Training Data#

Functions for mapping circuits to (near) Clifford circuits.

mitiq.cdr.clifford_training_data.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 [11], data generated from these circuits is used as a training set to learn the effect of noise.

Parameters
• circuit (Circuit) – A circuit of interest assumed to be compiled into the gate set {Rz, sqrt(X), CNOT}, or such that all the non-Clifford gates are contained in the Rz rotations.

• num_training_circuits (int) – Number of circuits in the returned training set.

• fraction_non_clifford (float) – The (approximate) fraction of non-Clifford gates in each returned circuit.

• method_select (str) – Method by which non-Clifford gates are selected to be replaced by Clifford gates. Options are ‘uniform’ or ‘gaussian’.

• method_replace (str) – Method by which selected non-Clifford gates are replaced by Clifford gates. Options are ‘uniform’, ‘gaussian’ or ‘closest’.

• random_state (Union[int, RandomState, None]) – Seed for sampling.

• kwargs (Any) – Available keyword arguments are: - sigma_select (float): Width of the Gaussian distribution used for method_select='gaussian'. - sigma_replace (float): Width of the Gaussian distribution used for method_replace='gaussian'.

Return type

List[Circuit]

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

### Data Regression#

The data regression portion of Clifford data regression.

mitiq.cdr.data_regression.linear_fit_function(x_data, params)[source]#

Returns y(x) = a_1 x_1 + … + a_n x_n + b.

Parameters
• x_data (ndarray) – The independent variables x_1, …, x_n. In CDR, these are nominally the noisy expectation values to perform regression on.

• params (Sequence[float]) – Parameters a_1, …, a_n, b of the linear fit. Note the b parameter is the intercept of the fit.

Return type

float

mitiq.cdr.data_regression.linear_fit_function_no_intercept(x_data, params)[source]#

Returns y(x) = a_1 x_1 + … + a_n x_n.

Parameters
Return type

float

See Ref. [11] 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.compute_density_matrix(circuit, noise_model=<function amplitude_damp>, noise_level=(0.01, ))[source]#

Returns the density matrix of the quantum state after the (noisy) execution of the input circuit.

Parameters
Return type

ndarray

Returns

The final density matrix as a NumPy array.

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

Simulates a circuit with depolarizing noise and returns the expectation value of the input observable. The expectation value is deterministically computed from the final density matrix and, therefore, shot noise is absent.

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.sample_bitstrings(circuit, noise_model=<function amplitude_damp>, noise_level=(0.01, ), sampler=<cirq.sim.density_matrix_simulator.DensityMatrixSimulator object>, shots=8192)[source]#

Adds noise to the input circuit. The noise is added based on a particular noise model and some value for the error rate.

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

• noise_model (Union[None, NoiseModel, Gate]) – Input Cirq noise model. Default is amplitude damping.

• noise_level (Tuple[float]) – Noise rate as a tuple of floats.

• sampler (Sampler) – Cirq simulator from which the result will be sampled from.

• shots (int) – Number of measurements.

Return type

MeasurementResult

Returns

Sampled outcome from a measurement.

## Mitiq - PyQuil#

### Conversions#

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

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

Returns a Mitiq circuit equivalent to the input pyQuil Program.

Parameters

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

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input pyQuil Program.

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

Returns a Mitiq circuit equivalent to the input Quil string.

Parameters

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

Return type

Circuit

Returns

Mitiq circuit representation equivalent to the input Quil string.

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

Returns a pyQuil Program equivalent to the input Mitiq circuit.

Parameters

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

Return type

Program

Returns

pyquil.Program object equivalent to the input Mitiq circuit.

mitiq.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.compute_expectation_value_on_noisy_backend(circuit, obs, backend=None, noise_model=None, shots=10000, measure_all=False, qubit_indices=None)[source]#

Returns the noisy expectation value of the input Mitiq observable obtained from executing the input circuit on a Qiskit backend.

Parameters
Return type

complex

Returns

The noisy expectation value.

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

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

Parameters
Return type

float

Returns

The expectation value of obs as a float.

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

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

Parameters
Return type

float

Returns

The expectation value of obs as a float.

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

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

Parameters
Return type

float

Returns

The expectation value of obs as a float.

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

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

Parameters
Return type

float

Returns

The expectation value of obs as a float.

mitiq.interface.mitiq_qiskit.qiskit_utils.initialized_depolarizing_noise(noise_level)[source]#

Initializes a depolarizing noise Qiskit NoiseModel.

Parameters

noise_level (float) – The noise strength as a float, e.g., 0.01 is 0.1%.

Return type

NoiseModel

Returns

A Qiskit depolarizing NoiseModel.

mitiq.interface.mitiq_qiskit.qiskit_utils.sample_bitstrings(circuit, backend=None, noise_model=None, shots=10000, measure_all=False, qubit_indices=None)[source]#

Returns measurement bitstrings obtained from executing the input circuit on a Qiskit backend (passed as an argument). Note that the input circuit must contain measurement gates (unless measure_all is True).

Parameters
Return type

MeasurementResult

Returns

The measured bitstrings casted as a Mitiq MeasurementResult object.

## Digital Dynamical Decoupling#

### Digital Dynamical Decoupling (High-Level Tools)#

High-level digital dynamical decoupling (DDD) tools.

mitiq.ddd.ddd.ddd_decorator(observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#

Decorator which adds an error-mitigation layer based on digital dynamical decoupling (DDD) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a QuantumResult (e.g. an expectation value).

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

• rule (Callable[[int], Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]) – A function that takes as main argument a slack length (i.e. the number of idle moments) of a slack window (i.e. a single-qubit idle window in a circuit) and returns the DDD sequence of gates to be applied in that window. Mitiq provides standard built-in rules that can be directly imported from mitiq.ddd.rules.

• rule_args (Dict[str, Any]) – An optional dictionary of keyword arguments for rule.

• num_trials (int) – The number of independent experiments to average over. A number larger than 1 can be useful to average over multiple applications of a rule returning non-deterministic DDD sequences.

• full_output (bool) – If False only the mitigated expectation value is returned. If True a dictionary containing all DDD data is returned too.

Return type

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

Returns

The error-mitigating decorator to be applied to an executor function.

mitiq.ddd.ddd.execute_with_ddd(circuit, executor, observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#

Estimates the error-mitigated expectation value associated to the input circuit, via the application of digital dynamical decoupling (DDD).

Parameters
Return type
Returns

The tuple (ddd_value, ddd_data) where ddd_value is the expectation value estimated with DDD and ddd_data is a dictionary containing all the raw data involved in the DDD process (e.g. the circuit filled with DDD sequences). If full_output is false, only ddd_value is returned.

mitiq.ddd.ddd.mitigate_executor(executor, observable=None, *, rule, rule_args={}, num_trials=1, full_output=False)[source]#

Returns a modified version of the input ‘executor’ which is error-mitigated with digital dynamical decoupling (DDD).

Parameters
Return type

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

Returns

The error-mitigated version of the input executor.

### Insertion#

Tools to determine slack windows in circuits and to insert DDD sequences.

mitiq.ddd.insertion.get_slack_matrix_from_circuit_mask(mask)[source]#

Given a circuit mask matrix $$A$$, e.g., the output of _get_circuit_mask(), returns a slack matrix $$B$$, where $$B_{i,j} = t$$ if the position $$A_{i,j}$$ is the initial element of a sequence of $$t$$ zeros (from left to right).

Parameters

mask (ndarray) – The mask matrix of a quantum circuit.

Return type

ndarray

Returns

The matrix of slack lengths.

mitiq.ddd.insertion.insert_ddd_sequences(circuit, rule)[source]#

Returns the circuit with DDD sequences applied according to the input rule.

Parameters
• circuit (Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]) – The QPROGRAM circuit to be modified with DDD sequences.

• rule (Callable[[int], Circuit]) – The rule determining what DDD sequences should be applied. A set of built-in DDD rules can be imported from mitiq.ddd.rules.

Return type

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

Returns

The circuit with DDD sequences added.

### Rules#

Built-in rules determining what DDD sequence should be applied in a given slack window.

mitiq.ddd.rules.rules.general_rule(slack_length, gates, spacing=- 1)[source]#

Returns a digital dynamical decoupling sequence, based on inputs.

Parameters
• slack_length (int) – Length of idle window to fill.

• spacing (int) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8, gates = [X, X] the spacing defaults to 2 and the rule returns the sequence: ──I──I──X──I──I──X──I──I── given slack_length = 9, gates [X, Y, X, Y] the spacing defaults to 1 and the rule returns the sequence: ──I──X──I──Y──I──X──I──Y──I──.

• gates (List[Gate]) – A list of single qubit Cirq gates to build the rule. E.g. [X, X] is the xx sequence, [X, Y, X, Y] is the xyxy sequence. - Note: To repeat the sequence, specify a repeated gateset.

Return type

Circuit

Returns

A digital dynamical decoupling sequence, as a Cirq circuit.

mitiq.ddd.rules.rules.repeated_rule(slack_length, gates)[source]#

Returns a general digital dynamical decoupling sequence that repeats until the slack is filled without spacing, up to a complete repetition.

Parameters
• slack_length (int) – Length of idle window to fill.

• gates (List[Gate]) – A list of single qubit Cirq gates to build the rule. E.g. [X, X] is the xx sequence, [X, Y, X, Y] is the xyxy sequence.

Return type

Circuit

Returns

A repeated digital dynamical decoupling sequence, as a Cirq circuit.

Note

Where general_rule() fills a slack window with a single sequence, this rule attempts to fill every moment with sequence repetitions (up to a complete repetition of the gate set). E.g. given slack_length = 8 and gates = [X, Y, X, Y], this rule returns the sequence: ──X──Y──X──Y──X──Y──X──Y──.

mitiq.ddd.rules.rules.xx(slack_length, spacing=- 1)[source]#

Returns an XX digital dynamical decoupling sequence, based on inputs.

Parameters
• slack_length (int) – Length of idle window to fill.

• spacing (int) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8 the spacing defaults to 2 and this rule returns the sequence: ──I──I──X──I──I──X──I──I──.

Return type

Circuit

Returns

An XX digital dynamical decoupling sequence, as a Cirq circuit.

mitiq.ddd.rules.rules.xyxy(slack_length, spacing=- 1)[source]#

Returns an XYXY digital dynamical decoupling sequence, based on inputs.

Parameters
• slack_length (int) – Length of idle window to fill.

• spacing (int) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 9 the spacing defaults to 1 and this rule returns the sequence: ──I──X──I──Y──I──X──I──Y──I──.

Return type

Circuit

Returns

An XYXY digital dynamical decoupling sequence, as a Cirq circuit.

mitiq.ddd.rules.rules.yy(slack_length, spacing=- 1)[source]#

Returns a YY digital dynamical decoupling sequence, based on inputs.

Parameters
• slack_length (int) – Length of idle window to fill.

• spacing (int) – How many identity spacing gates to apply between dynamical decoupling gates, as a non-negative int. Negative int corresponds to default. Defaults to maximal spacing that fits a single sequence in the given slack window. E.g. given slack_length = 8 the spacing defaults to 2 and this rule returns the sequence: ──I──I──Y──I──I──Y──I──I──.

Return type

Circuit

Returns

An YY digital dynamical decoupling sequence, as a Cirq circuit.

## Executors#

Defines utilities for efficiently running collections of circuits generated by error mitigation techniques to compute expectation values.

class mitiq.executor.executor.Executor(executor, max_batch_size=75)[source]#

Tool for efficiently scheduling/executing quantum programs and storing the results.

Parameters
evaluate(circuits, observable=None, force_run_all=False, **kwargs)[source]#

Returns the expectation value Tr[ρ O] for each circuit in circuits where O is the observable provided or implicitly defined by the executor. (The observable is implicitly defined when the executor returns float(s).)

All executed circuits are stored in self.executed_circuits, and all quantum results are stored in self.quantum_results.

Parameters
Return type
static is_batched_executor(executor)[source]#

Returns True if the input function is recognized as a “batched executor”, else False.

The executor is detected as “batched” if and only if it is annotated with a return type that is one of the following:

• Iterable[QuantumResult]

• List[QuantumResult]

• Sequence[QuantumResult]

• Tuple[QuantumResult]

Otherwise, it is considered “serial”.

Batched executors can _run several quantum programs in a single call. See below.

Parameters

executor (Callable[[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape, Sequence[Union[Circuit, Program, QuantumCircuit, Circuit, QuantumTape]]]], Any]) –

A “serial executor” (1) or a “batched executor” (2).

(1) A function which inputs a single QPROGRAM and outputs a single QuantumResult. (2) A function which inputs a list of QPROGRAMs and outputs a list of QuantumResults (one for each QPROGRAM).

Return type

bool

Returns

True if the executor is detected as batched, else False.

## Observables#

### Observable#

class mitiq.observable.observable.Observable(*paulis)[source]#

A quantum observable typically used to compute its mitigated expectation value.

Parameters

paulis (PauliString) –

matrix(qubit_indices=None, dtype=<class 'numpy.complex128'>)[source]#

Returns the (potentially very large) matrix of the Observable.

Parameters
Return type

ndarray

### Pauli#

class mitiq.observable.pauli.PauliString(spec='', coeff=1.0, support=None)[source]#

A PauliString is a (tensor) product of single-qubit Pauli gates I, X, Y, and Z, with a leading (real or complex) coefficient. PauliStrings can be measured in any mitiq.QPROGRAM.

Parameters
can_be_measured_with(other)[source]#

Returns True if the expectation value of the PauliString can be simultaneously estimated with other via single-qubit measurements.

Parameters

other (PauliString) – The PauliString to check simultaneous measurement with.

Return type

bool

matrix(qubit_indices_to_include=None, dtype=<class 'numpy.complex128'>)[source]#

Returns the (potentially very large) matrix of the PauliString.

Parameters
Return type

ndarray

weight()[source]#

Returns the weight of the PauliString, i.e., the number of non-identity terms in the PauliString.

Return type

int

class mitiq.observable.pauli.PauliStringCollection(*paulis, check_precondition=True)[source]#

A collection of PauliStrings that qubit-wise commute and so can be measured with a single circuit.

Parameters

## Probabilistic Error Cancellation#

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

High-level probabilistic error cancellation tools.

exception mitiq.pec.pec.LargeSampleWarning[source]#

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

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

Estimates the error-mitigated expectation value associated to the input circuit, via the application of probabilistic error cancellation (PEC). [4] [30].

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

The tuple (pec_value, pec_data) where pec_value is the expectation value estimated with PEC and pec_data is 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. If full_output is True, only pec_value is returned.

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

Returns a modified version of the input ‘executor’ which is error-mitigated with probabilistic error cancellation (PEC).

Parameters
Return type

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

Returns

The error-mitigated version of the input executor.

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

Decorator which adds an error-mitigation layer based on probabilistic error cancellation (PEC) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a QuantumResult (e.g. an expectation value).

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

• representations (Sequence[OperationRepresentation]) – Representations (basis expansions) of each operation in the input circuit.

• precision (float) – The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where ‘one_norm’ is related to the negativity of the quasi-probability representation [4]. If ‘num_samples’ is explicitly set by the user, ‘precision’ is ignored and has no effect.

• num_samples (Optional[int]) – The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument ‘precision’.

• force_run_all (bool) – If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed.

• random_state (Union[int, RandomState, None]) – Seed for sampling circuits.

• full_output (bool) – If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too.

Return type

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

Returns

The error-mitigating decorator to be applied to an executor function.

### Quasi-Probability Representations#

Functions for finding optimal representations given a noisy basis.

mitiq.pec.representations.optimal.find_optimal_representation(ideal_operation, noisy_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 [4], 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 [8] that, under suitable assumptions, this representation is optimal (minimum 1-norm).

Parameters
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 [4], 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
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.

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

Function to generate representations with biased noise.

mitiq.pec.representations.biased_noise.represent_operation_with_local_biased_noise(ideal_operation, epsilon, eta)[source]#

This function maps an ideal_operation $$\mathcal{U}$$ into its quasi-probability representation, which is a linear combination of noisy implementable operations $$\sum_\alpha \eta_{\alpha} \mathcal{O}_{\alpha}$$.

This function assumes a combined depolarizing and dephasing noise model with a bias factor $$\eta$$ (see [42]) and that the following noisy operations are implementable $$\mathcal{O}_{\alpha} = \mathcal{D} \circ \mathcal P_\alpha$$ where $$\mathcal{U}$$ is the unitary associated to the input ideal_operation, $$\mathcal{P}_\alpha$$ is a Pauli operation and

$\mathcal{D}(\epsilon) = (1 - \epsilon)[\mathbb{1}] + \epsilon(\frac{\eta}{\eta + 1} \mathcal{Z} + \frac{1}{3}\frac{1}{\eta + 1}(\mathcal{X} + \mathcal{Y} + \mathcal{Z}))$

is the combined (biased) dephasing and depolarizing channel acting on a single qubit. For multi-qubit operations, we use a noise channel that is the tensor product of the local single-qubit channels.

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

• epsilon (float) – The local noise severity (as a float) of the combined channel.

• eta (float) – The noise bias between combined dephasing and depolarizing channels with $$\eta = 0$$ describing a fully depolarizing channel and $$\eta = \inf$$ describing a fully dephasing 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 epsilon.

Note

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

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

## Raw#

### Run experiments without error mitigation (raw results)#

Run experiments without error mitigation.

### Measurement Result#

Defines MeasurementResult, a result obtained by measuring qubits on a quantum computer.

class mitiq.rem.measurement_result.MeasurementResult(result, qubit_indices=None)[source]#

Bitstrings sampled from a quantum computer.

Parameters

### Post-selection#

mitiq.rem.post_select.post_select(result, selector, inverted=False)[source]#

Returns only the bitstrings which satisfy the predicate in selector.

Parameters
• result (MeasurementResult) – List of bitstrings.

• selector (Callable[[List[int]], bool]) –

Predicate for which bitstrings to select. Examples:

• selector = lambda bitstring: sum(bitstring) == k - Select all bitstrings of Hamming weight k.

• selector = lambda bitstring: sum(bitstring) <= k - Select all bitstrings of Hamming weight at most k.

• selector = lambda bitstring: bitstring[0] == 1 - Select all bitstrings such that the the first bit is 1.

• inverted (bool) – Invert the selector predicate so that bitstrings which obey selector(bitstring) == False are selected and returned.

Return type

MeasurementResult

## Zero Noise Extrapolation#

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

High-level zero-noise extrapolation tools.

mitiq.zne.zne.execute_with_zne(circuit, executor, observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#

Estimates the error-mitigated expectation value associated to the input circuit, via the application of zero-noise extrapolation (ZNE).

Parameters
Return type

float

Returns

The expectation value estimated with ZNE.

mitiq.zne.zne.mitigate_executor(executor, observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#

Returns a modified version of the input ‘executor’ which is error-mitigated with zero-noise extrapolation (ZNE).

Parameters
Return type

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

Returns

The error-mitigated version of the input executor.

mitiq.zne.zne.zne_decorator(observable=None, *, factory=None, scale_noise=<function fold_gates_at_random>, num_to_average=1)[source]#

Decorator which adds an error-mitigation layer based on zero-noise extrapolation (ZNE) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a QuantumResult (e.g. an expectation value).

Parameters
Return type

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

Returns

The error-mitigating decorator to be applied to an executor function.

### Inference and Extrapolation: Factories#

Classes corresponding to different zero-noise extrapolation methods.

class mitiq.zne.inference.AdaExpFactory(steps, scale_factor=2.0, asymptote=None, avoid_log=False, max_scale_factor=6.0)[source]#

Factory object implementing an adaptive zero-noise extrapolation algorithm assuming an exponential ansatz y(x) = a + b * exp(-c * x), with c > 0.

The noise scale factors are are chosen adaptively at each step, depending on the history of collected results.

If y(x->inf) is unknown, the ansatz y(x) is fitted with a non-linear optimization.

If y(x->inf) is given and avoid_log=False, the exponential model is mapped into a linear model by logarithmic transformation.

Parameters
• steps (int) – The number of optimization steps. At least 3 are necessary.

• scale_factor (float) – The second noise scale factor (the first is always 1.0). Further scale factors are adaptively determined.

• asymptote (Optional[float]) – The infinite-noise limit y(x->inf) (optional argument).

• avoid_log (bool) – If set to True, the exponential model is not linearized with a logarithm and a non-linear fit is applied even if asymptote is not None. The default value is False.

• max_scale_factor (float) – Maximum noise scale factor. Default is 6.0.

Raises
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
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
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
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 [6].

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 [6].

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 [6].

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

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

Circuit

Returns

The parameter noise scaled circuit.