qp.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:
tape (QNode or QuantumTape or Callable) – A quantum circuit (QNode or quantum function).
- Returns:
The transformed circuit as described in
qp.transform.- Return type:
qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]
Example
You can apply the transform directly on a
QNode.import pennylane as qp dev = qp.device('default.qubit', wires=3) @qp.transforms.undo_swaps @qp.qnode(device=dev) def circuit(): qp.Hadamard(wires=0) qp.X(1) qp.SWAP(wires=[0,1]) qp.SWAP(wires=[0,2]) qp.Y(0) return qp.expval(qp.Z(0))
>>> print(qp.draw(circuit)()) 0: ──Y─┤ <Z> 1: ──H─┤ 2: ──X─┤
The SWAP gates are removed before execution.
Usage Details
Consider the following quantum function:
def qfunc(): qp.Hadamard(wires=0) qp.X(1) qp.SWAP(wires=[0,1]) qp.SWAP(wires=[0,2]) qp.Y(0) return qp.expval(qp.Z(0))
>>> dev = qp.device('default.qubit', wires=3) >>> qnode = qp.QNode(qfunc, dev) >>> print(qp.draw(qnode)()) 0: ──H─╭SWAP─╭SWAP──Y─┤ <Z> 1: ──X─╰SWAP─│────────┤ 2: ──────────╰SWAP────┤
We can remove the SWAP gates by running the
undo_swaptransform, where the wires involved in the SWAP gates are interchanged:>>> optimized_qnode = undo_swaps(qnode) >>> print(qp.draw(optimized_qnode)()) 0: ──Y─┤ <Z> 1: ──H─┤ 2: ──X─┤
Gates are iterated through from right to left, where non-SWAP gates are ignored. The first gate is a
Ygate, which is left to act on wire0. Next, the right-most SWAP gate acting on wires(0, 2)is removed, and the wires are manually swapped; wire2now becomes wire0, and vice versa. Next, the SWAP gate acting on wires(0, 1)is removed and the wires are interchanged.Altogether, this affects the wire labels as follows, where the operations to the left of both SWAP gates have their wire labels changed accordingly.
wire
0changes to wire2which changes to wire1. This moves theHgate from wire0to wire1.wire
2changes to wire0.wire
1changes to wire2. This moves theXgate from wire1to wire2.