Circuits

The divi.circuits module provides circuit abstractions for quantum program generation, execution, and error mitigation.

Core Circuit Classes

Warning

Developer-Facing Classes: The core circuit classes (CircuitBundle and MetaCircuit) are intended for advanced users and developers. Most users should interact with circuits through higher-level APIs in the divi.qprog module.

class CircuitBundle(executables)[source]

Bases: object

Represents a bundle of logically related quantum circuits.

A CircuitBundle is typically generated from a single MetaCircuit by instantiating it with concrete parameters. It may contain multiple executable circuits due to measurement grouping or error mitigation protocols. Each executable circuit has a QASM representation and a unique tag for identification.

executables: tuple[ExecutableQASMCircuit, ...]

Tuple of executable circuits.

__str__()[source]

Return a string representation of the circuit bundle.

Returns:

String in format “CircuitBundle ({num_executables} executables)”.

Return type:

str

property tags: list[str]

A list of tags for all executables in the bundle.

property qasm_circuits: list[str]

A list of QASM strings for all executables in the bundle.

__init__(executables)
class MetaCircuit(source_circuit, symbols, grouping_strategy=None, qem_protocol=None, precision=8)[source]

Bases: object

A parameterized quantum circuit template for batch circuit generation.

MetaCircuit represents a symbolic quantum circuit that can be instantiated multiple times with different parameter values. It handles circuit compilation, observable grouping, and measurement decomposition for efficient execution.

source_circuit: QuantumScript

The PennyLane quantum circuit with symbolic parameters.

symbols: ndarray[Any, dtype[object_]]

Array of sympy symbols used as circuit parameters.

grouping_strategy: Optional[Literal['wires', 'default', 'qwc', '_backend_expval']] = None

Strategy for grouping commuting observables.

qem_protocol: QEMProtocol | None = None

Quantum error mitigation protocol to apply.

precision: int = 8

Number of decimal places for parameter values in QASM conversion.

__init__(source_circuit, symbols, grouping_strategy=None, qem_protocol=None, precision=8)
measurement_groups: tuple[tuple[Operator, ...], ...]
postprocessing_fn: Callable
__post_init__()[source]

Compiles the circuit template after initialization.

This method performs several steps: 1. Decomposes the source circuit’s measurement into single-term observables. 2. Groups commuting observables according to the specified strategy. 3. Generates a post-processing function to correctly combine measurement results. 4. Compiles the circuit body and measurement instructions into QASM strings.

__getstate__()[source]

Prepare the MetaCircuit for pickling.

Serializes the postprocessing function using dill since regular pickle cannot handle certain PennyLane function objects.

Returns:

State dictionary with serialized postprocessing function.

Return type:

dict

__setstate__(state)[source]

Restore the MetaCircuit from a pickled state.

Deserializes the postprocessing function that was serialized with dill during pickling.

Parameters:

state (dict) – State dictionary from pickling with serialized postprocessing function.

initialize_circuit_from_params(param_list, tag_prefix='', precision=None)[source]

Instantiate a concrete CircuitBundle by substituting symbolic parameters with values.

Takes a list of parameter values and creates a fully instantiated CircuitBundle by replacing all symbolic parameters in the QASM representations with their concrete numerical values.

Parameters:
  • param_list – Array of numerical parameter values to substitute for symbols. Must match the length and order of self.symbols.

  • tag_prefix (str, optional) – Prefix to prepend to circuit tags for identification. Defaults to “”.

  • precision (int | None, optional) – Number of decimal places for parameter values in the QASM output. If None, uses the precision set on this MetaCircuit instance. Defaults to None.

Returns:

A new CircuitBundle instance with parameters substituted and proper

tags for identification.

Return type:

CircuitBundle

Note

The main circuit’s parameters are still in symbol form. Not sure if it is necessary for any useful application to parameterize them.

class ExecutableQASMCircuit(tag, qasm)[source]

Bases: object

