Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix evolved operator ansatz (backport #11682) #11965

Merged
merged 1 commit into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions qiskit/circuit/library/n_local/evolved_operator_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ def num_qubits(self) -> int:
if self.operators is None:
return 0

if isinstance(self.operators, list) and len(self.operators) > 0:
if isinstance(self.operators, list):
if len(self.operators) == 0:
return 0
return self.operators[0].num_qubits

return self.operators.num_qubits
Expand Down Expand Up @@ -152,7 +154,10 @@ def operators(self, operators=None) -> None:
operators = _validate_operators(operators)
self._invalidate()
self._operators = operators
self.qregs = [QuantumRegister(self.num_qubits, name="q")]
if self.num_qubits == 0:
self.qregs = []
else:
self.qregs = [QuantumRegister(self.num_qubits, name="q")]

# TODO: the `preferred_init_points`-implementation can (and should!) be improved!
@property
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
fixes:
- |
The :class:`.EvolvedOperatorAnsatz` now correctly handles the case where the
`operators` argument is an empty list. Previously, this would result in an
error.
- |
From now on, :class:`.EvolvedOperatorAnsatz` will not have any `qregs` when
thera are zero qubits, instead of having a :class:`.QuantumRegister` instance
with zero qubits. This behavior aligns more consistently with its superclass
:class:`.QuantumCircuit`.
5 changes: 5 additions & 0 deletions test/python/circuit/library/test_evolved_op_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ def test_empty_build_fails(self):
with self.assertRaises(ValueError):
_ = evo.draw()

def test_empty_operator_list(self):
"""Test setting an empty list of operators to be equal to an empty circuit."""
evo = EvolvedOperatorAnsatz([])
self.assertEqual(evo, QuantumCircuit())

def test_matrix_operator(self):
"""Test passing a quantum_info.Operator uses the HamiltonianGate."""
unitary = Operator([[0, 1], [1, 0]])
Expand Down
Loading