diff --git a/qiskit/dagcircuit/collect_blocks.py b/qiskit/dagcircuit/collect_blocks.py index cf9adf16fe85..b15cfee71087 100644 --- a/qiskit/dagcircuit/collect_blocks.py +++ b/qiskit/dagcircuit/collect_blocks.py @@ -346,7 +346,7 @@ def collapse_to_operation(self, blocks, collapse_fn): # Additionally, find the set of classical registers used in conditions over full registers # (in such a case, we need to add that register to the block circuit, not just its clbits). - cur_clregs = [] + cur_clregs = set() for node in block: cur_qubits.update(node.qargs) @@ -355,7 +355,7 @@ def collapse_to_operation(self, blocks, collapse_fn): if cond is not None: cur_clbits.update(condition_resources(cond).clbits) if isinstance(cond[0], ClassicalRegister): - cur_clregs.append(cond[0]) + cur_clregs.add(cond[0]) # For reproducibility, order these qubits/clbits compatibly with the global order. sorted_qubits = sorted(cur_qubits, key=lambda x: global_index_map[x]) diff --git a/releasenotes/notes/fix-block-collapser-cregs-6c2d2dc6931d7bad.yaml b/releasenotes/notes/fix-block-collapser-cregs-6c2d2dc6931d7bad.yaml new file mode 100644 index 000000000000..57543efb27bd --- /dev/null +++ b/releasenotes/notes/fix-block-collapser-cregs-6c2d2dc6931d7bad.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + The :class:`.BlockCollapser` transpiler pass will now correctly handle circuits that contain + more than one condition on the same classical register. diff --git a/test/python/dagcircuit/test_collect_blocks.py b/test/python/dagcircuit/test_collect_blocks.py index adcfd2be2eed..2cfae5486083 100644 --- a/test/python/dagcircuit/test_collect_blocks.py +++ b/test/python/dagcircuit/test_collect_blocks.py @@ -914,6 +914,23 @@ def test_split_layers_dagdependency(self): self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) + def test_block_collapser_register_condition(self): + """Test that BlockCollapser can handle a register being used more than once.""" + qc = QuantumCircuit(1, 2) + qc.x(0).c_if(qc.cregs[0], 0) + qc.y(0).c_if(qc.cregs[0], 1) + + dag = circuit_to_dag(qc) + blocks = BlockCollector(dag).collect_all_matching_blocks( + lambda _: True, split_blocks=False, min_block_size=1 + ) + dag = BlockCollapser(dag).collapse_to_operation(blocks, lambda circ: circ.to_instruction()) + collapsed_qc = dag_to_circuit(dag) + + self.assertEqual(len(collapsed_qc.data), 1) + self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 1) + self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) + if __name__ == "__main__": unittest.main()