Represents a single, executable QASM circuit with its associated tag.

tag: str
qasm: str
__init__(tag, qasm)

QASM Integration

QASM Generation Function

to_openqasm(main_qscript, measurement_groups, measure_all=True, precision=None, return_measurements_separately=False, symbols=None, qem_protocol=None)[source]

Serialize the circuit as an OpenQASM 2.0 program.

A modified version of PennyLane’s function that is more compatible with having several measurements and incorporates modifications introduced by splitting transforms, as well as error mitigation through folding.

The measurement outputs can be restricted to only those specified in the script by setting measure_all=False.

Note

The serialized OpenQASM program assumes that gate definitions in qelib1.inc are available.

Parameters:
  • main_qscript (QuantumScript) – the quantum circuit to be converted, as a QuantumScript/QuantumTape object.

  • measurement_groups (list[list]) – A list of list of commuting observables, generated by the grouping Pennylane transformation.

  • measure_all (bool) – whether to perform a computational basis measurement on all qubits or just those specified in the script

  • precision (int) – decimal digits to display for parameters

  • return_measurements_separately (bool) – whether to not append the measurement instructions and their diagonalizations to the main circuit QASM code and return separately.

  • symbols (list) – Sympy symbols present in the circuit. Needed for some QEM routines.

  • qem_protocol (QEMProtocol) – An optional QEMProtocol object for error mitigation, which may modify the circuit.

Returns:

OpenQASM serialization of the circuit

Return type:

list[str] or tuple[str, list[str]]

QASM Validation Functions

validate_qasm(src)[source]

Validate QASM syntax, raising SyntaxError on error.

Return type:

None

validate_qasm_count_qubits(src)[source]

Validate QASM and return the total number of qubits, raising SyntaxError on error.

Return type:

int

is_valid_qasm(src)[source]

Check if QASM is valid, returning True/False without raising exceptions.

Return type:

bool

Error Mitigation Protocols

Divi provides quantum error mitigation (QEM) capabilities to improve the accuracy of quantum computations in the presence of noise.

class QEMProtocol[source]

Bases: ABC

Abstract Base Class for Quantum Error Mitigation (QEM) protocols.

All concrete QEM protocols should inherit from this class and implement the abstract methods and properties. This ensures a consistent interface across different mitigation techniques.

abstract property name: str
abstract modify_circuit(cirq_circuit)[source]

Modifies a given Cirq circuit into one or more new circuits required by the QEM protocol.

For example, a Zero Noise Extrapolation (ZNE) protocol might produce multiple scaled versions of the input circuit. A simple mitigation protocol might return the original circuit unchanged.

Parameters:

cirq_circuit (cirq.Circuit) – The input quantum circuit to be modified.

Returns:

A sequence (e.g., list or tuple) of

Cirq circuits to be executed.

Return type:

Sequence[cirq.Circuit]

abstract postprocess_results(results)[source]

Applies post-processing (e.g., extrapolation, filtering) to the results obtained from executing the modified circuits.

This method takes the raw output from quantum circuit executions (typically a sequence of expectation values or probabilities) and applies the core error mitigation logic to produce a single, mitigated result.

Parameters:

results (Sequence[float]) – A sequence of floating-point results, corresponding to the executions of the circuits returned by modify_circuit.

Returns:

The single, mitigated result after post-processing.

Return type:

float

class ZNE(scale_factors, folding_fn, extrapolation_factory)[source]

Bases: QEMProtocol

Implements the Zero Noise Extrapolation (ZNE) quantum error mitigation protocol.

This protocol uses Mitiq’s functionalities to construct noise-scaled circuits and then extrapolate to the zero-noise limit based on the obtained results.

Initializes a ZNE protocol instance.

