Repository: PennyLaneAI/pennylane
Pull request #1533 (2021-08-16 14:20:02)

Fix issue when computing the specs of a qnode measuring a Hamiltonian
Currently this code throws an error:

```python
import pennylane as qml

dev = qml.device("default.qubit", wires=2)
H = qml.Hamiltonian([0.1, 0.2], [qml.PauliZ(0), qml.PauliZ(0) @ qml.PauliX(1)])
@qml.qnode(dev)
def circuit():
    return qml.expval(H)

res = qml.specs(circuit)()
print(res)
```

The reason is that `specs` (or more precisely, `tape.diagonalizing_gates`) assumes that an observable has `diagonalizing_gates` defined. The new Hamiltonian observable does not, since we do not know its diagonalisation. This is a new use case for an observable, and we need to think of a longer term solution when overhauling the operation class.

For now we fix this by returning an empty list as diagonalising gates of the Hamiltonian.

github-actions[bot]: Hello. You may have forgotten to update the changelog!
Please edit [.github/CHANGELOG.md](/PennyLaneAI/pennylane/blob/master/.github/CHANGELOG.md) with:
* A one-to-two sentence description of the change. You may include a small working example for new features.
* A link back to this PR.
* Your name (or GitHub username) in the contributors section.
codecov[bot]: # [Codecov](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
> Merging [#1533](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (543a0c5) into [master](https://codecov.io/gh/PennyLaneAI/pennylane/commit/683fbfad43274dab9138e3a429b11b4824f02c24?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (683fbfa) will **increase** coverage by `0.00%`.
> The diff coverage is `100.00%`.

> :exclamation: Current head 543a0c5 differs from pull request most recent head abb4d1c. Consider uploading reports for the commit abb4d1c to get more accurate results
[![Impacted file tree graph](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533/graphs/tree.svg?width=650&height=150&src=pr&token=9S3YzlUgGk&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI)](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI)

```diff
@@           Coverage Diff           @@
##           master    #1533   +/-   ##
=======================================
  Coverage   98.23%   98.23%           
=======================================
  Files         187      187           
  Lines       13370    13372    +2     
=======================================
+ Hits        13134    13136    +2     
  Misses        236      236           
```


| [Impacted Files](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) | Coverage Δ | |
|---|---|---|
| [pennylane/vqe/vqe.py](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#diff-cGVubnlsYW5lL3ZxZS92cWUucHk=) | `93.00% <100.00%> (+0.05%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI). Last update [683fbfa...abb4d1c](https://codecov.io/gh/PennyLaneAI/pennylane/pull/1533?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).


Patch:
diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md
index 05f61a7ed..792fc84a0 100644
--- a/.github/CHANGELOG.md
+++ b/.github/CHANGELOG.md
@@ -125,6 +125,9 @@
 
 <h3>Bug fixes</h3>
 
+* Fix bug when computing the specs of a circuit with a Hamiltonian observable.
+  [(#1533)](https://github.com/PennyLaneAI/pennylane/pull/1533)
+
 <h3>Documentation</h3>
 
 <h3>Contributors</h3>
diff --git a/pennylane/tape/tape.py b/pennylane/tape/tape.py
index 50593afbb..48841218b 100644
--- a/pennylane/tape/tape.py
+++ b/pennylane/tape/tape.py
@@ -977,7 +977,12 @@ class QuantumTape(AnnotatedQueue):
         rotation_gates = []
 
         for observable in self.observables:
-            rotation_gates.extend(observable.diagonalizing_gates())
+            try:
+                # some observables do not have diagonalizing gates,
+                # in which case we just don't append any
+                rotation_gates.extend(observable.diagonalizing_gates())
+            except NotImplementedError:
+                pass
 
         return rotation_gates
 


Test patch:
diff --git a/tests/test_vqe.py b/tests/test_vqe.py
index 3c74455cc..3385ed8a3 100644
--- a/tests/test_vqe.py
+++ b/tests/test_vqe.py
@@ -1452,6 +1452,23 @@ class TestNewVQE:
         dc = jax.grad(circuit)(w)
         assert np.allclose(dc, big_hamiltonian_grad, atol=tol)
 
+    def test_specs(self):
+        """Test that the specs of a VQE circuit can be computed"""
+        dev = qml.device("default.qubit", wires=2)
+        H = qml.Hamiltonian([0.1, 0.2], [qml.PauliZ(0), qml.PauliZ(0) @ qml.PauliX(1)])
+
+        @qml.qnode(dev)
+        def circuit():
+            qml.Hadamard(wires=0)
+            qml.CNOT(wires=[0, 1])
+            return qml.expval(H)
+
+        res = qml.specs(circuit)()
+
+        assert res["num_observables"] == 1
+        assert res["num_diagonalizing_gates"] == 0
+        assert res["num_used_wires"] == 2
+
 
 class TestAutogradInterface:
     """Tests for the Autograd interface (and the NumPy interface for backward compatibility)"""