Skip to content

Commit

Permalink
Remove usage of qml.Hamiltonian from hamiltonian.py (#5429)
Browse files Browse the repository at this point in the history
`hamiltonian.py` defines the legacy `Hamiltonian`. It should not be
returning `LinearCombination` in its own methods even with new op math
enabled.

Co-authored-by: qottmann <korbinian.kottmann@gmail.com>
  • Loading branch information
astralcai and Qottmann committed Mar 25, 2024
1 parent 9b22957 commit 0558038
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions pennylane/ops/qubit/hamiltonian.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class Hamiltonian(Observable):
The Hamiltonian is represented as a linear combination of other operators, e.g.,
:math:`\sum_{k=0}^{N-1} c_k O_k`, where the :math:`c_k` are trainable parameters.
Args:
coeffs (tensor_like): coefficients of the Hamiltonian expression
observables (Iterable[Observable]): observables in the Hamiltonian expression, of same length as coeffs
Expand Down Expand Up @@ -675,12 +676,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 qml.Hamiltonian(coeffs, terms, simplify=True)
return Hamiltonian(coeffs, terms, simplify=True)

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

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

return NotImplemented

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

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

return NotImplemented

Expand All @@ -712,14 +713,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 qml.Hamiltonian(coeffs, ops, simplify=True)
return Hamiltonian(coeffs, ops, simplify=True)

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 qml.Hamiltonian(coeffs, ops, simplify=True)
return Hamiltonian(coeffs, ops, simplify=True)

return NotImplemented

Expand All @@ -730,7 +731,7 @@ def __mul__(self, a):
if isinstance(a, (int, float)):
self_coeffs = copy(self.coeffs)
coeffs = qml.math.multiply(a, self_coeffs)
return qml.Hamiltonian(coeffs, self.ops.copy())
return Hamiltonian(coeffs, self.ops.copy())

return NotImplemented

Expand Down

0 comments on commit 0558038

Please sign in to comment.