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 qml.commutator function #5051

Merged
merged 45 commits into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
3ef8e19
[WIP] qml.commutator function
Qottmann Jan 12, 2024
2f8cead
add files
Qottmann Jan 12, 2024
327077a
[ci skip]
Qottmann Jan 12, 2024
5c65800
basic functionality
Qottmann Jan 12, 2024
c5acf79
formatting
Qottmann Jan 12, 2024
40969c2
clean up
Qottmann Jan 12, 2024
7200f92
black
Qottmann Jan 12, 2024
c977423
Merge branch 'master' of https://github.com/PennyLaneAI/pennylane int…
Qottmann Jan 12, 2024
4ffe91f
lint
Qottmann Jan 12, 2024
06ae8af
Merge branch 'master' of https://github.com/PennyLaneAI/pennylane int…
Qottmann Jan 15, 2024
a680c0e
add legacy test
Qottmann Jan 15, 2024
638ae70
legacy tests
Qottmann Jan 15, 2024
d1264e7
Documentation
Qottmann Jan 15, 2024
5672d20
changelog
Qottmann Jan 15, 2024
c972516
formatting
Qottmann Jan 15, 2024
b06c916
changelog
Qottmann Jan 15, 2024
74c64b7
Merge branch 'master' into commutator
Qottmann Jan 15, 2024
8b6d3e8
changelog
Qottmann Jan 15, 2024
0af20b2
Merge branch 'commutator' of https://github.com/PennyLaneAI/pennylane…
Qottmann Jan 15, 2024
8724ca9
merge
Qottmann Jan 16, 2024
cb9b2a7
Apply suggestions from code review
Qottmann Jan 16, 2024
62762df
Merge branch 'master' of https://github.com/PennyLaneAI/pennylane int…
Qottmann Jan 16, 2024
0ad8deb
xfail test
Qottmann Jan 16, 2024
4e9f7d3
qml.commutator -> comm
Qottmann Jan 16, 2024
6fbcb94
black
Qottmann Jan 16, 2024
dc6a3ab
changelog
Qottmann Jan 16, 2024
82a4c53
revert back to qml.commutator :)
Qottmann Jan 18, 2024
1754972
Merge branch 'master' of https://github.com/PennyLaneAI/pennylane int…
Qottmann Jan 18, 2024
6e6c2af
add alias and test
Qottmann Jan 18, 2024
605d3ed
black
Qottmann Jan 18, 2024
1d7a264
Merge branch 'master' into commutator
Qottmann Jan 18, 2024
2368914
Context managing
Qottmann Jan 22, 2024
aa2e630
add comment in usage details
Qottmann Jan 22, 2024
6c5a899
Merge branch 'master' into commutator
Qottmann Jan 22, 2024
56efc98
Apply suggestions from code review
Qottmann Jan 22, 2024
004e636
move alias
Qottmann Jan 22, 2024
1ab7ec1
black
Qottmann Jan 22, 2024
2e7f3e1
Apply suggestions from code review
Qottmann Jan 23, 2024
1c4b2a1
Merge branch 'master' into commutator
Qottmann Jan 23, 2024
89fbc7e
Merge branch 'master' into commutator
Qottmann Jan 23, 2024
e672c7d
Merge branch 'master' into commutator
Qottmann Jan 24, 2024
766a2a3
Update pennylane/ops/functions/commutator.py
Qottmann Jan 25, 2024
6806c7a
Update pennylane/ops/functions/commutator.py
Qottmann Jan 25, 2024
20dc3f9
Merge branch 'master' into commutator
Qottmann Jan 25, 2024
8a9ed89
retrigger CI
Qottmann Jan 25, 2024
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
31 changes: 31 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,37 @@
is now strictly faster for jax.
[(#4963)](https://github.com/PennyLaneAI/pennylane/pull/4963)

* New `qml.commutator` function that allows to compute commutators between
`qml.operation.Operator`, `qml.pauli.PauliWord` and `qml.pauli.PauliSentence` instances.
[(#5051)](https://github.com/PennyLaneAI/pennylane/pull/5051)

Basic usage with PennyLane operators.

```pycon
>>> qml.commutator(qml.PauliX(0), qml.PauliY(0))
2j*(PauliZ(wires=[0]))
```

We can return a `PauliSentence` instance by setting `pauli=True`.
trbromley marked this conversation as resolved.
Show resolved Hide resolved

```pycon
>>> op1 = qml.PauliX(0) @ qml.PauliX(1)
>>> op2 = qml.PauliY(0) + qml.PauliY(1)
>>> qml.commutator(op1, op2, pauli=True)
2j * X(1) @ Z(0)
+ 2j * Z(1) @ X(0)
```

We can also input `PauliWord` and `PauliSentence` instances.

```pycon
>>> op1 = PauliWord({0:"X", 1:"X"})
>>> op2 = PauliWord({0:"Y"}) + PauliWord({1:"Y"})
>>> qml.commutator(op1, op2, pauli=True)
2j * Z(0) @ X(1)
+ 2j * X(0) @ Z(1)
```

<h3>Improvements 🛠</h3>

* `device_vjp` can now be used with normal Tensorflow. Support has not yet been added
Expand Down
2 changes: 2 additions & 0 deletions pennylane/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@
matrix,
simplify,
iterative_qpe,
commutator,
comm,
)
from pennylane.optimize import *
from pennylane.vqe import ExpvalCost
Expand Down
3 changes: 3 additions & 0 deletions pennylane/ops/functions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@
~matrix
~simplify
~iterative_qpe
~commutator
Qottmann marked this conversation as resolved.
Show resolved Hide resolved
~comm

"""
from .bind_new_parameters import bind_new_parameters
from .commutator import commutator, comm
from .dot import dot
from .eigvals import eigvals
from .equal import equal
Expand Down
113 changes: 113 additions & 0 deletions pennylane/ops/functions/commutator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Copyright 2024 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This file contains the implementation of the commutator function in PennyLane
"""
import pennylane as qml
from pennylane.pauli import PauliWord, PauliSentence


def commutator(op1, op2, pauli=False):
r"""Compute commutator between two operators in PennyLane

.. math:: [O_1, O_2] = O_1 O_2 - O_2 O_1

Args:
op1 (Union[Operator, PauliWord, PauliSentence]): First operator
op2 (Union[Operator, PauliWord, PauliSentence]): Second operator
pauli (bool): When ``True``, all results are passed as a ``PauliSentence`` instance. Else, results are always returned as ``Operator`` instances.

Returns:
~Operator or ~PauliSentence: The commutator

**Examples**

You can compute commutators between operators in PennyLane.

>>> qml.commutator(qml.PauliX(0), qml.PauliY(0))
2j*(PauliZ(wires=[0]))

>>> op1 = qml.PauliX(0) @ qml.PauliX(1)
>>> op2 = qml.PauliY(0) @ qml.PauliY(1)
>>> qml.commutator(op1, op2)
0*(Identity(wires=[0, 1]))

We can return a :class:`~PauliSentence` instance by setting ``pauli=True``.

>>> op1 = qml.PauliX(0) @ qml.PauliX(1)
>>> op2 = qml.PauliY(0) + qml.PauliY(1)
>>> qml.commutator(op1, op2, pauli=True)
2j * X(1) @ Z(0)
+ 2j * Z(1) @ X(0)

We can also input :class:`~PauliWord` and :class:`~PauliSentence` instances.

>>> op1 = PauliWord({0:"X", 1:"X"})
Qottmann marked this conversation as resolved.
Show resolved Hide resolved
>>> op2 = PauliWord({0:"Y"}) + PauliWord({1:"Y"})
>>> qml.commutator(op1, op2, pauli=True)
2j * Z(0) @ X(1)
+ 2j * X(0) @ Z(1)

Note that when ``pauli=False``, even if Pauli operators are used
as inputs, ``qml.commutator`` returns Operators.

>>> qml.commutator(op1, op2, pauli=True)
(2j*(PauliX(wires=[1]) @ PauliZ(wires=[0]))) + (2j*(PauliZ(wires=[1]) @ PauliX(wires=[0])))

.. details::
:title: Usage Details

The input and result of ``qml.commutator`` is not recorded in a tape context (and inside a :class:`~QNode`).

.. code-block:: python3

with qml.tape.QuantumTape() as tape:
a = qml.PauliX(0) # gets recorded
b = PauliWord({0:"Y"}) # does not get recorded
comm = qml.commutator(a, b) # does not get recorded

In this example, we obtain ``tape.operations = [qml.PauliX(0)]``. When desired, we can still record the result of
the commutator by using :func:`~apply`, i.e. ``qml.apply(comm)`` inside the recording context.

A peculiarity worth repeating is how in a recording context every created operator is recorded.

.. code-block:: python3

with qml.tape.QuantumTape() as tape:
comm = qml.commutator(qml.PauliX(0), qml.PauliY(0))

In this example, both :class:`~PauliX` and :class:`PauliY` get recorded because they were created inside the
recording context. To avoid this, create the input to ``qml.commutator`` outside the recording context / qnode
or insert an extra ``stop_recording()`` context (see :class:`~QueuingManager`).
Qottmann marked this conversation as resolved.
Show resolved Hide resolved

"""
if pauli:
if not isinstance(op1, PauliSentence):
op1 = qml.pauli.pauli_sentence(op1)
if not isinstance(op2, PauliSentence):
op2 = qml.pauli.pauli_sentence(op2)
return op1 @ op2 - op2 @ op1

with qml.QueuingManager.stop_recording():
if isinstance(op1, (PauliWord, PauliSentence)):
op1 = op1.operation()
if isinstance(op2, (PauliWord, PauliSentence)):
op2 = op2.operation()

res = qml.sum(qml.prod(op1, op2), qml.s_prod(-1.0, qml.prod(op2, op1)))
res = res.simplify()
return res


comm = commutator # Slightly shorter alias
1 change: 0 additions & 1 deletion pennylane/ops/functions/equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ def _equal_operators(
# pylint: disable=unused-argument, protected-access
def _equal_prod_and_sum(op1: CompositeOp, op2: CompositeOp, **kwargs):
"""Determine whether two Prod or Sum objects are equal"""

if len(op1.operands) != len(op2.operands):
return False

Expand Down
7 changes: 7 additions & 0 deletions pennylane/pauli/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,13 @@ def pauli_sentence(op):
Returns:
.PauliSentence: the PauliSentence representation of an arithmetic operator or Hamiltonian
"""

if isinstance(op, PauliWord):
return PauliSentence({op: 1.0})

if isinstance(op, PauliSentence):
return op

if (ps := op.pauli_rep) is not None:
return ps

Expand Down
Loading
Loading