We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Flipping of gate direction in Transpiler for CZ gate
### What should we add?

The current version of the transpiler raises the following error when attempting to set the basis gate of a backend as `cz` 

` 'Flipping of gate direction is only supported for CX, ECR, and RZX at this time, not cz.' `

As far as I'm aware and through my own testing flipping of a CZ should be easy to implement as it's "flip" produces the same unitary operator. There is no direct identity needed. 

If this could get added that would be great! I would have done this via a pull request myself but it seems "too easy" of a solution that I must be missing something.

The Qiskit file that would need changing. 
https://github.com/Qiskit/qiskit-terra/blob/1312624309526812eb62b97e0d47699d46649a25/qiskit/transpiler/passes/utils/gate_direction.py



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qiskit/transpiler/passes/utils/gate_direction.py`
Content:
```
1 # This code is part of Qiskit.
2 #
3 # (C) Copyright IBM 2017, 2021.
4 #
5 # This code is licensed under the Apache License, Version 2.0. You may
6 # obtain a copy of this license in the LICENSE.txt file in the root directory
7 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8 #
9 # Any modifications or derivative works of this code must retain this
10 # copyright notice, and modified files need to carry a notice indicating
11 # that they have been altered from the originals.
12 
13 """Rearrange the direction of the cx nodes to match the directed coupling map."""
14 
15 from math import pi
16 
17 from qiskit.transpiler.layout import Layout
18 from qiskit.transpiler.basepasses import TransformationPass
19 from qiskit.transpiler.exceptions import TranspilerError
20 
21 from qiskit.circuit import QuantumRegister
22 from qiskit.dagcircuit import DAGCircuit
23 from qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, ECRGate, RZXGate
24 
25 
26 class GateDirection(TransformationPass):
27     """Modify asymmetric gates to match the hardware coupling direction.
28 
29     This pass makes use of the following identities::
30 
31                              ┌───┐┌───┐┌───┐
32         q_0: ──■──      q_0: ┤ H ├┤ X ├┤ H ├
33              ┌─┴─┐  =        ├───┤└─┬─┘├───┤
34         q_1: ┤ X ├      q_1: ┤ H ├──■──┤ H ├
35              └───┘           └───┘     └───┘
36 
37              ┌──────┐          ┌───────────┐┌──────┐┌───┐
38         q_0: ┤0     ├     q_0: ┤ RY(-pi/2) ├┤1     ├┤ H ├
39              │  ECR │  =       └┬──────────┤│  ECR │├───┤
40         q_1: ┤1     ├     q_1: ─┤ RY(pi/2) ├┤0     ├┤ H ├
41              └──────┘           └──────────┘└──────┘└───┘
42 
43              ┌──────┐          ┌───┐┌──────┐┌───┐
44         q_0: ┤0     ├     q_0: ┤ H ├┤1     ├┤ H ├
45              │  RZX │  =       ├───┤│  RZX │├───┤
46         q_1: ┤1     ├     q_1: ┤ H ├┤0     ├┤ H ├
47              └──────┘          └───┘└──────┘└───┘
48     """
49 
50     def __init__(self, coupling_map, target=None):
51         """GateDirection pass.
52 
53         Args:
54             coupling_map (CouplingMap): Directed graph represented a coupling map.
55             target (Target): The backend target to use for this pass. If this is specified
56                 it will be used instead of the coupling map
57         """
58         super().__init__()
59         self.coupling_map = coupling_map
60         self.target = target
61 
62         # Create the replacement dag and associated register.
63         self._cx_dag = DAGCircuit()
64         qr = QuantumRegister(2)
65         self._cx_dag.add_qreg(qr)
66         self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])
67         self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])
68         self._cx_dag.apply_operation_back(CXGate(), [qr[1], qr[0]], [])
69         self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])
70         self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])
71 
72         self._ecr_dag = DAGCircuit()
73         qr = QuantumRegister(2)
74         self._ecr_dag.add_qreg(qr)
75         self._ecr_dag.apply_operation_back(RYGate(-pi / 2), [qr[0]], [])
76         self._ecr_dag.apply_operation_back(RYGate(pi / 2), [qr[1]], [])
77         self._ecr_dag.apply_operation_back(ECRGate(), [qr[1], qr[0]], [])
78         self._ecr_dag.apply_operation_back(HGate(), [qr[0]], [])
79         self._ecr_dag.apply_operation_back(HGate(), [qr[1]], [])
80 
81     @staticmethod
82     def _rzx_dag(parameter):
83         _rzx_dag = DAGCircuit()
84         qr = QuantumRegister(2)
85         _rzx_dag.add_qreg(qr)
86         _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])
87         _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])
88         _rzx_dag.apply_operation_back(RZXGate(parameter), [qr[1], qr[0]], [])
89         _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])
90         _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])
91         return _rzx_dag
92 
93     def run(self, dag):
94         """Run the GateDirection pass on `dag`.
95 
96         Flips the cx nodes to match the directed coupling map. Modifies the
97         input dag.
98 
99         Args:
100             dag (DAGCircuit): DAG to map.
101 
102         Returns:
103             DAGCircuit: The rearranged dag for the coupling map
104 
105         Raises:
106             TranspilerError: If the circuit cannot be mapped just by flipping the
107                 cx nodes.
108         """
109         trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
110         layout_map = trivial_layout.get_virtual_bits()
111         if len(dag.qregs) > 1:
112             raise TranspilerError(
113                 "GateDirection expects a single qreg input DAG,"
114                 "but input DAG had qregs: {}.".format(dag.qregs)
115             )
116         if self.target is None:
117             cmap_edges = set(self.coupling_map.get_edges())
118             if not cmap_edges:
119                 return dag
120 
121             self.coupling_map.compute_distance_matrix()
122 
123             dist_matrix = self.coupling_map.distance_matrix
124 
125             for node in dag.two_qubit_ops():
126                 control = node.qargs[0]
127                 target = node.qargs[1]
128 
129                 physical_q0 = layout_map[control]
130                 physical_q1 = layout_map[target]
131 
132                 if dist_matrix[physical_q0, physical_q1] != 1:
133                     raise TranspilerError(
134                         "The circuit requires a connection between physical "
135                         "qubits %s and %s" % (physical_q0, physical_q1)
136                     )
137 
138                 if (physical_q0, physical_q1) not in cmap_edges:
139                     if node.name == "cx":
140                         dag.substitute_node_with_dag(node, self._cx_dag)
141                     elif node.name == "ecr":
142                         dag.substitute_node_with_dag(node, self._ecr_dag)
143                     elif node.name == "rzx":
144                         dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))
145                     else:
146                         raise TranspilerError(
147                             f"Flipping of gate direction is only supported "
148                             f"for CX, ECR, and RZX at this time, not {node.name}."
149                         )
150         else:
151             # TODO: Work with the gate instances and only use names as look up keys.
152             # This will require iterating over the target names to build a mapping
153             # of names to gates that implement CXGate, ECRGate, RZXGate (including
154             # fixed angle variants)
155             for node in dag.two_qubit_ops():
156                 control = node.qargs[0]
157                 target = node.qargs[1]
158 
159                 physical_q0 = layout_map[control]
160                 physical_q1 = layout_map[target]
161 
162                 if node.name == "cx":
163                     if (physical_q0, physical_q1) in self.target["cx"]:
164                         continue
165                     if (physical_q1, physical_q0) in self.target["cx"]:
166                         dag.substitute_node_with_dag(node, self._cx_dag)
167                     else:
168                         raise TranspilerError(
169                             "The circuit requires a connection between physical "
170                             "qubits %s and %s for cx" % (physical_q0, physical_q1)
171                         )
172                 elif node.name == "ecr":
173                     if (physical_q0, physical_q1) in self.target["ecr"]:
174                         continue
175                     if (physical_q1, physical_q0) in self.target["ecr"]:
176                         dag.substitute_node_with_dag(node, self._ecr_dag)
177                     else:
178                         raise TranspilerError(
179                             "The circuit requires a connection between physical "
180                             "qubits %s and %s for ecr" % (physical_q0, physical_q1)
181                         )
182                 elif node.name == "rzx":
183                     if (physical_q0, physical_q1) in self.target["rzx"]:
184                         continue
185                     if (physical_q1, physical_q0) in self.target["rzx"]:
186                         dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))
187                     else:
188                         raise TranspilerError(
189                             "The circuit requires a connection between physical "
190                             "qubits %s and %s for rzx" % (physical_q0, physical_q1)
191                         )
192                 else:
193                     raise TranspilerError(
194                         f"Flipping of gate direction is only supported "
195                         f"for CX, ECR, and RZX at this time, not {node.name}."
196                     )
197         return dag
198
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qiskit/transpiler/passes/utils/gate_direction.py b/qiskit/transpiler/passes/utils/gate_direction.py
--- a/qiskit/transpiler/passes/utils/gate_direction.py
+++ b/qiskit/transpiler/passes/utils/gate_direction.py
@@ -20,7 +20,7 @@
 
 from qiskit.circuit import QuantumRegister
 from qiskit.dagcircuit import DAGCircuit
