Skip to content

qiskit_pytest_helper.circuits

Typed helpers to inspect and transpile circuits in unit tests.

Qiskit's annotations of Operator.data and QuantumCircuit.count_ops are too loose or wrong for type checkers, so tests use these helpers instead.

Functions:

  • unitary_matrix –

    Return the dense unitary matrix of a circuit or operator.

  • gate_counts –

    Return the number of gates of each name in the circuit.

  • transpile_exactly –

    Transpile the circuit for the backend without approximating it.

Attributes:

EXACT_OPTIMIZATION_LEVEL module-attribute

EXACT_OPTIMIZATION_LEVEL = 1

The highest transpiler optimization level that keeps circuits exact.

From level 2, the transpiler removes gates it deems equivalent to the identity, e.g. rotations by angles of 1e-7, which changes the amplitudes by as much.

unitary_matrix

unitary_matrix(circuit: QuantumCircuit | Operator) -> NDArray[complex128]

Return the dense unitary matrix of a circuit or operator.

Source code in packages-dev/qiskit-pytest-helper/src/qiskit_pytest_helper/circuits.py
15
16
17
18
def unitary_matrix(circuit: QuantumCircuit | Operator) -> npt.NDArray[np.complex128]:
    """Return the dense unitary matrix of a circuit or operator."""
    operator = circuit if isinstance(circuit, Operator) else Operator(circuit)
    return np.asarray(operator.data, dtype=np.complex128)

gate_counts

gate_counts(circuit: QuantumCircuit) -> dict[str, int]

Return the number of gates of each name in the circuit.

Source code in packages-dev/qiskit-pytest-helper/src/qiskit_pytest_helper/circuits.py
21
22
23
def gate_counts(circuit: QuantumCircuit) -> dict[str, int]:
    """Return the number of gates of each name in the circuit."""
    return {str(name): count for name, count in circuit.count_ops().items()}

transpile_exactly

transpile_exactly(circuit: QuantumCircuit, backend: BackendV2) -> QuantumCircuit

Transpile the circuit for the backend without approximating it.

Source code in packages-dev/qiskit-pytest-helper/src/qiskit_pytest_helper/circuits.py
34
35
36
def transpile_exactly(circuit: QuantumCircuit, backend: BackendV2) -> QuantumCircuit:
    """Transpile the circuit for the backend without approximating it."""
    return transpile(circuit, backend, optimization_level=EXACT_OPTIMIZATION_LEVEL)