diff --git a/qiskit/circuit/library/grover_operator.py b/qiskit/circuit/library/grover_operator.py index 03464bec5628..28d373341f47 100644 --- a/qiskit/circuit/library/grover_operator.py +++ b/qiskit/circuit/library/grover_operator.py @@ -15,6 +15,7 @@ from typing import List, Optional, Union import numpy from qiskit.circuit import QuantumCircuit, QuantumRegister, AncillaRegister +from qiskit.exceptions import QiskitError from qiskit.quantum_info import Statevector, Operator, DensityMatrix from .standard_gates import MCXGate @@ -274,10 +275,10 @@ def _build(self): circuit.global_phase = numpy.pi self.add_register(*circuit.qregs) - if self._insert_barriers: - circuit_wrapped = circuit.to_instruction() - else: + try: circuit_wrapped = circuit.to_gate() + except QiskitError: + circuit_wrapped = circuit.to_instruction() self.compose(circuit_wrapped, qubits=self.qubits, inplace=True) diff --git a/test/python/circuit/library/test_grover_operator.py b/test/python/circuit/library/test_grover_operator.py index 9f6d47cb6902..3fd27c02d212 100644 --- a/test/python/circuit/library/test_grover_operator.py +++ b/test/python/circuit/library/test_grover_operator.py @@ -69,6 +69,21 @@ def test_quantum_info_input(self): grover_op, oracle=np.diag((-1) ** mark.data), zero_reflection=diffuse.data ) + def test_stateprep_contains_instruction(self): + """Test wrapping works if the state preparation is not unitary.""" + oracle = QuantumCircuit(1) + oracle.z(0) + + instr = QuantumCircuit(1) + instr.s(0) + instr = instr.to_instruction() + + stateprep = QuantumCircuit(1) + stateprep.append(instr, [0]) + + grover_op = GroverOperator(oracle, stateprep) + self.assertEqual(grover_op.num_qubits, 1) + def test_reflection_qubits(self): """Test setting idle qubits doesn't apply any operations on these qubits.""" oracle = QuantumCircuit(4)