-from qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, ECRGate, RZXGate
+from qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, CZGate, ECRGate, RZXGate
 
 
 class GateDirection(TransformationPass):
@@ -78,6 +78,11 @@
         self._ecr_dag.apply_operation_back(HGate(), [qr[0]], [])
         self._ecr_dag.apply_operation_back(HGate(), [qr[1]], [])
 
+        self._cz_dag = DAGCircuit()
+        qr = QuantumRegister(2)
+        self._cz_dag.add_qreg(qr)
+        self._cz_dag.apply_operation_back(CZGate(), [qr[1], qr[0]], [])
+
     @staticmethod
     def _rzx_dag(parameter):
         _rzx_dag = DAGCircuit()
@@ -138,6 +143,8 @@
                 if (physical_q0, physical_q1) not in cmap_edges:
                     if node.name == "cx":
                         dag.substitute_node_with_dag(node, self._cx_dag)
+                    elif node.name == "cz":
+                        dag.substitute_node_with_dag(node, self._cz_dag)
                     elif node.name == "ecr":
                         dag.substitute_node_with_dag(node, self._ecr_dag)
                     elif node.name == "rzx":
@@ -169,6 +176,16 @@
                             "The circuit requires a connection between physical "
                             "qubits %s and %s for cx" % (physical_q0, physical_q1)
                         )
