Skip to content

Commit

Permalink
Reject bad values in SparsePauliOp.paulis setter (#10437) (#10643)
Browse files Browse the repository at this point in the history
* Fix Sparse pauli setter to update dimension info

* Fix Sparse pauli setter to verify dimension info

Value error will be raised if:
1. Number of qubits are not equal
2. Number of elements in PauliList are not equal

* Add tests

* Add release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
(cherry picked from commit fe87015)

Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>
  • Loading branch information
mergify[bot] and atharva-satpute committed Aug 16, 2023
1 parent 91ca2c4 commit 48a7b82
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,14 @@ def paulis(self):
def paulis(self, value):
if not isinstance(value, PauliList):
value = PauliList(value)
if value.num_qubits != self.num_qubits:
raise ValueError(
f"incorrect number of qubits: expected {self.num_qubits}, got {value.num_qubits}"
)
if len(value) != len(self.paulis):
raise ValueError(
f"incorrect number of operators: expected {len(self.paulis)}, got {len(value)}"
)
self._pauli_list = value

@property
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
fixes:
- |
The setter for :attr:`.SparsePauliOp.paulis` will now correctly reject attempts to set the
attribute with incorrectly shaped data, rather than silently allowing an invalid object to be
created. See `#10384 <https://github.com/Qiskit/qiskit-terra/issues/10384>`__.
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,14 @@ def test_assign_parameters(self):
with self.subTest(msg="fully bound"):
self.assertTrue(np.allclose(bound.coeffs.astype(complex), [1, 3, 6]))

def test_paulis_setter_rejects_bad_inputs(self):
"""Test that the setter for `paulis` rejects different-sized inputs."""
op = SparsePauliOp(["XY", "ZX"], coeffs=[1, 1j])
with self.assertRaisesRegex(ValueError, "incorrect number of qubits"):
op.paulis = PauliList([Pauli("X"), Pauli("Y")])
with self.assertRaisesRegex(ValueError, "incorrect number of operators"):
op.paulis = PauliList([Pauli("XY"), Pauli("ZX"), Pauli("YZ")])


if __name__ == "__main__":
unittest.main()

0 comments on commit 48a7b82

Please sign in to comment.