Skip to content

Commit 5cc3f56

Browse files
feat: implement commutativity between PauliStringMonomials
1 parent c30dfb7 commit 5cc3f56

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

mpqp/core/instruction/measurement/pauli_string.py

+28-6
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from typeguard import typechecked
1919

2020
from mpqp.core.languages import Language
21-
from mpqp.tools import format_element
21+
from mpqp.tools import format_element, NumberQubitsError
2222
from mpqp.tools.generics import Matrix
2323
from mpqp.tools.maths import atol, is_power_of_two, rtol
2424

@@ -830,7 +830,7 @@ class PauliStringMonomial(PauliString):
830830
def __init__(self, coef: Coef = 1, atoms: Optional[list["PauliStringAtom"]] = None):
831831
self.coef = coef
832832
"""Coefficient of the monomial."""
833-
self.atoms = [] if atoms is None else atoms
833+
self.atoms: list["PauliStringAtom"] = [] if atoms is None else atoms
834834
"""The list of atoms in the monomial."""
835835

836836
@property
@@ -932,15 +932,35 @@ def __hash__(self):
932932
atoms_as_tuples = tuple((atom.label for atom in self.atoms))
933933
return hash(atoms_as_tuples)
934934

935-
def commutes_with(self, p: PauliString):
936-
"""
937-
TODO: Determine EFFICIENTLY if this pauli monomial is commuting with the one in parameter.
935+
def commutes_with(self, pm: PauliStringMonomial) -> bool:
936+
"""Checks wether this Pauli monomial commutes (full commutativity) with the Pauli monomial in parameter. This
937+
is done by checking that the number of anti-commuting atoms is even.
938+
938939
Args:
939-
p:
940+
pm: The Pauli monomial for which we want to check commutativity with this monomial.
940941
941942
Returns:
943+
True if this Pauli monomial commutes with the one in parameter.
944+
945+
Examples:
946+
>>> (I @ X @ Y).commutes_with(Z @ Y @ X)
947+
True
948+
>>> (X @ Z @ Z).commutes_with(Y @ Z @ I)
949+
False
950+
>>> (X @ Z @ Z).commutes_with(X @ Z @ Z)
951+
True
942952
943953
"""
954+
if self.nb_qubits != pm.nb_qubits:
955+
raise NumberQubitsError(
956+
f"The number of qubits of this Pauli monomial {self.nb_qubits} is not matching "
957+
f"the one of the monomial in parameter {pm.nb_qubits}"
958+
)
959+
960+
return (
961+
sum(1 for a, b in zip(self.atoms, pm.atoms) if not a.commutes_with(b)) % 2
962+
== 0
963+
)
944964

945965
def subs(
946966
self, values: dict[Expr | str, Real], remove_symbolic: bool = True
@@ -1155,6 +1175,8 @@ def commutes_with(self, a: PauliStringAtom) -> bool:
11551175
False
11561176
>>> X.commutes_with(I)
11571177
True
1178+
>>> Y.commutes_with(Z)
1179+
False
11581180
>>> I.commutes_with(Z)
11591181
True
11601182
"""

0 commit comments

Comments
 (0)