diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 11070059c927..6bcdafceda97 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -1008,6 +1008,10 @@ def compose( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) + if len(set(mapped_qubits)) != len(mapped_qubits): + raise CircuitError( + f"Duplicate qubits referenced in 'qubits' parameter: '{mapped_qubits}'" + ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: @@ -1019,6 +1023,10 @@ def compose( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) + if len(set(mapped_clbits)) != len(mapped_clbits): + raise CircuitError( + f"Duplicate clbits referenced in 'clbits' parameter: '{mapped_clbits}'" + ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( diff --git a/releasenotes/notes/fix-circuit-compose-duplicate-59de6c1c51f58e54.yaml b/releasenotes/notes/fix-circuit-compose-duplicate-59de6c1c51f58e54.yaml new file mode 100644 index 000000000000..fbeb2d33c2c1 --- /dev/null +++ b/releasenotes/notes/fix-circuit-compose-duplicate-59de6c1c51f58e54.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + :meth:`.QuantumCircuit.compose` will now correctly raise a :exc:`.CircuitError` when there are + duplicates in the ``qubits`` or ``clbits`` arguments. diff --git a/test/python/circuit/test_compose.py b/test/python/circuit/test_compose.py index 70eaffb0f748..1c6d00915de1 100644 --- a/test/python/circuit/test_compose.py +++ b/test/python/circuit/test_compose.py @@ -31,6 +31,7 @@ Instruction, CASE_DEFAULT, SwitchCaseOp, + CircuitError, ) from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal from qiskit.circuit.classical import expr @@ -880,6 +881,16 @@ def test_expr_target_is_mapped(self): self.assertEqual(dest, expected) + def test_rejects_duplicate_bits(self): + """Test that compose rejects duplicates in either qubits or clbits.""" + base = QuantumCircuit(5, 5) + + attempt = QuantumCircuit(2, 2) + with self.assertRaisesRegex(CircuitError, "Duplicate qubits"): + base.compose(attempt, [1, 1], [0, 1]) + with self.assertRaisesRegex(CircuitError, "Duplicate clbits"): + base.compose(attempt, [0, 1], [1, 1]) + if __name__ == "__main__": unittest.main()