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

Reject bad values in SparsePauliOp.paulis setter (backport #10437) #10643

Merged
merged 1 commit into from
Aug 16, 2023
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
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()