+                elif node.name == "cz":
+                    if (physical_q0, physical_q1) in self.target["cz"]:
+                        continue
+                    if (physical_q1, physical_q0) in self.target["cz"]:
+                        dag.substitute_node_with_dag(node, self._cz_dag)
+                    else:
+                        raise TranspilerError(
+                            "The circuit requires a connection between physical "
+                            "qubits %s and %s for cz" % (physical_q0, physical_q1)
+                        )
                 elif node.name == "ecr":
                     if (physical_q0, physical_q1) in self.target["ecr"]:
                         continue

{"golden_diff": "diff --git a/qiskit/transpiler/passes/utils/gate_direction.py b/qiskit/transpiler/passes/utils/gate_direction.py\n--- a/qiskit/transpiler/passes/utils/gate_direction.py\n+++ b/qiskit/transpiler/passes/utils/gate_direction.py\n@@ -20,7 +20,7 @@\n \n from qiskit.circuit import QuantumRegister\n from qiskit.dagcircuit import DAGCircuit\n-from qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, ECRGate, RZXGate\n+from qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, CZGate, ECRGate, RZXGate\n \n \n class GateDirection(TransformationPass):\n@@ -78,6 +78,11 @@\n         self._ecr_dag.apply_operation_back(HGate(), [qr[0]], [])\n         self._ecr_dag.apply_operation_back(HGate(), [qr[1]], [])\n \n+        self._cz_dag = DAGCircuit()\n+        qr = QuantumRegister(2)\n+        self._cz_dag.add_qreg(qr)\n+        self._cz_dag.apply_operation_back(CZGate(), [qr[1], qr[0]], [])\n+\n     @staticmethod\n     def _rzx_dag(parameter):\n         _rzx_dag = DAGCircuit()\n@@ -138,6 +143,8 @@\n                 if (physical_q0, physical_q1) not in cmap_edges:\n                     if node.name == \"cx\":\n                         dag.substitute_node_with_dag(node, self._cx_dag)\n+                    elif node.name == \"cz\":\n+                        dag.substitute_node_with_dag(node, self._cz_dag)\n                     elif node.name == \"ecr\":\n                         dag.substitute_node_with_dag(node, self._ecr_dag)\n                     elif node.name == \"rzx\":\n@@ -169,6 +176,16 @@\n                             \"The circuit requires a connection between physical \"\n                             \"qubits %s and %s for cx\" % (physical_q0, physical_q1)\n                         )\n+                elif node.name == \"cz\":\n+                    if (physical_q0, physical_q1) in self.target[\"cz\"]:\n+                        continue\n+                    if (physical_q1, physical_q0) in self.target[\"cz\"]:\n+                        dag.substitute_node_with_dag(node, self._cz_dag)\n+                    else:\n+                        raise TranspilerError(\n+                            \"The circuit requires a connection between physical \"\n+                            \"qubits %s and %s for cz\" % (physical_q0, physical_q1)\n+                        )\n                 elif node.name == \"ecr\":\n                     if (physical_q0, physical_q1) in self.target[\"ecr\"]:\n                         continue\n", "issue": "Flipping of gate direction in Transpiler for CZ gate\n### What should we add?\n\nThe current version of the transpiler raises the following error when attempting to set the basis gate of a backend as `cz` \r\n\r\n` 'Flipping of gate direction is only supported for CX, ECR, and RZX at this time, not cz.' `\r\n\r\nAs far as I'm aware and through my own testing flipping of a CZ should be easy to implement as it's \"flip\" produces the same unitary operator. There is no direct identity needed. \r\n\r\nIf this could get added that would be great! I would have done this via a pull request myself but it seems \"too easy\" of a solution that I must be missing something.\r\n\r\nThe Qiskit file that would need changing. \r\nhttps://github.com/Qiskit/qiskit-terra/blob/1312624309526812eb62b97e0d47699d46649a25/qiskit/transpiler/passes/utils/gate_direction.py\r\n\r\n\n", "before_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Rearrange the direction of the cx nodes to match the directed coupling map.\"\"\"\n\nfrom math import pi\n\nfrom qiskit.transpiler.layout import Layout\nfrom qiskit.transpiler.basepasses import TransformationPass\nfrom qiskit.transpiler.exceptions import TranspilerError\n\nfrom qiskit.circuit import QuantumRegister\nfrom qiskit.dagcircuit import DAGCircuit\nfrom qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, ECRGate, RZXGate\n\n\nclass GateDirection(TransformationPass):\n    \"\"\"Modify asymmetric gates to match the hardware coupling direction.\n\n    This pass makes use of the following identities::\n\n                             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u2500\u2500\u25a0\u2500\u2500      q_0: \u2524 H \u251c\u2524 X \u251c\u2524 H \u251c\n             \u250c\u2500\u2534\u2500\u2510  =        \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u252c\u2500\u2518\u251c\u2500\u2500\u2500\u2524\n        q_1: \u2524 X \u251c      q_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2518           \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2518\n\n             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u25240     \u251c     q_0: \u2524 RY(-pi/2) \u251c\u25241     \u251c\u2524 H \u251c\n             \u2502  ECR \u2502  =       \u2514\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2502  ECR \u2502\u251c\u2500\u2500\u2500\u2524\n        q_1: \u25241     \u251c     q_1: \u2500\u2524 RY(pi/2) \u251c\u25240     \u251c\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n\n             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u25240     \u251c     q_0: \u2524 H \u251c\u25241     \u251c\u2524 H \u251c\n             \u2502  RZX \u2502  =       \u251c\u2500\u2500\u2500\u2524\u2502  RZX \u2502\u251c\u2500\u2500\u2500\u2524\n        q_1: \u25241     \u251c     q_1: \u2524 H \u251c\u25240     \u251c\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n    \"\"\"\n\n    def __init__(self, coupling_map, target=None):\n        \"\"\"GateDirection pass.\n\n        Args:\n            coupling_map (CouplingMap): Directed graph represented a coupling map.\n            target (Target): The backend target to use for this pass. If this is specified\n                it will be used instead of the coupling map\n        \"\"\"\n        super().__init__()\n        self.coupling_map = coupling_map\n        self.target = target\n\n        # Create the replacement dag and associated register.\n        self._cx_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        self._cx_dag.add_qreg(qr)\n        self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        self._cx_dag.apply_operation_back(CXGate(), [qr[1], qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])\n\n        self._ecr_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        self._ecr_dag.add_qreg(qr)\n        self._ecr_dag.apply_operation_back(RYGate(-pi / 2), [qr[0]], [])\n        self._ecr_dag.apply_operation_back(RYGate(pi / 2), [qr[1]], [])\n        self._ecr_dag.apply_operation_back(ECRGate(), [qr[1], qr[0]], [])\n        self._ecr_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._ecr_dag.apply_operation_back(HGate(), [qr[1]], [])\n\n    @staticmethod\n    def _rzx_dag(parameter):\n        _rzx_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        _rzx_dag.add_qreg(qr)\n        _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        _rzx_dag.apply_operation_back(RZXGate(parameter), [qr[1], qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        return _rzx_dag\n\n    def run(self, dag):\n        \"\"\"Run the GateDirection pass on `dag`.\n\n        Flips the cx nodes to match the directed coupling map. Modifies the\n        input dag.\n\n        Args:\n            dag (DAGCircuit): DAG to map.\n\n        Returns:\n            DAGCircuit: The rearranged dag for the coupling map\n\n        Raises:\n            TranspilerError: If the circuit cannot be mapped just by flipping the\n                cx nodes.\n        \"\"\"\n        trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())\n        layout_map = trivial_layout.get_virtual_bits()\n        if len(dag.qregs) > 1:\n            raise TranspilerError(\n                \"GateDirection expects a single qreg input DAG,\"\n                \"but input DAG had qregs: {}.\".format(dag.qregs)\n            )\n        if self.target is None:\n            cmap_edges = set(self.coupling_map.get_edges())\n            if not cmap_edges:\n                return dag\n\n            self.coupling_map.compute_distance_matrix()\n\n            dist_matrix = self.coupling_map.distance_matrix\n\n            for node in dag.two_qubit_ops():\n                control = node.qargs[0]\n                target = node.qargs[1]\n\n                physical_q0 = layout_map[control]\n                physical_q1 = layout_map[target]\n\n                if dist_matrix[physical_q0, physical_q1] != 1:\n                    raise TranspilerError(\n                        \"The circuit requires a connection between physical \"\n                        \"qubits %s and %s\" % (physical_q0, physical_q1)\n                    )\n\n                if (physical_q0, physical_q1) not in cmap_edges:\n                    if node.name == \"cx\":\n                        dag.substitute_node_with_dag(node, self._cx_dag)\n                    elif node.name == \"ecr\":\n                        dag.substitute_node_with_dag(node, self._ecr_dag)\n                    elif node.name == \"rzx\":\n                        dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))\n                    else:\n                        raise TranspilerError(\n                            f\"Flipping of gate direction is only supported \"\n                            f\"for CX, ECR, and RZX at this time, not {node.name}.\"\n                        )\n        else:\n            # TODO: Work with the gate instances and only use names as look up keys.\n            # This will require iterating over the target names to build a mapping\n            # of names to gates that implement CXGate, ECRGate, RZXGate (including\n            # fixed angle variants)\n            for node in dag.two_qubit_ops():\n                control = node.qargs[0]\n                target = node.qargs[1]\n\n                physical_q0 = layout_map[control]\n                physical_q1 = layout_map[target]\n\n                if node.name == \"cx\":\n                    if (physical_q0, physical_q1) in self.target[\"cx\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"cx\"]:\n                        dag.substitute_node_with_dag(node, self._cx_dag)\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for cx\" % (physical_q0, physical_q1)\n                        )\n                elif node.name == \"ecr\":\n                    if (physical_q0, physical_q1) in self.target[\"ecr\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"ecr\"]:\n                        dag.substitute_node_with_dag(node, self._ecr_dag)\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for ecr\" % (physical_q0, physical_q1)\n                        )\n                elif node.name == \"rzx\":\n                    if (physical_q0, physical_q1) in self.target[\"rzx\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"rzx\"]:\n                        dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for rzx\" % (physical_q0, physical_q1)\n                        )\n                else:\n                    raise TranspilerError(\n                        f\"Flipping of gate direction is only supported \"\n                        f\"for CX, ECR, and RZX at this time, not {node.name}.\"\n                    )\n        return dag\n", "path": "qiskit/transpiler/passes/utils/gate_direction.py"}], "after_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Rearrange the direction of the cx nodes to match the directed coupling map.\"\"\"\n\nfrom math import pi\n\nfrom qiskit.transpiler.layout import Layout\nfrom qiskit.transpiler.basepasses import TransformationPass\nfrom qiskit.transpiler.exceptions import TranspilerError\n\nfrom qiskit.circuit import QuantumRegister\nfrom qiskit.dagcircuit import DAGCircuit\nfrom qiskit.circuit.library.standard_gates import RYGate, HGate, CXGate, CZGate, ECRGate, RZXGate\n\n\nclass GateDirection(TransformationPass):\n    \"\"\"Modify asymmetric gates to match the hardware coupling direction.\n\n    This pass makes use of the following identities::\n\n                             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u2500\u2500\u25a0\u2500\u2500      q_0: \u2524 H \u251c\u2524 X \u251c\u2524 H \u251c\n             \u250c\u2500\u2534\u2500\u2510  =        \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u252c\u2500\u2518\u251c\u2500\u2500\u2500\u2524\n        q_1: \u2524 X \u251c      q_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2518           \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2518\n\n             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u25240     \u251c     q_0: \u2524 RY(-pi/2) \u251c\u25241     \u251c\u2524 H \u251c\n             \u2502  ECR \u2502  =       \u2514\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2502  ECR \u2502\u251c\u2500\u2500\u2500\u2524\n        q_1: \u25241     \u251c     q_1: \u2500\u2524 RY(pi/2) \u251c\u25240     \u251c\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n\n             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n        q_0: \u25240     \u251c     q_0: \u2524 H \u251c\u25241     \u251c\u2524 H \u251c\n             \u2502  RZX \u2502  =       \u251c\u2500\u2500\u2500\u2524\u2502  RZX \u2502\u251c\u2500\u2500\u2500\u2524\n        q_1: \u25241     \u251c     q_1: \u2524 H \u251c\u25240     \u251c\u2524 H \u251c\n             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n    \"\"\"\n\n    def __init__(self, coupling_map, target=None):\n        \"\"\"GateDirection pass.\n\n        Args:\n            coupling_map (CouplingMap): Directed graph represented a coupling map.\n            target (Target): The backend target to use for this pass. If this is specified\n                it will be used instead of the coupling map\n        \"\"\"\n        super().__init__()\n        self.coupling_map = coupling_map\n        self.target = target\n\n        # Create the replacement dag and associated register.\n        self._cx_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        self._cx_dag.add_qreg(qr)\n        self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        self._cx_dag.apply_operation_back(CXGate(), [qr[1], qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._cx_dag.apply_operation_back(HGate(), [qr[1]], [])\n\n        self._ecr_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        self._ecr_dag.add_qreg(qr)\n        self._ecr_dag.apply_operation_back(RYGate(-pi / 2), [qr[0]], [])\n        self._ecr_dag.apply_operation_back(RYGate(pi / 2), [qr[1]], [])\n        self._ecr_dag.apply_operation_back(ECRGate(), [qr[1], qr[0]], [])\n        self._ecr_dag.apply_operation_back(HGate(), [qr[0]], [])\n        self._ecr_dag.apply_operation_back(HGate(), [qr[1]], [])\n\n        self._cz_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        self._cz_dag.add_qreg(qr)\n        self._cz_dag.apply_operation_back(CZGate(), [qr[1], qr[0]], [])\n\n    @staticmethod\n    def _rzx_dag(parameter):\n        _rzx_dag = DAGCircuit()\n        qr = QuantumRegister(2)\n        _rzx_dag.add_qreg(qr)\n        _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        _rzx_dag.apply_operation_back(RZXGate(parameter), [qr[1], qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[0]], [])\n        _rzx_dag.apply_operation_back(HGate(), [qr[1]], [])\n        return _rzx_dag\n\n    def run(self, dag):\n        \"\"\"Run the GateDirection pass on `dag`.\n\n        Flips the cx nodes to match the directed coupling map. Modifies the\n        input dag.\n\n        Args:\n            dag (DAGCircuit): DAG to map.\n\n        Returns:\n            DAGCircuit: The rearranged dag for the coupling map\n\n        Raises:\n            TranspilerError: If the circuit cannot be mapped just by flipping the\n                cx nodes.\n        \"\"\"\n        trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())\n        layout_map = trivial_layout.get_virtual_bits()\n        if len(dag.qregs) > 1:\n            raise TranspilerError(\n                \"GateDirection expects a single qreg input DAG,\"\n                \"but input DAG had qregs: {}.\".format(dag.qregs)\n            )\n        if self.target is None:\n            cmap_edges = set(self.coupling_map.get_edges())\n            if not cmap_edges:\n                return dag\n\n            self.coupling_map.compute_distance_matrix()\n\n            dist_matrix = self.coupling_map.distance_matrix\n\n            for node in dag.two_qubit_ops():\n                control = node.qargs[0]\n                target = node.qargs[1]\n\n                physical_q0 = layout_map[control]\n                physical_q1 = layout_map[target]\n\n                if dist_matrix[physical_q0, physical_q1] != 1:\n                    raise TranspilerError(\n                        \"The circuit requires a connection between physical \"\n                        \"qubits %s and %s\" % (physical_q0, physical_q1)\n                    )\n\n                if (physical_q0, physical_q1) not in cmap_edges:\n                    if node.name == \"cx\":\n                        dag.substitute_node_with_dag(node, self._cx_dag)\n                    elif node.name == \"cz\":\n                        dag.substitute_node_with_dag(node, self._cz_dag)\n                    elif node.name == \"ecr\":\n                        dag.substitute_node_with_dag(node, self._ecr_dag)\n                    elif node.name == \"rzx\":\n                        dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))\n                    else:\n                        raise TranspilerError(\n                            f\"Flipping of gate direction is only supported \"\n                            f\"for CX, ECR, and RZX at this time, not {node.name}.\"\n                        )\n        else:\n            # TODO: Work with the gate instances and only use names as look up keys.\n            # This will require iterating over the target names to build a mapping\n            # of names to gates that implement CXGate, ECRGate, RZXGate (including\n            # fixed angle variants)\n            for node in dag.two_qubit_ops():\n                control = node.qargs[0]\n                target = node.qargs[1]\n\n                physical_q0 = layout_map[control]\n                physical_q1 = layout_map[target]\n\n                if node.name == \"cx\":\n                    if (physical_q0, physical_q1) in self.target[\"cx\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"cx\"]:\n                        dag.substitute_node_with_dag(node, self._cx_dag)\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for cx\" % (physical_q0, physical_q1)\n                        )\n                elif node.name == \"cz\":\n                    if (physical_q0, physical_q1) in self.target[\"cz\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"cz\"]:\n                        dag.substitute_node_with_dag(node, self._cz_dag)\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for cz\" % (physical_q0, physical_q1)\n                        )\n                elif node.name == \"ecr\":\n                    if (physical_q0, physical_q1) in self.target[\"ecr\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"ecr\"]:\n                        dag.substitute_node_with_dag(node, self._ecr_dag)\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for ecr\" % (physical_q0, physical_q1)\n                        )\n                elif node.name == \"rzx\":\n                    if (physical_q0, physical_q1) in self.target[\"rzx\"]:\n                        continue\n                    if (physical_q1, physical_q0) in self.target[\"rzx\"]:\n                        dag.substitute_node_with_dag(node, self._rzx_dag(*node.op.params))\n                    else:\n                        raise TranspilerError(\n                            \"The circuit requires a connection between physical \"\n                            \"qubits %s and %s for rzx\" % (physical_q0, physical_q1)\n                        )\n                else:\n                    raise TranspilerError(\n                        f\"Flipping of gate direction is only supported \"\n                        f\"for CX, ECR, and RZX at this time, not {node.name}.\"\n                    )\n        return dag\n", "path": "qiskit/transpiler/passes/utils/gate_direction.py"}]}