We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Cannot map a single qubit to a given device qubit that is not zero
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: master
- **Python version**:
- **Operating system**:

### What is the current behavior?
It is not possible to map a single qubit circuit to a device qubit that is not zero.

```python

qr = QuantumRegister(1, 'qr')
qc = QuantumCircuit(qr)
qc.h(qr[0])

layout = Layout({(qr,0): 19})
backend = IBMQ.get_backend('ibmq_16_melbourne')
new_circ = transpile(qc, backend, initial_layout=layout)
new_circ.draw()
```

<img width="235" alt="Screen Shot 2019-03-28 at 11 18 08 AM" src="https://user-images.githubusercontent.com/1249193/55169462-34199680-514b-11e9-8760-64f5e32ed0af.png">

Note also that the layout used is not valid for the device, but no error is thrown.  I think all of this is due to this:

https://github.com/Qiskit/qiskit-terra/blob/ef46e442e4320500c847da617aadd5476bca4b70/qiskit/transpiler/transpiler.py#L190

that sets the coupling map to `None`, and therefore the transpiler skips the swap mapper that currently implements the mapping to device qubits.  Increasing the quantum register size to two or more gives a circuit with correct mapping, and which is the width of the device.




### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions




--- 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/transpiler.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright 2018, IBM.
4 #
5 # This source code is licensed under the Apache License, Version 2.0 found in
6 # the LICENSE.txt file in the root directory of this source tree.
7 
8 """Tools for compiling a batch of quantum circuits."""
9 import logging
10 import warnings
11 
12 from qiskit.circuit import QuantumCircuit
13 from qiskit.mapper import CouplingMap
14 from qiskit.tools.parallel import parallel_map
15 from qiskit.converters import circuit_to_dag
16 from qiskit.converters import dag_to_circuit
17 from qiskit.extensions.standard import SwapGate
18 from qiskit.mapper.layout import Layout
19 from qiskit.transpiler.passmanager import PassManager
20 from qiskit.transpiler.exceptions import TranspilerError
21 
22 from .passes.unroller import Unroller
23 from .passes.cx_cancellation import CXCancellation
24 from .passes.decompose import Decompose
25 from .passes.optimize_1q_gates import Optimize1qGates
26 from .passes.fixed_point import FixedPoint
27 from .passes.depth import Depth
28 from .passes.mapping.check_map import CheckMap
29 from .passes.mapping.cx_direction import CXDirection
30 from .passes.mapping.dense_layout import DenseLayout
31 from .passes.mapping.trivial_layout import TrivialLayout
32 from .passes.mapping.legacy_swap import LegacySwap
33 from .passes.mapping.enlarge_with_ancilla import EnlargeWithAncilla
34 from .passes.mapping.extend_layout import ExtendLayout
35 
36 logger = logging.getLogger(__name__)
37 
38 
39 def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
40               initial_layout=None, seed_mapper=None, pass_manager=None):
41     """transpile one or more circuits.
42 
43     Args:
44         circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
45         backend (BaseBackend): a backend to compile for
46         basis_gates (list[str]): list of basis gate names supported by the
47             target. Default: ['u1','u2','u3','cx','id']
48         coupling_map (list): coupling map (perhaps custom) to target in mapping
49         initial_layout (list): initial layout of qubits in mapping
50         seed_mapper (int): random seed for the swap_mapper
51         pass_manager (PassManager): a pass_manager for the transpiler stages
52 
53     Returns:
54         QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
55     """
56     return_form_is_single = False
57     if isinstance(circuits, QuantumCircuit):
58         circuits = [circuits]
59         return_form_is_single = True
60 
61     # pass manager overrides explicit transpile options (basis_gates, coupling_map)
62     # explicit transpile options override options gotten from a backend
63     if not pass_manager and backend:
64         basis_gates = basis_gates or getattr(backend.configuration(), 'basis_gates', None)
65         # This needs to be removed once Aer 0.2 is out
66         coupling_map = coupling_map or getattr(backend.configuration(), 'coupling_map', None)
67 
68     # Convert integer list format to Layout
69     if isinstance(initial_layout, list) and \
70             all(isinstance(elem, int) for elem in initial_layout):
71         if isinstance(circuits, list):
72             circ = circuits[0]
73         else:
74             circ = circuits
75         initial_layout = Layout.generate_from_intlist(initial_layout, *circ.qregs)
76 
77     if initial_layout is not None and not isinstance(initial_layout, Layout):
78         initial_layout = Layout(initial_layout)
79 
80     circuits = parallel_map(_transpilation, circuits,
81                             task_kwargs={'basis_gates': basis_gates,
82                                          'coupling_map': coupling_map,
83                                          'initial_layout': initial_layout,
84                                          'seed_mapper': seed_mapper,
85                                          'pass_manager': pass_manager})
86     if return_form_is_single:
87         return circuits[0]
88     return circuits
89 
90 
91 def _transpilation(circuit, basis_gates=None, coupling_map=None,
92                    initial_layout=None, seed_mapper=None,
93                    pass_manager=None):
94     """Perform transpilation of a single circuit.
95 
96     Args:
97         circuit (QuantumCircuit): A circuit to transpile.
98         basis_gates (list[str]): list of basis gate names supported by the
99             target. Default: ['u1','u2','u3','cx','id']
100         coupling_map (CouplingMap): coupling map (perhaps custom) to target in mapping
101         initial_layout (Layout): initial layout of qubits in mapping
102         seed_mapper (int): random seed for the swap_mapper
103         pass_manager (PassManager): a pass_manager for the transpiler stage
104 
105     Returns:
106         QuantumCircuit: A transpiled circuit.
107 
108     Raises:
109         TranspilerError: If the Layout does not matches the circuit
110     """
111     if initial_layout is not None and set(circuit.qregs) != initial_layout.get_registers():
112         raise TranspilerError('The provided initial layout does not match the registers in '
113                               'the circuit "%s"' % circuit.name)
114 
115     if pass_manager and not pass_manager.working_list:
116         return circuit
117 
118     dag = circuit_to_dag(circuit)
119     del circuit
120 
121     # if the circuit and layout already satisfy the coupling_constraints, use that layout
122     # if there's no layout but the circuit is compatible, use a trivial layout
123     # otherwise layout on the most densely connected physical qubit subset
124     # FIXME: this should be simplified once it is ported to a PassManager
125     if coupling_map:
126         cm_object = CouplingMap(coupling_map)
127         check_map = CheckMap(cm_object, initial_layout)
128         check_map.run(dag)
129         if check_map.property_set['is_swap_mapped']:
130             if not initial_layout:
131                 trivial_layout = TrivialLayout(cm_object)
132                 trivial_layout.run(dag)
133                 initial_layout = trivial_layout.property_set['layout']
134         else:
135             dense_layout = DenseLayout(cm_object)
136             dense_layout.run(dag)
137             initial_layout = dense_layout.property_set['layout']
138 
139     final_dag = transpile_dag(dag, basis_gates=basis_gates,
140                               coupling_map=coupling_map,
141                               initial_layout=initial_layout,
142                               seed_mapper=seed_mapper,
143                               pass_manager=pass_manager)
144 
145     out_circuit = dag_to_circuit(final_dag)
146 
147     return out_circuit
148 
149 
150 # pylint: disable=redefined-builtin
151 def transpile_dag(dag, basis_gates=None, coupling_map=None,
152                   initial_layout=None, seed_mapper=None, pass_manager=None):
153     """Transform a dag circuit into another dag circuit (transpile), through
154     consecutive passes on the dag.
155 
156     Args:
157         dag (DAGCircuit): dag circuit to transform via transpilation
158         basis_gates (list[str]): list of basis gate names supported by the
159             target. Default: ['u1','u2','u3','cx','id']
160         coupling_map (list): A graph of coupling::
161 
162             [
163              [control0(int), target0(int)],
164              [control1(int), target1(int)],
165             ]
166 
167             eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
168 
169         initial_layout (Layout or None): A layout object
170         seed_mapper (int): random seed_mapper for the swap mapper
171         pass_manager (PassManager): pass manager instance for the transpilation process
172             If None, a default set of passes are run.
173             Otherwise, the passes defined in it will run.
174             If contains no passes in it, no dag transformations occur.
175 
176     Returns:
177         DAGCircuit: transformed dag
178     """
179     # TODO: `basis_gates` will be removed after we have the unroller pass.
180     # TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
181 
182     # TODO: move this to the mapper pass
183 
184     num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
185     if num_qubits == 1:
186         coupling_map = None
187 
188     if basis_gates is None:
189         basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
190     if isinstance(basis_gates, str):
191         warnings.warn("The parameter basis_gates is now a list of strings. "
192                       "For example, this basis ['u1','u2','u3','cx'] should be used "
193                       "instead of 'u1,u2,u3,cx'. The string format will be "
194                       "removed after 0.9", DeprecationWarning, 2)
195         basis_gates = basis_gates.split(',')
196 
197     if initial_layout is None:
198         initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
199 
200     if pass_manager is None:
201         # default set of passes
202 
203         pass_manager = PassManager()
204         pass_manager.append(Unroller(basis_gates))
205 
206         # if a coupling map is given compile to the map
207         if coupling_map:
208             coupling = CouplingMap(coupling_map)
209 
210             # Extend and enlarge the the dag/layout with ancillas using the full coupling map
211             pass_manager.property_set['layout'] = initial_layout
212             pass_manager.append(ExtendLayout(coupling))
213             pass_manager.append(EnlargeWithAncilla(initial_layout))
214 
215             # Swap mapper
216             pass_manager.append(LegacySwap(coupling, initial_layout, trials=20, seed=seed_mapper))
217 
218             # Expand swaps
219             pass_manager.append(Decompose(SwapGate))
220 
221             # Change CX directions
222             pass_manager.append(CXDirection(coupling))
223 
224             # Unroll to the basis
225             pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))
226 
227             # Simplify single qubit gates and CXs
228             pass_manager.append([Optimize1qGates(), CXCancellation(), Depth(), FixedPoint('depth')],
229                                 do_while=lambda property_set: not property_set['depth_fixed_point'])
230 
231     # run the passes specified by the pass manager
232     # TODO return the property set too. See #1086
233     name = dag.name
234     dag = pass_manager.run_passes(dag)
235     dag.name = name
236 
237     return dag
238
```
--- 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/transpiler.py b/qiskit/transpiler/transpiler.py
--- a/qiskit/transpiler/transpiler.py
+++ b/qiskit/transpiler/transpiler.py
@@ -179,12 +179,6 @@
     # TODO: `basis_gates` will be removed after we have the unroller pass.
     # TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
 
-    # TODO: move this to the mapper pass
-
-    num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
-    if num_qubits == 1:
-        coupling_map = None
-
     if basis_gates is None:
         basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
     if isinstance(basis_gates, str):

{"golden_diff": "diff --git a/qiskit/transpiler/transpiler.py b/qiskit/transpiler/transpiler.py\n--- a/qiskit/transpiler/transpiler.py\n+++ b/qiskit/transpiler/transpiler.py\n@@ -179,12 +179,6 @@\n     # TODO: `basis_gates` will be removed after we have the unroller pass.\n     # TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.\n \n-    # TODO: move this to the mapper pass\n-\n-    num_qubits = sum([qreg.size for qreg in dag.qregs.values()])\n-    if num_qubits == 1:\n-        coupling_map = None\n-\n     if basis_gates is None:\n         basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']\n     if isinstance(basis_gates, str):\n", "issue": "Cannot map a single qubit to a given device qubit that is not zero\n<!-- \u26a0\ufe0f If you do not respect this template, your issue will be closed -->\r\n<!-- \u26a0\ufe0f Make sure to browse the opened and closed issues -->\r\n\r\n### Information\r\n\r\n- **Qiskit Terra version**: master\r\n- **Python version**:\r\n- **Operating system**:\r\n\r\n### What is the current behavior?\r\nIt is not possible to map a single qubit circuit to a device qubit that is not zero.\r\n\r\n```python\r\n\r\nqr = QuantumRegister(1, 'qr')\r\nqc = QuantumCircuit(qr)\r\nqc.h(qr[0])\r\n\r\nlayout = Layout({(qr,0): 19})\r\nbackend = IBMQ.get_backend('ibmq_16_melbourne')\r\nnew_circ = transpile(qc, backend, initial_layout=layout)\r\nnew_circ.draw()\r\n```\r\n\r\n<img width=\"235\" alt=\"Screen Shot 2019-03-28 at 11 18 08 AM\" src=\"https://user-images.githubusercontent.com/1249193/55169462-34199680-514b-11e9-8760-64f5e32ed0af.png\">\r\n\r\nNote also that the layout used is not valid for the device, but no error is thrown.  I think all of this is due to this:\r\n\r\nhttps://github.com/Qiskit/qiskit-terra/blob/ef46e442e4320500c847da617aadd5476bca4b70/qiskit/transpiler/transpiler.py#L190\r\n\r\nthat sets the coupling map to `None`, and therefore the transpiler skips the swap mapper that currently implements the mapping to device qubits.  Increasing the quantum register size to two or more gives a circuit with correct mapping, and which is the width of the device.\r\n\r\n\r\n\r\n\r\n### Steps to reproduce the problem\r\n\r\n\r\n\r\n### What is the expected behavior?\r\n\r\n\r\n\r\n### Suggested solutions\r\n\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"Tools for compiling a batch of quantum circuits.\"\"\"\nimport logging\nimport warnings\n\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.mapper import CouplingMap\nfrom qiskit.tools.parallel import parallel_map\nfrom qiskit.converters import circuit_to_dag\nfrom qiskit.converters import dag_to_circuit\nfrom qiskit.extensions.standard import SwapGate\nfrom qiskit.mapper.layout import Layout\nfrom qiskit.transpiler.passmanager import PassManager\nfrom qiskit.transpiler.exceptions import TranspilerError\n\nfrom .passes.unroller import Unroller\nfrom .passes.cx_cancellation import CXCancellation\nfrom .passes.decompose import Decompose\nfrom .passes.optimize_1q_gates import Optimize1qGates\nfrom .passes.fixed_point import FixedPoint\nfrom .passes.depth import Depth\nfrom .passes.mapping.check_map import CheckMap\nfrom .passes.mapping.cx_direction import CXDirection\nfrom .passes.mapping.dense_layout import DenseLayout\nfrom .passes.mapping.trivial_layout import TrivialLayout\nfrom .passes.mapping.legacy_swap import LegacySwap\nfrom .passes.mapping.enlarge_with_ancilla import EnlargeWithAncilla\nfrom .passes.mapping.extend_layout import ExtendLayout\n\nlogger = logging.getLogger(__name__)\n\n\ndef transpile(circuits, backend=None, basis_gates=None, coupling_map=None,\n              initial_layout=None, seed_mapper=None, pass_manager=None):\n    \"\"\"transpile one or more circuits.\n\n    Args:\n        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile\n        backend (BaseBackend): a backend to compile for\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (list): coupling map (perhaps custom) to target in mapping\n        initial_layout (list): initial layout of qubits in mapping\n        seed_mapper (int): random seed for the swap_mapper\n        pass_manager (PassManager): a pass_manager for the transpiler stages\n\n    Returns:\n        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).\n    \"\"\"\n    return_form_is_single = False\n    if isinstance(circuits, QuantumCircuit):\n        circuits = [circuits]\n        return_form_is_single = True\n\n    # pass manager overrides explicit transpile options (basis_gates, coupling_map)\n    # explicit transpile options override options gotten from a backend\n    if not pass_manager and backend:\n        basis_gates = basis_gates or getattr(backend.configuration(), 'basis_gates', None)\n        # This needs to be removed once Aer 0.2 is out\n        coupling_map = coupling_map or getattr(backend.configuration(), 'coupling_map', None)\n\n    # Convert integer list format to Layout\n    if isinstance(initial_layout, list) and \\\n            all(isinstance(elem, int) for elem in initial_layout):\n        if isinstance(circuits, list):\n            circ = circuits[0]\n        else:\n            circ = circuits\n        initial_layout = Layout.generate_from_intlist(initial_layout, *circ.qregs)\n\n    if initial_layout is not None and not isinstance(initial_layout, Layout):\n        initial_layout = Layout(initial_layout)\n\n    circuits = parallel_map(_transpilation, circuits,\n                            task_kwargs={'basis_gates': basis_gates,\n                                         'coupling_map': coupling_map,\n                                         'initial_layout': initial_layout,\n                                         'seed_mapper': seed_mapper,\n                                         'pass_manager': pass_manager})\n    if return_form_is_single:\n        return circuits[0]\n    return circuits\n\n\ndef _transpilation(circuit, basis_gates=None, coupling_map=None,\n                   initial_layout=None, seed_mapper=None,\n                   pass_manager=None):\n    \"\"\"Perform transpilation of a single circuit.\n\n    Args:\n        circuit (QuantumCircuit): A circuit to transpile.\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (CouplingMap): coupling map (perhaps custom) to target in mapping\n        initial_layout (Layout): initial layout of qubits in mapping\n        seed_mapper (int): random seed for the swap_mapper\n        pass_manager (PassManager): a pass_manager for the transpiler stage\n\n    Returns:\n        QuantumCircuit: A transpiled circuit.\n\n    Raises:\n        TranspilerError: If the Layout does not matches the circuit\n    \"\"\"\n    if initial_layout is not None and set(circuit.qregs) != initial_layout.get_registers():\n        raise TranspilerError('The provided initial layout does not match the registers in '\n                              'the circuit \"%s\"' % circuit.name)\n\n    if pass_manager and not pass_manager.working_list:\n        return circuit\n\n    dag = circuit_to_dag(circuit)\n    del circuit\n\n    # if the circuit and layout already satisfy the coupling_constraints, use that layout\n    # if there's no layout but the circuit is compatible, use a trivial layout\n    # otherwise layout on the most densely connected physical qubit subset\n    # FIXME: this should be simplified once it is ported to a PassManager\n    if coupling_map:\n        cm_object = CouplingMap(coupling_map)\n        check_map = CheckMap(cm_object, initial_layout)\n        check_map.run(dag)\n        if check_map.property_set['is_swap_mapped']:\n            if not initial_layout:\n                trivial_layout = TrivialLayout(cm_object)\n                trivial_layout.run(dag)\n                initial_layout = trivial_layout.property_set['layout']\n        else:\n            dense_layout = DenseLayout(cm_object)\n            dense_layout.run(dag)\n            initial_layout = dense_layout.property_set['layout']\n\n    final_dag = transpile_dag(dag, basis_gates=basis_gates,\n                              coupling_map=coupling_map,\n                              initial_layout=initial_layout,\n                              seed_mapper=seed_mapper,\n                              pass_manager=pass_manager)\n\n    out_circuit = dag_to_circuit(final_dag)\n\n    return out_circuit\n\n\n# pylint: disable=redefined-builtin\ndef transpile_dag(dag, basis_gates=None, coupling_map=None,\n                  initial_layout=None, seed_mapper=None, pass_manager=None):\n    \"\"\"Transform a dag circuit into another dag circuit (transpile), through\n    consecutive passes on the dag.\n\n    Args:\n        dag (DAGCircuit): dag circuit to transform via transpilation\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (list): A graph of coupling::\n\n            [\n             [control0(int), target0(int)],\n             [control1(int), target1(int)],\n            ]\n\n            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}\n\n        initial_layout (Layout or None): A layout object\n        seed_mapper (int): random seed_mapper for the swap mapper\n        pass_manager (PassManager): pass manager instance for the transpilation process\n            If None, a default set of passes are run.\n            Otherwise, the passes defined in it will run.\n            If contains no passes in it, no dag transformations occur.\n\n    Returns:\n        DAGCircuit: transformed dag\n    \"\"\"\n    # TODO: `basis_gates` will be removed after we have the unroller pass.\n    # TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.\n\n    # TODO: move this to the mapper pass\n\n    num_qubits = sum([qreg.size for qreg in dag.qregs.values()])\n    if num_qubits == 1:\n        coupling_map = None\n\n    if basis_gates is None:\n        basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']\n    if isinstance(basis_gates, str):\n        warnings.warn(\"The parameter basis_gates is now a list of strings. \"\n                      \"For example, this basis ['u1','u2','u3','cx'] should be used \"\n                      \"instead of 'u1,u2,u3,cx'. The string format will be \"\n                      \"removed after 0.9\", DeprecationWarning, 2)\n        basis_gates = basis_gates.split(',')\n\n    if initial_layout is None:\n        initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())\n\n    if pass_manager is None:\n        # default set of passes\n\n        pass_manager = PassManager()\n        pass_manager.append(Unroller(basis_gates))\n\n        # if a coupling map is given compile to the map\n        if coupling_map:\n            coupling = CouplingMap(coupling_map)\n\n            # Extend and enlarge the the dag/layout with ancillas using the full coupling map\n            pass_manager.property_set['layout'] = initial_layout\n            pass_manager.append(ExtendLayout(coupling))\n            pass_manager.append(EnlargeWithAncilla(initial_layout))\n\n            # Swap mapper\n            pass_manager.append(LegacySwap(coupling, initial_layout, trials=20, seed=seed_mapper))\n\n            # Expand swaps\n            pass_manager.append(Decompose(SwapGate))\n\n            # Change CX directions\n            pass_manager.append(CXDirection(coupling))\n\n            # Unroll to the basis\n            pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))\n\n            # Simplify single qubit gates and CXs\n            pass_manager.append([Optimize1qGates(), CXCancellation(), Depth(), FixedPoint('depth')],\n                                do_while=lambda property_set: not property_set['depth_fixed_point'])\n\n    # run the passes specified by the pass manager\n    # TODO return the property set too. See #1086\n    name = dag.name\n    dag = pass_manager.run_passes(dag)\n    dag.name = name\n\n    return dag\n", "path": "qiskit/transpiler/transpiler.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"Tools for compiling a batch of quantum circuits.\"\"\"\nimport logging\nimport warnings\n\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.mapper import CouplingMap\nfrom qiskit.tools.parallel import parallel_map\nfrom qiskit.converters import circuit_to_dag\nfrom qiskit.converters import dag_to_circuit\nfrom qiskit.extensions.standard import SwapGate\nfrom qiskit.mapper.layout import Layout\nfrom qiskit.transpiler.passmanager import PassManager\nfrom qiskit.transpiler.exceptions import TranspilerError\n\nfrom .passes.unroller import Unroller\nfrom .passes.cx_cancellation import CXCancellation\nfrom .passes.decompose import Decompose\nfrom .passes.optimize_1q_gates import Optimize1qGates\nfrom .passes.fixed_point import FixedPoint\nfrom .passes.depth import Depth\nfrom .passes.mapping.check_map import CheckMap\nfrom .passes.mapping.cx_direction import CXDirection\nfrom .passes.mapping.dense_layout import DenseLayout\nfrom .passes.mapping.trivial_layout import TrivialLayout\nfrom .passes.mapping.legacy_swap import LegacySwap\nfrom .passes.mapping.enlarge_with_ancilla import EnlargeWithAncilla\nfrom .passes.mapping.extend_layout import ExtendLayout\n\nlogger = logging.getLogger(__name__)\n\n\ndef transpile(circuits, backend=None, basis_gates=None, coupling_map=None,\n              initial_layout=None, seed_mapper=None, pass_manager=None):\n    \"\"\"transpile one or more circuits.\n\n    Args:\n        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile\n        backend (BaseBackend): a backend to compile for\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (list): coupling map (perhaps custom) to target in mapping\n        initial_layout (list): initial layout of qubits in mapping\n        seed_mapper (int): random seed for the swap_mapper\n        pass_manager (PassManager): a pass_manager for the transpiler stages\n\n    Returns:\n        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).\n    \"\"\"\n    return_form_is_single = False\n    if isinstance(circuits, QuantumCircuit):\n        circuits = [circuits]\n        return_form_is_single = True\n\n    # pass manager overrides explicit transpile options (basis_gates, coupling_map)\n    # explicit transpile options override options gotten from a backend\n    if not pass_manager and backend:\n        basis_gates = basis_gates or getattr(backend.configuration(), 'basis_gates', None)\n        # This needs to be removed once Aer 0.2 is out\n        coupling_map = coupling_map or getattr(backend.configuration(), 'coupling_map', None)\n\n    # Convert integer list format to Layout\n    if isinstance(initial_layout, list) and \\\n            all(isinstance(elem, int) for elem in initial_layout):\n        if isinstance(circuits, list):\n            circ = circuits[0]\n        else:\n            circ = circuits\n        initial_layout = Layout.generate_from_intlist(initial_layout, *circ.qregs)\n\n    if initial_layout is not None and not isinstance(initial_layout, Layout):\n        initial_layout = Layout(initial_layout)\n\n    circuits = parallel_map(_transpilation, circuits,\n                            task_kwargs={'basis_gates': basis_gates,\n                                         'coupling_map': coupling_map,\n                                         'initial_layout': initial_layout,\n                                         'seed_mapper': seed_mapper,\n                                         'pass_manager': pass_manager})\n    if return_form_is_single:\n        return circuits[0]\n    return circuits\n\n\ndef _transpilation(circuit, basis_gates=None, coupling_map=None,\n                   initial_layout=None, seed_mapper=None,\n                   pass_manager=None):\n    \"\"\"Perform transpilation of a single circuit.\n\n    Args:\n        circuit (QuantumCircuit): A circuit to transpile.\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (CouplingMap): coupling map (perhaps custom) to target in mapping\n        initial_layout (Layout): initial layout of qubits in mapping\n        seed_mapper (int): random seed for the swap_mapper\n        pass_manager (PassManager): a pass_manager for the transpiler stage\n\n    Returns:\n        QuantumCircuit: A transpiled circuit.\n\n    Raises:\n        TranspilerError: If the Layout does not matches the circuit\n    \"\"\"\n    if initial_layout is not None and set(circuit.qregs) != initial_layout.get_registers():\n        raise TranspilerError('The provided initial layout does not match the registers in '\n                              'the circuit \"%s\"' % circuit.name)\n\n    if pass_manager and not pass_manager.working_list:\n        return circuit\n\n    dag = circuit_to_dag(circuit)\n    del circuit\n\n    # if the circuit and layout already satisfy the coupling_constraints, use that layout\n    # if there's no layout but the circuit is compatible, use a trivial layout\n    # otherwise layout on the most densely connected physical qubit subset\n    # FIXME: this should be simplified once it is ported to a PassManager\n    if coupling_map:\n        cm_object = CouplingMap(coupling_map)\n        check_map = CheckMap(cm_object, initial_layout)\n        check_map.run(dag)\n        if check_map.property_set['is_swap_mapped']:\n            if not initial_layout:\n                trivial_layout = TrivialLayout(cm_object)\n                trivial_layout.run(dag)\n                initial_layout = trivial_layout.property_set['layout']\n        else:\n            dense_layout = DenseLayout(cm_object)\n            dense_layout.run(dag)\n            initial_layout = dense_layout.property_set['layout']\n\n    final_dag = transpile_dag(dag, basis_gates=basis_gates,\n                              coupling_map=coupling_map,\n                              initial_layout=initial_layout,\n                              seed_mapper=seed_mapper,\n                              pass_manager=pass_manager)\n\n    out_circuit = dag_to_circuit(final_dag)\n\n    return out_circuit\n\n\n# pylint: disable=redefined-builtin\ndef transpile_dag(dag, basis_gates=None, coupling_map=None,\n                  initial_layout=None, seed_mapper=None, pass_manager=None):\n    \"\"\"Transform a dag circuit into another dag circuit (transpile), through\n    consecutive passes on the dag.\n\n    Args:\n        dag (DAGCircuit): dag circuit to transform via transpilation\n        basis_gates (list[str]): list of basis gate names supported by the\n            target. Default: ['u1','u2','u3','cx','id']\n        coupling_map (list): A graph of coupling::\n\n            [\n             [control0(int), target0(int)],\n             [control1(int), target1(int)],\n            ]\n\n            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}\n\n        initial_layout (Layout or None): A layout object\n        seed_mapper (int): random seed_mapper for the swap mapper\n        pass_manager (PassManager): pass manager instance for the transpilation process\n            If None, a default set of passes are run.\n            Otherwise, the passes defined in it will run.\n            If contains no passes in it, no dag transformations occur.\n\n    Returns:\n        DAGCircuit: transformed dag\n    \"\"\"\n    # TODO: `basis_gates` will be removed after we have the unroller pass.\n    # TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.\n\n    if basis_gates is None:\n        basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']\n    if isinstance(basis_gates, str):\n        warnings.warn(\"The parameter basis_gates is now a list of strings. \"\n                      \"For example, this basis ['u1','u2','u3','cx'] should be used \"\n                      \"instead of 'u1,u2,u3,cx'. The string format will be \"\n                      \"removed after 0.9\", DeprecationWarning, 2)\n        basis_gates = basis_gates.split(',')\n\n    if initial_layout is None:\n        initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())\n\n    if pass_manager is None:\n        # default set of passes\n\n        pass_manager = PassManager()\n        pass_manager.append(Unroller(basis_gates))\n\n        # if a coupling map is given compile to the map\n        if coupling_map:\n            coupling = CouplingMap(coupling_map)\n\n            # Extend and enlarge the the dag/layout with ancillas using the full coupling map\n            pass_manager.property_set['layout'] = initial_layout\n            pass_manager.append(ExtendLayout(coupling))\n            pass_manager.append(EnlargeWithAncilla(initial_layout))\n\n            # Swap mapper\n            pass_manager.append(LegacySwap(coupling, initial_layout, trials=20, seed=seed_mapper))\n\n            # Expand swaps\n            pass_manager.append(Decompose(SwapGate))\n\n            # Change CX directions\n            pass_manager.append(CXDirection(coupling))\n\n            # Unroll to the basis\n            pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))\n\n            # Simplify single qubit gates and CXs\n            pass_manager.append([Optimize1qGates(), CXCancellation(), Depth(), FixedPoint('depth')],\n                                do_while=lambda property_set: not property_set['depth_fixed_point'])\n\n    # run the passes specified by the pass manager\n    # TODO return the property set too. See #1086\n    name = dag.name\n    dag = pass_manager.run_passes(dag)\n    dag.name = name\n\n    return dag\n", "path": "qiskit/transpiler/transpiler.py"}]}