Repository: Qiskit/qiskit

Issue:
Drawing circuit after transpilation with initial_layout set fails
<!-- ⚠️ 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**:3.7
- **Operating system**:osx

### What is the current behavior?



### Steps to reproduce the problem
```python
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
import itertools

#Import Qiskit classes classes
import qiskit
from qiskit import pulse
from qiskit import IBMQ
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
from qiskit.result import marginal_counts
import qiskit.tools.jupyter
#Import the qv function.
import qiskit.ignis.verification.quantum_volume as qv

IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-internal', group='dev-sys-software', project='internal-test')
backend = provider.get_backend('ibmq_boeblingen')

#Qubit list
qubit_lists = [[11, 15, 16]]
n_qubits = 20
n_trials = 20
shots=4096

qr = qiskit.QuantumRegister(n_qubits)
cr = qiskit.ClassicalRegister(n_qubits)

qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, n_trials, qr=qr, cr=cr)

qv_circs_joined = list(itertools.chain.from_iterable(qv_circs))

qc_joined = qiskit.transpile(qv_circs_joined, backend=backend, optimization_level=0, initial_layout=list(range(20)))

qc_joined[0].draw()
```
output:
```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    700                 type_pprinters=self.type_printers,
    701                 deferred_pprinters=self.deferred_printers)
--> 702             printer.pretty(obj)
    703             printer.flush()
    704             return stream.getvalue()

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/IPython/lib/pretty.py in pretty(self, obj)
    392                         if cls is not object \
    393                                 and callable(cls.__dict__.get('__repr__')):
--> 394                             return _repr_pprint(obj, self, cycle)
    395 
    396             return _default_pprint(obj, self, cycle)

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle)
    698     """A pprint that just redirects to the normal repr function."""
    699     # Find newlines and replace them with p.break_()
--> 700     output = repr(obj)
    701     lines = output.splitlines()
    702     with p.group():

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in __repr__(self)
    546 
    547     def __repr__(self):
--> 548         return self.single_string()
    549 
    550     def single_string(self):

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in single_string(self)
    554             str: The lines joined by a newline (``\\n``)
    555         """
--> 556         return "\n".join(self.lines())
    557 
    558     def dump(self, filename, encoding="utf8"):

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in lines(self, line_length)
    590 
    591         try:
--> 592             layers = self.build_layers()
    593         except TextDrawerCregBundle:
    594             self.cregbundle = False

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in build_layers(self)
   1061             VisualizationError: When the drawing is, for some reason, impossible to be drawn.
   1062         """
-> 1063         wire_names = self.wire_names(with_initial_state=self.initial_state)
   1064         if not wire_names:
   1065             return []

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in wire_names(self, with_initial_state)
    664             for bit in self.qregs:
    665                 label = '{name}_{index} -> {physical} ' + initial_qubit_value
--> 666                 qubit_labels.append(label.format(name=self.layout[bit.index].register.name,
    667                                                  index=self.layout[bit.index].index,
    668                                                  physical=bit.index))

AttributeError: 'NoneType' object has no attribute 'register'

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in _repr_html_(self)
    543                'line-height: 1.1;' \
    544                'font-family: &quot;Courier New&quot;,Courier,monospace">' \
--> 545                '%s</pre>' % self.single_string()
    546 
    547     def __repr__(self):

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in single_string(self)
    554             str: The lines joined by a newline (``\\n``)
    555         """
--> 556         return "\n".join(self.lines())
    557 
    558     def dump(self, filename, encoding="utf8"):

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in lines(self, line_length)
    590 
    591         try:
--> 592             layers = self.build_layers()
    593         except TextDrawerCregBundle:
    594             self.cregbundle = False

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in build_layers(self)
   1061             VisualizationError: When the drawing is, for some reason, impossible to be drawn.
   1062         """
-> 1063         wire_names = self.wire_names(with_initial_state=self.initial_state)
   1064         if not wire_names:
   1065             return []

~/anaconda3/envs/new-qiskit/lib/python3.7/site-packages/qiskit/visualization/text.py in wire_names(self, with_initial_state)
    664             for bit in self.qregs:
    665                 label = '{name}_{index} -> {physical} ' + initial_qubit_value
--> 666                 qubit_labels.append(label.format(name=self.layout[bit.index].register.name,
    667                                                  index=self.layout[bit.index].index,
    668                                                  physical=bit.index))

AttributeError: 'NoneType' object has no attribute 'register'
```


### What is the expected behavior?
This should draw the circuit as usual.


### Suggested solutions





Discussion:
#4757 Could it test by changing the provider for backend...I think may be that...

Resolving patch:
diff --git a/qiskit/visualization/latex.py b/qiskit/visualization/latex.py
--- a/qiskit/visualization/latex.py
+++ b/qiskit/visualization/latex.py
@@ -240,10 +240,13 @@ def _initialize_latex_array(self):
                     label = "\\lstick{{ {{{}}}_{{{}}} : ".format(
                         self.ordered_regs[i].register.name, self.ordered_regs[i].index)
                 else:
-                    label = "\\lstick{{ {{{}}}_{{{}}}\\mapsto{{{}}} : ".format(
-                        self.layout[self.ordered_regs[i].index].register.name,
-                        self.layout[self.ordered_regs[i].index].index,
-                        self.ordered_regs[i].index)
+                    if self.layout[self.ordered_regs[i].index]:
+                        label = "\\lstick{{ {{{}}}_{{{}}}\\mapsto{{{}}} : ".format(
+                            self.layout[self.ordered_regs[i].index].register.name,
+                            self.layout[self.ordered_regs[i].index].index,
+                            self.ordered_regs[i].index)
+                    else:
+                        label = "\\lstick{{ {{{}}} : ".format(self.ordered_regs[i].index)
                 if self.initial_state:
                     label += "\\ket{{0}}"
                 label += " }"
