fuse_adjacents#

fuse_adjacents(qc: QuantumCircuit) QuantumCircuit[source]#

Cancel adjacent gate–inverse-gate pairs.

How it works

  1. Build a directed acyclic graph (DAG) where each instruction is a node. Edges connect an instruction to its immediate successor on the same qubit or classical bit.

  2. Walk through the instructions in circuit order. For each instruction whose predecessors all agree on a single node (i.e. the instruction is directly adjacent to its predecessor on every qubit it touches), call _fuse_instructions to attempt to merge or cancel the pair.

  3. When a pair is cancelled, both nodes are removed from the DAG and their qubit edges are rewired to bridge over the gap.

  4. When a pair is fused into a new gate, the predecessor node is replaced with the fused result and the successor node is removed.

  5. After all candidate pairs have been inspected, the surviving nodes are emitted in topological order, which preserves the circuit’s original dependency structure.

What it cancels / fuses

  • Self-inverse gates: X·X, H·H, CX·CX, CZ·CZ, SWAP·SWAP, …

  • Parameterised rotations with opposite angles: Rz(θ)·Rz(−θ), Rx(θ)·Rx(−θ), Ry(θ)·Ry(−θ)

  • Phase gates: P(θ)·P(−θ)

  • Cross-type fusion: Rz(θ)·P(−θ)P(0)·Gphase

  • Controlled operations whose base gates cancel

  • Partial fusion of SWAP with neighbouring CX, CP, RZZ into fewer CX gates

Global phase tracking

Gates that carry a global_phase attribute (notably Rz) contribute their global phase to a running total. At the end of the pass, any non-zero accumulated phase is emitted as a single gphase gate.

Parameters:
qcQuantumCircuit

The input circuit.

Returns:
QuantumCircuit

A new circuit with adjacent inverse gates cancelled.

Examples

Cancel adjacent self-inverse gates (e.g. CX·CX):

>>> from qrisp import QuantumCircuit, PassManager
>>> from qrisp import fuse_adjacents
>>> qc = QuantumCircuit(2)
>>> qc.cx(0, 1)
>>> qc.cx(0, 1)   # CX is self-inverse → cancelled
>>> print(qc)

qb_96: ──■────■──
       ┌─┴─┐┌─┴─┐
qb_97: ┤ X ├┤ X ├
       └───┘└───┘
>>>
>>> pm = PassManager()
>>> pm += fuse_adjacents
>>> optimized_qc = pm.run(qc)
>>> print(optimized_qc)

qb_96:

qb_97:

Fuse a SWAP with a neighbouring CX into fewer gates:

>>> qc = QuantumCircuit(2)
>>> qc.swap(0, 1)
>>> qc.cx(0, 1)
>>> pm = PassManager()
>>> pm += fuse_adjacents
>>> pm += decompose()
>>> optimized = pm.run(qc)
>>> # SWAP·CX fused into a cheaper compound gate rather than
>>> # decomposing into 3 CX + 1 CX = 4 CX gates.
>>> print(optimized)
             ┌───┐
qb_110: ──■──┤ X ├
        ┌─┴─┐└─┬─┘
qb_111: ┤ X ├──■──
        └───┘