Parameters:
  • scale_factors (Sequence[float]) – A sequence of noise scale factors to be applied to the circuits. These factors typically range from 1.0 upwards.

  • folding_fn (Callable) – A callable (e.g., a functools.partial object) that defines how the circuit should be “folded” to increase noise. This function must accept a cirq.Circuit and a float (scale factor) as its first two arguments.

  • extrapolation_factory (mitiq.zne.inference.Factory) – An instance of Mitiq’s Factory class, which provides the extrapolation method.

Raises:

ValueError – If scale_factors is not a sequence of numbers, folding_fn is not callable, or extrapolation_factory is not an instance of mitiq.zne.inference.Factory.

__init__(scale_factors, folding_fn, extrapolation_factory)[source]

Initializes a ZNE protocol instance.

Parameters:
  • scale_factors (Sequence[float]) – A sequence of noise scale factors to be applied to the circuits. These factors typically range from 1.0 upwards.

  • folding_fn (Callable) – A callable (e.g., a functools.partial object) that defines how the circuit should be “folded” to increase noise. This function must accept a cirq.Circuit and a float (scale factor) as its first two arguments.

  • extrapolation_factory (mitiq.zne.inference.Factory) – An instance of Mitiq’s Factory class, which provides the extrapolation method.

Raises:

ValueError – If scale_factors is not a sequence of numbers, folding_fn is not callable, or extrapolation_factory is not an instance of mitiq.zne.inference.Factory.

property name: str
property scale_factors: Sequence[float]
property folding_fn
property extrapolation_factory
modify_circuit(cirq_circuit)[source]

Modifies a given Cirq circuit into one or more new circuits required by the QEM protocol.

For example, a Zero Noise Extrapolation (ZNE) protocol might produce multiple scaled versions of the input circuit. A simple mitigation protocol might return the original circuit unchanged.

Parameters:

cirq_circuit (cirq.Circuit) – The input quantum circuit to be modified.

Returns:

A sequence (e.g., list or tuple) of

Cirq circuits to be executed.

Return type:

Sequence[cirq.Circuit]

postprocess_results(results)[source]

Applies post-processing (e.g., extrapolation, filtering) to the results obtained from executing the modified circuits.

This method takes the raw output from quantum circuit executions (typically a sequence of expectation values or probabilities) and applies the core error mitigation logic to produce a single, mitigated result.

Parameters:

results (Sequence[float]) – A sequence of floating-point results, corresponding to the executions of the circuits returned by modify_circuit.

Returns:

The single, mitigated result after post-processing.

Return type:

float

QEM Protocol Architecture

All error mitigation protocols in Divi inherit from the QEMProtocol base class, providing a consistent interface for different mitigation techniques.

class QEMProtocol[source]

Bases: ABC

Abstract Base Class for Quantum Error Mitigation (QEM) protocols.

All concrete QEM protocols should inherit from this class and implement the abstract methods and properties. This ensures a consistent interface across different mitigation techniques.

abstract property name: str
abstract modify_circuit(cirq_circuit)[source]

Modifies a given Cirq circuit into one or more new circuits required by the QEM protocol.

For example, a Zero Noise Extrapolation (ZNE) protocol might produce multiple scaled versions of the input circuit. A simple mitigation protocol might return the original circuit unchanged.

Parameters:

cirq_circuit (cirq.Circuit) – The input quantum circuit to be modified.

Returns:

A sequence (e.g., list or tuple) of

Cirq circuits to be executed.

Return type:

Sequence[cirq.Circuit]

abstract postprocess_results(results)[source]

Applies post-processing (e.g., extrapolation, filtering) to the results obtained from executing the modified circuits.

This method takes the raw output from quantum circuit executions (typically a sequence of expectation values or probabilities) and applies the core error mitigation logic to produce a single, mitigated result.

Parameters:

results (Sequence[float]) – A sequence of floating-point results, corresponding to the executions of the circuits returned by modify_circuit.

Returns:

The single, mitigated result after post-processing.

Return type:

float

Zero Noise Extrapolation (ZNE)

class ZNE(scale_factors, folding_fn, extrapolation_factory)[source]