diff --git a/qiskit/visualization/matplotlib.py b/qiskit/visualization/matplotlib.py
--- a/qiskit/visualization/matplotlib.py
+++ b/qiskit/visualization/matplotlib.py
@@ -623,9 +623,12 @@ def _fix_double_script(label):
                     label = _fix_double_script(label) + initial_qbit
                     text_width = self._get_text_width(label, self._style.fs)
                 else:
-                    label = '${{{name}}}_{{{index}}} \\mapsto {{{physical}}}$'.format(
-                        name=self.layout[reg.index].register.name,
-                        index=self.layout[reg.index].index, physical=reg.index)
+                    if self.layout[reg.index]:
+                        label = '${{{name}}}_{{{index}}} \\mapsto {{{physical}}}$'.format(
+                            name=self.layout[reg.index].register.name,
+                            index=self.layout[reg.index].index, physical=reg.index)
+                    else:
+                        label = '${{{physical}}}$'.format(physical=reg.index)
                     label = _fix_double_script(label) + initial_qbit
                     text_width = self._get_text_width(label, self._style.fs)
             else:
diff --git a/qiskit/visualization/text.py b/qiskit/visualization/text.py
--- a/qiskit/visualization/text.py
+++ b/qiskit/visualization/text.py
@@ -668,10 +668,14 @@ def wire_names(self, with_initial_state=False):
                                                  physical=''))
         else:
             for bit in self.qregs:
-                label = '{name}_{index} -> {physical} ' + initial_qubit_value
-                qubit_labels.append(label.format(name=self.layout[bit.index].register.name,
-                                                 index=self.layout[bit.index].index,
-                                                 physical=bit.index))
+                if self.layout[bit.index]:
+                    label = '{name}_{index} -> {physical} ' + initial_qubit_value
+                    qubit_labels.append(label.format(name=self.layout[bit.index].register.name,
+                                                     index=self.layout[bit.index].index,
+                                                     physical=bit.index))
+                else:
+                    qubit_labels.append('%s ' % bit.index + initial_qubit_value)
+
         clbit_labels = []
         previous_creg = None
         for bit in self.cregs:


Test patch:
diff --git a/test/ipynb/mpl/references/partial_layout.png b/test/ipynb/mpl/references/partial_layout.png
new file mode 100644
Binary files /dev/null and b/test/ipynb/mpl/references/partial_layout.png differ
diff --git a/test/ipynb/mpl/test_circuit_matplotlib_drawer.py b/test/ipynb/mpl/test_circuit_matplotlib_drawer.py
--- a/test/ipynb/mpl/test_circuit_matplotlib_drawer.py
+++ b/test/ipynb/mpl/test_circuit_matplotlib_drawer.py
@@ -19,7 +19,8 @@
 from contextlib import contextmanager
 from qiskit.test import QiskitTestCase
 
-from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
+from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
+from qiskit.test.mock import FakeTenerife
 from qiskit.visualization.circuit_visualization import _matplotlib_circuit_drawer
 from qiskit.circuit.library import (U3Gate, U2Gate, U1Gate, XGate, SwapGate,
                                     MCXGate, YGate, HGate, ZGate,
@@ -327,12 +328,22 @@ def test_scale(self):
         See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
         circuit = QuantumCircuit(5)
         circuit.unitary(random_unitary(2 ** 5), circuit.qubits)
-        circuit.draw('mpl')
 
         self.circuit_drawer(circuit, filename='scale_default.png')
         self.circuit_drawer(circuit, filename='scale_half.png', scale=0.5)
         self.circuit_drawer(circuit, filename='scale_double.png', scale=2)
 
+    def test_partial_layout(self):
+        """Tests partial_layout
+        See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
+        circuit = QuantumCircuit(3)
+        circuit.h(1)
+        transpiled = transpile(circuit, backend=FakeTenerife(),
+                               optimization_level=0, initial_layout=list(range(5)),
+                               seed_transpiler=0)
+
+        self.circuit_drawer(transpiled, filename='partial_layout.png')
+
     def test_init_reset(self):
         """Test reset and initialize with 1 and 2 qubits"""
         circuit = QuantumCircuit(2)
diff --git a/test/python/visualization/test_circuit_text_drawer.py b/test/python/visualization/test_circuit_text_drawer.py
--- a/test/python/visualization/test_circuit_text_drawer.py
+++ b/test/python/visualization/test_circuit_text_drawer.py
@@ -2823,6 +2823,26 @@ def test_mixed_layout(self):
         circuit.h(pqr)
         self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
 
+    def test_partial_layout(self):
+        """ With a partial layout.
+        See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
+        expected = '\n'.join(["            ┌───┐",
+                              "v_0 -> 0 |0>┤ H ├",
+                              "            └───┘",
+                              "       1 |0>─────",
+                              "                 ",
+                              "       2 |0>─────",
+                              "            ┌───┐",
+                              "v_1 -> 3 |0>┤ H ├",
+                              "            └───┘"])
+        qr = QuantumRegister(2, 'v')
+        pqr = QuantumRegister(4, 'physical')
+        circuit = QuantumCircuit(pqr)
+        circuit.h(0)
+        circuit.h(3)
+        circuit._layout = Layout({0: qr[0], 1: None, 2: None, 3: qr[1]})
+        self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
+
     def test_with_classical_regs(self):
         """ Involving classical registers"""
         expected = '\n'.join(["                    ",