qml.transforms.undo_swaps

undo_swaps(tape)[source]

Quantum function transform to remove SWAP gates by running from right to left through the circuit changing the position of the qubits accordingly.

Parameters

qfunc (function) – A quantum function.

Returns

the transformed quantum function

Return type

function

Example

Consider the following quantum function:

def qfunc():
    qml.Hadamard(wires=0)
    qml.PauliX(wires=1)
    qml.SWAP(wires=[0,1])
    qml.SWAP(wires=[0,2])
    qml.PauliY(wires=0)
    return qml.expval(qml.PauliZ(0))

The circuit before optimization:

>>> dev = qml.device('default.qubit', wires=3)
>>> qnode = qml.QNode(qfunc, dev)
>>> print(qml.draw(qnode)())
    0: ──H──╭SWAP──╭SWAP──Y──┤ ⟨Z⟩
    1: ──X──╰SWAP──│─────────┤
    2: ────────────╰SWAP─────┤

We can remove the SWAP gates by running the undo_swap transform:

>>> optimized_qfunc = undo_swaps(qfunc)
>>> optimized_qnode = qml.QNode(optimized_qfunc, dev)
>>> print(qml.draw(optimized_qnode)())
    0: ──Y──┤ ⟨Z⟩
    1: ──H──┤
    2: ──X──┤