Skip to content

Commit

Permalink
Deprecate simplify argument in qml.ops.Hamiltonian and `qml.Linea…
Browse files Browse the repository at this point in the history
…rCombination` (#5677)

**Context:** ***Part of  deprecations and removals for pennylane-0.37***

**Description of the Change:** Deprecating the ``simplify`` argument in
``qml.ops.Hamiltonian`` and ``qml.ops.LinearCombination`` in favour of
``qml.simplify()``.

[sc-59086]
  • Loading branch information
PietropaoloFrisoni authored May 16, 2024
1 parent fce552a commit 6855709
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 29 deletions.
7 changes: 7 additions & 0 deletions doc/development/deprecations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,17 @@ deprecations are listed below.
Pending deprecations
--------------------

* The ``simplify`` argument in ``qml.Hamiltonian`` and ``qml.ops.LinearCombination`` is deprecated.
Instead, ``qml.simplify()`` can be called on the constructed operator.

- Deprecated in v0.37
- Will be removed in v0.39

* ``qml.transforms.map_batch_transform`` is deprecated, since transforms can be applied directly to a batch of tapes.
See :func:`~.pennylane.transform` for more information.

- Deprecated in v0.37
- Will be removed in v0.38

New operator arithmetic deprecations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
10 changes: 7 additions & 3 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@
* `qml.is_commuting` no longer accepts the `wire_map` argument, which does not bring any functionality.
[(#5660)](https://github.com/PennyLaneAI/pennylane/pull/5660)

* ``qml.from_qasm_file`` has been removed. The user can open files and load their content using `qml.from_qasm`.
* `qml.from_qasm_file` has been removed. The user can open files and load their content using `qml.from_qasm`.
[(#5659)](https://github.com/PennyLaneAI/pennylane/pull/5659)

* ``qml.load`` has been removed in favour of more specific functions, such as ``qml.from_qiskit``, etc.
* `qml.load` has been removed in favour of more specific functions, such as `qml.from_qiskit`, etc.
[(#5654)](https://github.com/PennyLaneAI/pennylane/pull/5654)

<h4>Community contributions 🥳</h4>
Expand All @@ -105,7 +105,11 @@

<h3>Deprecations 👋</h3>

* ``qml.transforms.map_batch_transform`` is deprecated, since a transform can be applied directly to a batch of tapes.
* The `simplify` argument in `qml.Hamiltonian` and `qml.ops.LinearCombination` is deprecated.
Instead, `qml.simplify()` can be called on the constructed operator.
[(#5677)](https://github.com/PennyLaneAI/pennylane/pull/5677)

* `qml.transforms.map_batch_transform` is deprecated, since a transform can be applied directly to a batch of tapes.
[(#5676)](https://github.com/PennyLaneAI/pennylane/pull/5676)

<h3>Documentation 📝</h3>
Expand Down
4 changes: 2 additions & 2 deletions pennylane/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2033,7 +2033,7 @@ def __add__(self, other):
if isinstance(other, (qml.ops.Hamiltonian, qml.ops.LinearCombination)):
return other + self
if isinstance(other, (Observable, Tensor)):
return qml.Hamiltonian([1, 1], [self, other], simplify=True)
return qml.simplify(qml.Hamiltonian([1, 1], [self, other]))

return super().__add__(other=other)

Expand All @@ -2045,7 +2045,7 @@ def __mul__(self, a):
return super().__mul__(other=a)

if isinstance(a, (int, float)):
return qml.Hamiltonian([a], [self], simplify=True)
return qml.simplify(qml.Hamiltonian([a], [self]))

return super().__mul__(other=a)

Expand Down
13 changes: 12 additions & 1 deletion pennylane/ops/op_math/linear_combination.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class LinearCombination(Sum):
observables (Iterable[Observable]): observables in the ``LinearCombination`` expression, of same length as ``coeffs``
simplify (bool): Specifies whether the ``LinearCombination`` is simplified upon initialization
(like-terms are combined). The default value is `False`. Note that ``coeffs`` cannot
be differentiated when using the ``'torch'`` interface and ``simplify=True``.
be differentiated when using the ``'torch'`` interface and ``simplify=True``. Use of this argument is deprecated.
grouping_type (str): If not ``None``, compute and store information on how to group commuting
observables upon initialization. This information may be accessed when a :class:`~.QNode` containing this
``LinearCombination`` is executed on devices. The string refers to the type of binary relation between Pauli words.
Expand All @@ -48,6 +48,10 @@ class LinearCombination(Sum):
can be ``'lf'`` (Largest First) or ``'rlf'`` (Recursive Largest First). Ignored if ``grouping_type=None``.
id (str): name to be assigned to this ``LinearCombination`` instance
.. warning::
The ``simplify`` argument is deprecated and will be removed in a future release.
Instead, you can call ``qml.simplify`` on the constructed operator.
**Example:**
A ``LinearCombination`` can be created by simply passing the list of coefficients
Expand Down Expand Up @@ -131,6 +135,13 @@ def __init__(
_pauli_rep = self._build_pauli_rep_static(coeffs, observables)

if simplify:

warnings.warn(
"The simplify argument in qml.Hamiltonian and qml.ops.LinearCombination is deprecated. "
"Instead, you can call qml.simplify on the constructed operator.",
qml.PennyLaneDeprecationWarning,
)

# simplify upon initialization changes ops such that they wouldnt be removed in self.queue() anymore
if qml.QueuingManager.recording():
for o in observables:
Expand Down
23 changes: 17 additions & 6 deletions pennylane/ops/qubit/hamiltonian.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class Hamiltonian(Observable):
coeffs (tensor_like): coefficients of the Hamiltonian expression
observables (Iterable[Observable]): observables in the Hamiltonian expression, of same length as coeffs
simplify (bool): Specifies whether the Hamiltonian is simplified upon initialization
(like-terms are combined). The default value is `False`.
(like-terms are combined). The default value is `False`. Use of this argument is deprecated.
grouping_type (str): If not None, compute and store information on how to group commuting
observables upon initialization. This information may be accessed when QNodes containing this
Hamiltonian are executed on devices. The string refers to the type of binary relation between Pauli words.
Expand All @@ -86,6 +86,10 @@ class Hamiltonian(Observable):
can be ``'lf'`` (Largest First) or ``'rlf'`` (Recursive Largest First). Ignored if ``grouping_type=None``.
id (str): name to be assigned to this Hamiltonian instance
.. warning::
The ``simplify`` argument is deprecated and will be removed in a future release.
Instead, you can call ``qml.simplify`` on the constructed operator.
**Example:**
.. note::
Expand Down Expand Up @@ -279,6 +283,13 @@ def __init__(
self._grouping_indices = None

if simplify:

warn(
"The simplify argument in qml.Hamiltonian and qml.ops.LinearCombination is deprecated. "
"Instead, you can call qml.simplify on the constructed operator.",
qml.PennyLaneDeprecationWarning,
)

# simplify upon initialization changes ops such that they wouldnt be
# removed in self.queue() anymore, removing them here manually.
if qml.QueuingManager.recording():
Expand Down Expand Up @@ -744,12 +755,12 @@ def __matmul__(self, H):
coeffs = qml.math.kron(coeffs1, coeffs2)
ops_list = itertools.product(ops1, ops2)
terms = [qml.operation.Tensor(t[0], t[1]) for t in ops_list]
return Hamiltonian(coeffs, terms, simplify=True)
return qml.simplify(Hamiltonian(coeffs, terms))

if isinstance(H, (Tensor, Observable)):
terms = [op @ copy(H) for op in ops1]

return Hamiltonian(coeffs1, terms, simplify=True)
return qml.simplify(Hamiltonian(coeffs1, terms))

return NotImplemented

Expand All @@ -766,7 +777,7 @@ def __rmatmul__(self, H):
if isinstance(H, (Tensor, Observable)):
terms = [copy(H) @ op for op in ops1]

return Hamiltonian(coeffs1, terms, simplify=True)
return qml.simplify(Hamiltonian(coeffs1, terms))

return NotImplemented

Expand All @@ -781,14 +792,14 @@ def __add__(self, H):
if isinstance(H, Hamiltonian):
coeffs = qml.math.concatenate([self_coeffs, copy(H.coeffs)], axis=0)
ops.extend(H.ops.copy())
return Hamiltonian(coeffs, ops, simplify=True)
return qml.simplify(Hamiltonian(coeffs, ops))

if isinstance(H, (Tensor, Observable)):
coeffs = qml.math.concatenate(
[self_coeffs, qml.math.cast_like([1.0], self_coeffs)], axis=0
)
ops.append(H)
return Hamiltonian(coeffs, ops, simplify=True)
return qml.simplify(Hamiltonian(coeffs, ops))

return NotImplemented

Expand Down
6 changes: 3 additions & 3 deletions pennylane/transforms/batch_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ def map_batch_transform(
"""

warnings.warn(
"qml.transforms.map_batch_transform is deprecated."
"Instead, a transform can be applied directly to a batch of tapes."
"See :func:`~.pennylane.transform` for more details.",
"qml.transforms.map_batch_transform is deprecated. "
"Instead, a transform can be applied directly to a batch of tapes. "
"See qml.transform for more details.",
qml.PennyLaneDeprecationWarning,
)

Expand Down
75 changes: 67 additions & 8 deletions tests/ops/op_math/test_linear_combination.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,14 @@ def circuit2(param):
class TestLinearCombination:
"""Test the LinearCombination class"""

def test_deprecation_simplify_argument(self):
"""Test that a deprecation warning is raised if the simplify argument is True."""
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
_ = qml.ops.LinearCombination([1.0], [qml.X(0)], simplify=True)

def test_error_if_observables_operator(self):
"""Test thatt an error is raised if an operator is provided to observables."""

Expand All @@ -588,7 +596,14 @@ def test_error_if_observables_operator(self):
@pytest.mark.parametrize("coeffs, ops, true_pauli", PAULI_REPS)
def test_pauli_rep(self, coeffs, ops, true_pauli, simplify):
"""Test the pauli rep is correctly constructed"""
H = qml.ops.LinearCombination(coeffs, ops, simplify=simplify)
if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
H = qml.ops.LinearCombination(coeffs, ops, simplify=simplify)
else:
H = qml.ops.LinearCombination(coeffs, ops, simplify=simplify)
pr = H.pauli_rep
if simplify:
pr.simplify()
Expand Down Expand Up @@ -1629,7 +1644,11 @@ def circuit():
qml.RY(0.1, wires=0)
return qml.expval(qml.ops.LinearCombination([1.0, 2.0], [X(1), X(1)], simplify=True))

circuit()
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
circuit()
pars = circuit.qtape.get_parameters(trainable_only=False)
# simplify worked and added 1. and 2.
assert pars == [0.1, 3.0]
Expand All @@ -1639,7 +1658,11 @@ def test_queuing_behaviour(self):
"""Tests that the base observables are correctly dequeued with simplify=True"""

with qml.queuing.AnnotatedQueue() as q:
obs = qml.Hamiltonian([1, 1, 1], [qml.X(0), qml.X(0), qml.Z(0)], simplify=True)
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
obs = qml.Hamiltonian([1, 1, 1], [qml.X(0), qml.X(0), qml.Z(0)], simplify=True)

assert len(q) == 1
assert q.queue[0] == obs
Expand Down Expand Up @@ -1671,7 +1694,14 @@ def circuit(coeffs, param):
)

grad_fn = qml.grad(circuit)
grad = grad_fn(coeffs, param)
if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
grad = grad_fn(coeffs, param)
else:
grad = grad_fn(coeffs, param)

# differentiating a cost that combines circuits with
# measurements expval(Pauli)
Expand Down Expand Up @@ -1745,7 +1775,14 @@ def circuit(coeffs, param):
)

grad_fn = qml.grad(circuit)
grad = grad_fn(coeffs, param)
if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
grad = grad_fn(coeffs, param)
else:
grad = grad_fn(coeffs, param)

# differentiating a cost that combines circuits with
# measurements expval(Pauli)
Expand Down Expand Up @@ -1815,7 +1852,15 @@ def circuit(coeffs, param):
)

grad_fn = jax.grad(circuit)
grad = grad_fn(coeffs, param)

if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
grad = grad_fn(coeffs, param)
else:
grad = grad_fn(coeffs, param)

# differentiating a cost that combines circuits with
# measurements expval(Pauli)
Expand Down Expand Up @@ -1884,7 +1929,14 @@ def circuit(coeffs, param):
)
)

res = circuit(coeffs, param)
if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
res = circuit(coeffs, param)
else:
res = circuit(coeffs, param)
res.backward() # pylint:disable=no-member
grad = (coeffs.grad, param.grad)

Expand Down Expand Up @@ -1972,7 +2024,14 @@ def circuit(coeffs, param):
)

with tf.GradientTape() as tape:
res = circuit(coeffs, param)
if simplify:
with pytest.warns(
qml.PennyLaneDeprecationWarning,
match="deprecated",
):
res = circuit(coeffs, param)
else:
res = circuit(coeffs, param)
grad = tape.gradient(res, [coeffs, param])

# differentiating a cost that combines circuits with
Expand Down
Loading

0 comments on commit 6855709

Please sign in to comment.