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

Add __iadd__ method to PauliSentence #4662

Merged
merged 14 commits into from
Oct 30, 2023
4 changes: 4 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
* Updates to some relevant Pytests to enable its use as a suite of benchmarks.
[(#4703)](https://github.com/PennyLaneAI/pennylane/pull/4703)

* Added `__iadd__` method to PauliSentence, which enables inplace-addition using `+=`, we no longer need to perform a copy, leading to performance improvements.
[(#4662)](https://github.com/PennyLaneAI/pennylane/pull/4662)

* `qml.ArbitraryUnitary` now supports batching.
[(#4745)](https://github.com/PennyLaneAI/pennylane/pull/4745)

Expand All @@ -28,5 +31,6 @@
This release contains contributions from (in alphabetical order):

Amintor Dusko,
Anurav Modak,
David Wierichs,
Justin Woodring
9 changes: 9 additions & 0 deletions pennylane/pauli/pauli_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,15 @@ def __add__(self, other):

return larger_ps

def __iadd__(self, other):
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved
"""Inplace addition of two Pauli sentence together by adding terms of other to self"""
for key in other:
if key in self:
self[key] += other[key]
else:
self[key] = other[key]
return self

def __copy__(self):
"""Copy the PauliSentence instance."""
copied_ps = {}
Expand Down
11 changes: 11 additions & 0 deletions tests/pauli/test_pauli_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,17 @@ def test_add(self, string1, string2, result):
(ps5, "Can't get the matrix of an empty PauliSentence."),
)

@pytest.mark.parametrize("string1, string2, result", tup_ps_add)
def test_iadd(self, string1, string2, result):
"""Test that the correct result of inplace addition is produced and other object is not changed."""
copied_string1 = copy(string1)
copied_string2 = copy(string2)
copied_string1 += copied_string2
copied_string1.simplify()

assert copied_string1 == result # Check if the modified object matches the expected result
assert copied_string2 == string2 # Ensure the original object is not modified
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved

@pytest.mark.parametrize("ps, match", ps_match)
def test_to_mat_error_empty(self, ps, match):
"""Test that an appropriate error is raised when an empty
Expand Down
Loading