# Buggy code
def run(self, dag):
    """Run the SabreLayout pass on `dag`.

    Args:
        dag (DAGCircuit): DAG to find layout for.

    Raises:
        TranspilerError: if dag wider than self.coupling_map
    """
    if len(dag.qubits) > self.coupling_map.size():
        raise TranspilerError("More virtual qubits exist than physical.")

    # Choose a random initial_layout.
    if self.seed is None:
        self.seed = np.random.randint(0, np.iinfo(np.int32).max)
    rng = np.random.default_rng(self.seed)

    physical_qubits = rng.choice(
        self.coupling_map.size(), len(dag.qubits), replace=False
    )
    physical_qubits = rng.permutation(physical_qubits)
    initial_layout = Layout({q: dag.qubits[i] for i, q in enumerate(physical_qubits)})

    if self.routing_pass is None:
        self.routing_pass = SabreSwap(self.coupling_map, "decay", seed=self.seed)

    # Do forward-backward iterations.
    circ = dag_to_circuit(dag)
    for i in range(self.max_iterations):
        for _ in ("forward", "backward"):
            pm = self._layout_and_route_passmanager(initial_layout)
            new_circ = pm.run(circ)

            # Update initial layout and reverse the unmapped circuit.
            pass_final_layout = pm.property_set["final_layout"]
            final_layout = self._compose_layouts(
                initial_layout, pass_final_layout, circ.qregs
            )
            initial_layout = final_layout
            circ = circ.reverse_ops()

        # Diagnostics
        logger.info(
            "After round %d, num_swaps: %d", i + 1, new_circ.count_ops().get("swap", 0)
        )
        logger.info("new initial layout")
        logger.info(initial_layout)

    self.property_set["layout"] = initial_layout


# Traceback (KeyError)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-21-ce5f1efe766e> in <module>
51
52 # Run passes
---> 53 logical_qreg = pm.run(logical)
54 physical_qreg = pm.run(physical)

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\passmanager.py in run(self, circuits, output_name, callback)
212         """
213         if isinstance(circuits, QuantumCircuit):
--> 214             return self._run_single_circuit(circuits, output_name, callback)
215         elif len(circuits) == 1:
216             return self._run_single_circuit(circuits[0], output_name, callback)

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\passmanager.py in _run_single_circuit(self, circuit, output_name, callback)
275         if callback is None and self.callback:  # TODO to remove with __init__(callback)
276             callback = self.callback
--> 277         result = running_passmanager.run(circuit, output_name=output_name, callback=callback)
278         self.property_set = running_passmanager.property_set
279         return result

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\runningpassmanager.py in run(***failed resolving arguments***)
113         for passset in self.working_list:
114             for pass_ in passset:
--> 115                 dag = self._do_pass(pass_, dag, passset.options)
116
117         circuit = dag_to_circuit(dag)

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\runningpassmanager.py in _do_pass(self, pass_, dag, options)
143         # Run the pass itself, if not already run
144         if pass_ not in self.valid_passes:
--> 145             dag = self._run_this_pass(pass_, dag)
146
147             # update the valid_passes property

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\runningpassmanager.py in _run_this_pass(self, pass_, dag)
174             # Measure time if we have a callback or logging set
175             start_time = time()
--> 176             pass_.run(FencedDAGCircuit(dag))
177             end_time = time()
178             run_time = end_time - start_time

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\passes\layout\sabre_layout.py in run(self, dag)
105                 final_layout = self._compose_layouts(initial_layout,
106                                                      pass_final_layout,
--> 107                                                      circ.qregs)
108                 initial_layout = final_layout
109                 circ = circ.reverse_ops()

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\passes\layout\sabre_layout.py in _compose_layouts(self, initial_layout, pass_final_layout, qregs)
141         trivial_layout = Layout.generate_trivial_layout(*qregs)
142         pass_final_layout = Layout({trivial_layout[v.index]: p
--> 143                                     for v, p in pass_final_layout.get_virtual_bits().items()})
144         qubit_map = Layout.combine_into_edge_map(initial_layout, trivial_layout)
145         final_layout = {v: pass_final_layout[qubit_map[v]]

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\passes\layout\sabre_layout.py in <dictcomp>(.0)
141         trivial_layout = Layout.generate_trivial_layout(*qregs)
142         pass_final_layout = Layout({trivial_layout[v.index]: p
--> 143                                     for v, p in pass_final_layout.get_virtual_bits().items()})
144         qubit_map = Layout.combine_into_edge_map(initial_layout, trivial_layout)
145         final_layout = {v: pass_final_layout[qubit_map[v]]

c:\anaconda3\envs\qubit\lib\site-packages\qiskit\transpiler\layout.py in __getitem__(self, item)
102         if item in self._v2p:
103             return self._v2p[item]
--> 104         raise KeyError('The item %s does not exist in the Layout' % (item,))
105
106     def __setitem__(self, key, value):

KeyError: 'The item 6 does not exist in the Layout'

# Fixed code
def run(self, dag):
    """Run the SabreLayout pass on `dag`.

    Args:
        dag (DAGCircuit): DAG to find layout for.

    Raises:
        TranspilerError: if dag wider than self.coupling_map
    """
    if len(dag.qubits) > self.coupling_map.size():
        raise TranspilerError("More virtual qubits exist than physical.")

    # Choose a random initial_layout.
    if self.seed is None:
        self.seed = np.random.randint(0, np.iinfo(np.int32).max)
    rng = np.random.default_rng(self.seed)

    physical_qubits = rng.choice(
        self.coupling_map.size(), len(dag.qubits), replace=False
    )
    physical_qubits = rng.permutation(physical_qubits)
    initial_layout = Layout({q: dag.qubits[i] for i, q in enumerate(physical_qubits)})

    if self.routing_pass is None:
        self.routing_pass = SabreSwap(self.coupling_map, "decay", seed=self.seed)

    # Do forward-backward iterations.
    circ = dag_to_circuit(dag)
    for i in range(self.max_iterations):
        for _ in ("forward", "backward"):
            pm = self._layout_and_route_passmanager(initial_layout)
            new_circ = pm.run(circ)

            # Update initial layout and reverse the unmapped circuit.
            pass_final_layout = pm.property_set["final_layout"]
            final_layout = self._compose_layouts(
                initial_layout, pass_final_layout, new_circ.qregs
            )
            initial_layout = final_layout
            circ = circ.reverse_ops()

        # Diagnostics
        logger.info(
            "After round %d, num_swaps: %d", i + 1, new_circ.count_ops().get("swap", 0)
        )
        logger.info("new initial layout")
        logger.info(initial_layout)

    self.property_set["layout"] = initial_layout