Bases: QEMProtocol

Implements the Zero Noise Extrapolation (ZNE) quantum error mitigation protocol.

This protocol uses Mitiq’s functionalities to construct noise-scaled circuits and then extrapolate to the zero-noise limit based on the obtained results.

Initializes a ZNE protocol instance.

Parameters:
  • scale_factors (Sequence[float]) – A sequence of noise scale factors to be applied to the circuits. These factors typically range from 1.0 upwards.

  • folding_fn (Callable) – A callable (e.g., a functools.partial object) that defines how the circuit should be “folded” to increase noise. This function must accept a cirq.Circuit and a float (scale factor) as its first two arguments.

  • extrapolation_factory (mitiq.zne.inference.Factory) – An instance of Mitiq’s Factory class, which provides the extrapolation method.

Raises:

ValueError – If scale_factors is not a sequence of numbers, folding_fn is not callable, or extrapolation_factory is not an instance of mitiq.zne.inference.Factory.

__init__(scale_factors, folding_fn, extrapolation_factory)[source]

Initializes a ZNE protocol instance.

Parameters:
  • scale_factors (Sequence[float]) – A sequence of noise scale factors to be applied to the circuits. These factors typically range from 1.0 upwards.

  • folding_fn (Callable) – A callable (e.g., a functools.partial object) that defines how the circuit should be “folded” to increase noise. This function must accept a cirq.Circuit and a float (scale factor) as its first two arguments.

  • extrapolation_factory (mitiq.zne.inference.Factory) – An instance of Mitiq’s Factory class, which provides the extrapolation method.

Raises:

ValueError – If scale_factors is not a sequence of numbers, folding_fn is not callable, or extrapolation_factory is not an instance of mitiq.zne.inference.Factory.

property name: str
property scale_factors: Sequence[float]
property folding_fn
property extrapolation_factory
modify_circuit(cirq_circuit)[source]

Modifies a given Cirq circuit into one or more new circuits required by the QEM protocol.

For example, a Zero Noise Extrapolation (ZNE) protocol might produce multiple scaled versions of the input circuit. A simple mitigation protocol might return the original circuit unchanged.

Parameters:

cirq_circuit (cirq.Circuit) – The input quantum circuit to be modified.

Returns:

A sequence (e.g., list or tuple) of

Cirq circuits to be executed.

Return type:

Sequence[cirq.Circuit]

postprocess_results(results)[source]

Applies post-processing (e.g., extrapolation, filtering) to the results obtained from executing the modified circuits.

This method takes the raw output from quantum circuit executions (typically a sequence of expectation values or probabilities) and applies the core error mitigation logic to produce a single, mitigated result.

Parameters:

results (Sequence[float]) – A sequence of floating-point results, corresponding to the executions of the circuits returned by modify_circuit.

Returns:

The single, mitigated result after post-processing.

Return type:

float

No Mitigation Protocol

class _NoMitigation[source]

Bases: QEMProtocol

A dummy default mitigation protocol.

property name: str
modify_circuit(cirq_circuit)[source]

Modifies a given Cirq circuit into one or more new circuits required by the QEM protocol.

For example, a Zero Noise Extrapolation (ZNE) protocol might produce multiple scaled versions of the input circuit. A simple mitigation protocol might return the original circuit unchanged.

Parameters:

cirq_circuit (cirq.Circuit) – The input quantum circuit to be modified.

Returns:

A sequence (e.g., list or tuple) of

Cirq circuits to be executed.

Return type:

Sequence[cirq.Circuit]

postprocess_results(results)[source]

Returns the single result provided, ensuring only one result is given.

If multiple results are provided, it raises a RuntimeError, as this protocol expects a single measurement outcome for its input circuit.

Parameters:

results (Sequence[float]) – A sequence containing a single floating-point result.

Returns:

The single result from the sequence.

Return type:

float

Raises:

RuntimeError – If more than one result is provided.