-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
86 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
qopt_best_practices/transpilation/swap_cancellation_pass.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
"""Pass to remove SWAP gates that are not needed.""" | ||
|
||
from qiskit.dagcircuit import DAGOutNode, DAGCircuit | ||
from qiskit.transpiler import TransformationPass | ||
|
||
|
||
class SwapToFinalMapping(TransformationPass): | ||
"""Absorb any redundent SWAPs in the final layout. | ||
This pass should be executed after a SWAPStrategy has been applied to a block | ||
of commuting gates. It will remove any final redundent SWAP gates and absorb | ||
them into the virtual layout. This effectively undoes any possibly redundent | ||
SWAP gates that the SWAPStrategy may have inserted. | ||
""" | ||
|
||
def run(self, dag: DAGCircuit): | ||
"""run the pass.""" | ||
|
||
qmap = self.property_set["virtual_permutation_layout"] | ||
|
||
qreg = dag.qregs[next(iter(dag.qregs))] | ||
|
||
# This will remove SWAP gates that are applied before anything else | ||
# This remove is executed multiple times until there are no more SWAP | ||
# gates left to remove. Note: a more inteligent DAG traversal could | ||
# be implemented here. | ||
|
||
done = False | ||
|
||
while not done: | ||
permuted = False | ||
for node in dag.topological_op_nodes(): | ||
if node.op.name == "swap": | ||
successors = list(dag.successors(node)) | ||
if len(successors) == 2: | ||
if all(isinstance(successors[idx], DAGOutNode) for idx in [0, 1]): | ||
bits = [qreg.index(qubit) for qubit in node.qargs] | ||
qmap[bits[0]], qmap[bits[1]] = qmap[bits[1]], qmap[bits[0]] | ||
dag.remove_op_node(node) | ||
permuted = True | ||
|
||
done = not permuted | ||
|
||
return dag |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters