# Buggy code
def run(self, dag):
    """iterate over each block and replace it with an equivalent Unitary
    on the same wires.
    """
    new_dag = DAGCircuit()
    for qreg in dag.qregs.values():
        new_dag.add_qreg(qreg)
    for creg in dag.cregs.values():
        new_dag.add_creg(creg)

    # compute ordered indices for the global circuit wires
    global_index_map = {}
    for wire in dag.wires:
        if not isinstance(wire, Qubit):
            continue
        global_qregs = list(dag.qregs.values())
        global_index_map[wire] = global_qregs.index(wire.register) + wire.index

    blocks = self.property_set["block_list"]
    # just to make checking if a node is in any block easier
    all_block_nodes = {nd for bl in blocks for nd in bl}

    for node in dag.topological_op_nodes():
        if node not in all_block_nodes:
            # need to add this node to find out where in the list it goes
            preds = [nd for nd in dag.predecessors(node) if nd.type == "op"]

            block_count = 0
            while preds:
                if block_count < len(blocks):
                    block = blocks[block_count]

                    # if any of the predecessors are in the block, remove them
                    preds = [p for p in preds if p not in block]
                else:
                    # should never occur as this would mean not all
                    # nodes before this one topologically had been added
                    # so not all predecessors were removed
                    raise TranspilerError(
                        "Not all predecessors removed due to error in topological order"
                    )

                block_count += 1

            # we have now seen all predecessors
            # so update the blocks list to include this block
            blocks = blocks[:block_count] + [[node]] + blocks[block_count:]

    # create the dag from the updated list of blocks
    basis_gate_name = self.decomposer.gate.name
    for block in blocks:
        if len(block) == 1 and block[0].name != "cx":
            # an intermediate node that was added into the overall list
            new_dag.apply_operation_back(
                block[0].op, block[0].qargs, block[0].cargs, block[0].condition
            )
        else:
            # find the qubits involved in this block
            block_qargs = set()
            for nd in block:
                block_qargs |= set(nd.qargs)
            # convert block to a sub-circuit, then simulate unitary and add
            block_width = len(block_qargs)
            q = QuantumRegister(block_width)
            subcirc = QuantumCircuit(q)
            block_index_map = self._block_qargs_to_indices(
                block_qargs, global_index_map
            )
            basis_count = 0
            for nd in block:
                if nd.op.name == basis_gate_name:
                    basis_count += 1
                subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])
            unitary = UnitaryGate(Operator(subcirc))  # simulates the circuit
            if (
                self.force_consolidate
                or unitary.num_qubits > 2
                or self.decomposer.num_basis_gates(unitary) != basis_count
            ):
                new_dag.apply_operation_back(
                    unitary, sorted(block_qargs, key=lambda x: block_index_map[x])
                )
            else:
                for nd in block:
                    new_dag.apply_operation_back(
                        nd.op, nd.qargs, nd.cargs, nd.condition
                    )

    return new_dag


# Traceback (qiskit.exceptions.QiskitError)
qr1 = qk.QuantumRegister(1)
qr2 = qk.QuantumRegister(2)
qc = qk.QuantumCircuit(qr2, qr1, cr)
qc.cx(qr1[0], qr2[1])
qc.measure(qr1[0], cr[0])
qk.transpile(qc, optimization_level=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 187, in transpile
circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/tools/parallel.py", line 100, in parallel_map
return [task(values[0], *task_args, **task_kwargs)]
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 208, in _transpile_circuit
return transpile_circuit(circuit, transpile_config)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/transpile_circuit.py", line 65, in transpile_circuit
return pass_manager.run(circuit)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 171, in run
dag = self._do_pass(pass_, dag, passset.options)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 202, in _do_pass
dag = self._run_this_pass(pass_, dag)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 215, in _run_this_pass
new_dag = pass_.run(dag)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passes/consolidate_blocks.py", line 93, in run
subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/circuit/quantumcircuit.py", line 359, in append
instructions.add(self._append(instruction, qarg, carg), qarg, carg)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/circuit/quantumcircuit.py", line 382, in _append
self._check_dups(qargs)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/circuit/quantumcircuit.py", line 438, in _check_dups
raise QiskitError("duplicate qubit arguments")
qiskit.exceptions.QiskitError: 'duplicate qubit arguments'

# Fixed code
def run(self, dag):
    """iterate over each block and replace it with an equivalent Unitary
    on the same wires.
    """
    new_dag = DAGCircuit()
    for qreg in dag.qregs.values():
        new_dag.add_qreg(qreg)
    for creg in dag.cregs.values():
        new_dag.add_creg(creg)

    # compute ordered indices for the global circuit wires
    global_index_map = {wire: idx for idx, wire in enumerate(dag.qubits())}

    blocks = self.property_set["block_list"]
    # just to make checking if a node is in any block easier
    all_block_nodes = {nd for bl in blocks for nd in bl}

    for node in dag.topological_op_nodes():
        if node not in all_block_nodes:
            # need to add this node to find out where in the list it goes
            preds = [nd for nd in dag.predecessors(node) if nd.type == "op"]

            block_count = 0
            while preds:
                if block_count < len(blocks):
                    block = blocks[block_count]

                    # if any of the predecessors are in the block, remove them
                    preds = [p for p in preds if p not in block]
                else:
                    # should never occur as this would mean not all
                    # nodes before this one topologically had been added
                    # so not all predecessors were removed
                    raise TranspilerError(
                        "Not all predecessors removed due to error in topological order"
                    )

                block_count += 1

            # we have now seen all predecessors
            # so update the blocks list to include this block
            blocks = blocks[:block_count] + [[node]] + blocks[block_count:]

    # create the dag from the updated list of blocks
    basis_gate_name = self.decomposer.gate.name
    for block in blocks:
        if len(block) == 1 and block[0].name != "cx":
            # an intermediate node that was added into the overall list
            new_dag.apply_operation_back(
                block[0].op, block[0].qargs, block[0].cargs, block[0].condition
            )
        else:
            # find the qubits involved in this block
            block_qargs = set()
            for nd in block:
                block_qargs |= set(nd.qargs)
            # convert block to a sub-circuit, then simulate unitary and add
            block_width = len(block_qargs)
            q = QuantumRegister(block_width)
            subcirc = QuantumCircuit(q)
            block_index_map = self._block_qargs_to_indices(
                block_qargs, global_index_map
            )
            basis_count = 0
            for nd in block:
                if nd.op.name == basis_gate_name:
                    basis_count += 1
                subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])
            unitary = UnitaryGate(Operator(subcirc))  # simulates the circuit
            if (
                self.force_consolidate
                or unitary.num_qubits > 2
                or self.decomposer.num_basis_gates(unitary) != basis_count
            ):
                new_dag.apply_operation_back(
                    unitary, sorted(block_qargs, key=lambda x: block_index_map[x])
                )
            else:
                for nd in block:
                    new_dag.apply_operation_back(
                        nd.op, nd.qargs, nd.cargs, nd.condition
                    )

    return new_dag