Skip to content

Commit

Permalink
Make ListOp.num_qubits check all ops for same num_qubits (qiskit-comm…
Browse files Browse the repository at this point in the history
…unity#1189)

* Make ListOp.num_qubits check all ops for same num_qubits

Previously, the number of qubits in the first operator in the ListOp
was returned. With this change, an additional check is made that all
other operators also have the same number of qubits.

Closes qiskit-community#1086

* Add release note for listop-check-num-qubits

Co-authored-by: Manoel Marques <Manoel.Marques@ibm.com>
  • Loading branch information
2 people authored and Cryoris committed Sep 3, 2020
1 parent 8335c3c commit 357d52d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion qiskit/aqua/operators/list_ops/list_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,10 @@ def primitive_strings(self) -> Set[str]:

@property
def num_qubits(self) -> int:
return self.oplist[0].num_qubits
num_qubits0 = self.oplist[0].num_qubits
if not all(num_qubits0 == op.num_qubits for op in self.oplist):
raise ValueError('Operators in ListOp have differing numbers of qubits.')
return num_qubits0

def add(self, other: OperatorBase) -> OperatorBase:
if self == other:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
Make ListOp.num_qubits check that all ops in list have the same num_qubits
Previously, the number of qubits in the first operator in the ListOp
was returned. With this change, an additional check is made that all
other operators also have the same number of qubits.
18 changes: 18 additions & 0 deletions test/aqua/operators/test_op_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,24 @@ def test_list_op_parameters(self):
self.assertEqual(list_op.parameters, set(params))


class TestOpMethods(QiskitAquaTestCase):
"""Basic method tests."""

def test_listop_num_qubits(self):
"""Test that ListOp.num_qubits checks that all operators have the same number of qubits."""
op = ListOp([X ^ Y, Y ^ Z])
with self.subTest('All operators have the same numbers of qubits'):
self.assertEqual(op.num_qubits, 2)

op = ListOp([X ^ Y, Y])
with self.subTest('Operators have different numbers of qubits'):
with self.assertRaises(ValueError):
op.num_qubits # pylint: disable=pointless-statement

with self.assertRaises(ValueError):
X @ op # pylint: disable=pointless-statement


class TestListOpComboFn(QiskitAquaTestCase):
"""Test combo fn is propagated."""

Expand Down

0 comments on commit 357d52d

Please sign in to comment.