Skip to content

Commit

Permalink
If input paulis have phase, mutate and warn
Browse files Browse the repository at this point in the history
  • Loading branch information
aeddins-ibm committed Aug 2, 2024
1 parent e5aad3c commit 836126e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
12 changes: 10 additions & 2 deletions qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections.abc import Mapping, Sequence, Iterable
from numbers import Number
from copy import deepcopy
import warnings

import numpy as np
import rustworkx as rx
Expand Down Expand Up @@ -256,8 +257,15 @@ def paulis(self, value):
raise ValueError(
f"incorrect number of operators: expected {len(self.paulis)}, got {len(value)}"
)
self.coeffs *= (-1j) ** value.phase
self._pauli_list = PauliList.from_symplectic(value.z, value.x, phase=0)
if np.any(value.phase):
warnings.warn(
"Assigning SparsePauliOp.paulis to be a PauliList with nonzero phase sets the phase "
"of the given PauliList to zero, absorbing the phase into SparsePauliOp.coeffs.",
UserWarning,
)
self.coeffs *= (-1j) ** value.phase
value.phase = 0
self._pauli_list = value

@property
def coeffs(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1102,13 +1102,15 @@ def test_paulis_setter_absorbs_phase(self):
coeffs_init = np.array([1, 1j])
op = SparsePauliOp(["XY", "ZX"], coeffs=coeffs_init)
paulis_new = PauliList(["-1jXY", "1jZX"])
op.paulis = paulis_new
with self.assertWarns(UserWarning):
# Raise a warning that the RHS is mutated:
op.paulis = paulis_new
# Paulis attribute should have no phase:
self.assertEqual(op.paulis, PauliList(["XY", "ZX"]))
# Coeffs attribute should now include that phase:
self.assertTrue(np.allclose(op.coeffs, coeffs_init * np.array([-1j, 1j])))
# Do not mutate the phase of the input array:
self.assertTrue(np.allclose(paulis_new.phase, np.array([1, 3])))
# The phase of the input array is now zero:
self.assertTrue(np.allclose(paulis_new.phase, np.array([0, 0])))

def test_apply_layout_with_transpile(self):
"""Test the apply_layout method with a transpiler layout."""
Expand Down

0 comments on commit 836126e

Please sign in to comment.