Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

undo_swaps #1960

Merged
merged 19 commits into from Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Expand Up @@ -350,6 +350,9 @@
* The `merge_amplitude_embedding` transformation has been created to automatically merge all gates of this type into one.
[(#1933)](https://github.com/PennyLaneAI/pennylane/pull/1933)

* The `undo_swaps` transformation has been created to automatically remove all swaps of a circuit.
[(#1960)](https://github.com/PennyLaneAI/pennylane/pull/1960)

<h3>Improvements</h3>

* Tests do not loop over automatically imported and instantiated operations any more,
Expand Down
4 changes: 4 additions & 0 deletions pennylane/transforms/__init__.py
Expand Up @@ -67,6 +67,9 @@
~transforms.merge_rotations
~transforms.single_qubit_fusion
~transforms.unitary_to_rot
~transforms.merge_amplitude_embedding
~transforms.remove_barrier
~transforms.undo_swaps

There are also utility functions and decompositions available that assist with
both transforms, and decompositions within the larger PennyLane codebase.
Expand Down Expand Up @@ -131,6 +134,7 @@
single_qubit_fusion,
merge_amplitude_embedding,
remove_barrier,
undo_swaps,
dime10 marked this conversation as resolved.
Show resolved Hide resolved
)
from .specs import specs
from .qmc import apply_controlled_Q, quantum_monte_carlo
Expand Down
1 change: 1 addition & 0 deletions pennylane/transforms/optimization/__init__.py
Expand Up @@ -21,3 +21,4 @@
from .merge_rotations import merge_rotations
from .merge_amplitude_embedding import merge_amplitude_embedding
from .single_qubit_fusion import single_qubit_fusion
from .undo_swaps import undo_swaps
108 changes: 108 additions & 0 deletions pennylane/transforms/optimization/undo_swaps.py
@@ -0,0 +1,108 @@
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Transform that eliminates the swap operators by reordering the wires."""
# pylint: disable=too-many-branches
from pennylane import apply
from pennylane.transforms import qfunc_transform
from pennylane.wires import Wires
from pennylane.tape import stop_recording


@qfunc_transform
def undo_swaps(tape):
"""Quantum function transform to remove SWAP gates by running from right
to left through the circuit changing the position of the qubits accordingly.

Args:
qfunc (function): A quantum function.

Returns:
function: the transformed quantum function

**Example**

Consider the following quantum function:

.. code-block:: python

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)(1, 2))
0: ──Y──┤ ⟨Z⟩
1: ──H──┤
2: ──X──┤

"""
# Make a working copy of the list to traverse
list_copy = tape.operations.copy()
list_copy.reverse()

map_wires = {wire: wire for wire in tape.wires}
gates = []

def _change_wires(wires):
change_wires = Wires([])
wires = wires.toarray()
for wire in wires:
change_wires += map_wires[wire]
return change_wires

with stop_recording():
while len(list_copy) > 0:
current_gate = list_copy[0]
params = current_gate.parameters
if current_gate.name != "SWAP":
if len(params) == 0:
gates.append(type(current_gate)(wires=_change_wires(current_gate.wires)))
else:
gates.append(
type(current_gate)(*params, wires=_change_wires(current_gate.wires))
)

else:
swap_wires_0, swap_wires_1 = current_gate.wires
map_wires[swap_wires_0], map_wires[swap_wires_1] = (
map_wires[swap_wires_1],
map_wires[swap_wires_0],
)
list_copy.pop(0)

gates.reverse()

for m in tape.measurements:
gates.append(m)

for gate in gates:
apply(gate)