# From \`qml.Hamiltonian\` to numpy representation

**URL:** <https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320>\
**Category:** PennyLane Help\
**Created:** [August 26, 2021, 1:51pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320 "2021-08-26T13:51:56Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Javier](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/javier/32/324_2.png) [@Javier](https://discuss.pennylane.ai/u/Javier)\
**Post date:** [August 26, 2021, 1:51pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/1 "2021-08-26T13:51:56Z")

</div>

Hi,

I have a question regarding the `qml.Hamiltonian` function. Given that I have a Hamiltonian written as a `qml.Hamiltonian`, can I see it’s matrix representation as a `np.array`? The point of this is because I want to use a circuit that does the following:

```
def circuit(params):
        # performs some operations
        return qml.expval(qml.Hermitian(array), wires = [...])

```

I know that a possibility is to use `qml.ExpvalCost()` instead of doing this. However, I want to use JAX here so that instead of working with `circuit` I work with `vcircuit = jax.vmap(circuit)` so I can run the same circuit for multiple parameters simultaneously.

Also, the point of this is because I know how to write my Hamiltonian efficiently in terms of the parameters needed for `qml.Hamiltonian` (it’s basically a sum of local terms so I can use `qml.PauliX` operations together with the Y and Z).

On the other hand, in the `qml.Hamiltonian` documentation I see that it is possible to go from `qml.Hermitian` to `qml.Hamiltonian`, so I wonder whether it is possible to do it the other way around, i.e., given that I have a `qml.Hamiltonian`, could I generate the corresponding `qml.Hermitian`?

Thank you very much for your attention.

Cheers,  
Javier.

---

<div class="post-metadata">

**Author:** ![Ant\_Hayes](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/ant_hayes/32/455_2.png) [@Ant\_Hayes](https://discuss.pennylane.ai/u/Ant_Hayes)\
**Post date:** [August 26, 2021, 7:07pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/2 "2021-08-26T19:07:09Z")

</div>

Hi Javier,

Thanks for the question! The `qml.Hamilonian` class does not currently have a `matrix` attribute however the [`qml.Operation`](https://pennylane.readthedocs.io/en/stable/code/api/pennylane.operation.Operation.html#pennylane.operation.Operation.matrix) class does which returns a numpy (nd)array as you’re looking for. Since a Hamiltonian is built up of operators and coefficients we can find work around e.g

```python
import pennylane as qml

coeffs = [0.2, -0.543]
ops = [qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.Hadamard(2)]
H = qml.Hamiltonian(coeffs, ops)

matrix = 0
for coeff, op in zip(H.coeffs, H.ops):
    matrix += coeff * op.matrix

```

where the variable `matrix` gives the array

```auto
 array([[-0.38395898, -0.38395898, 0.2 , 0.],
       [-0.38395898, 0.38395898, 0. , -0.2],
       [0.2 , 0. , 0.38395898, 0.38395898],
       [0. , -0.2 , 0.38395898, -0.38395898]])

```

Let us know if you have any more questions!

---

<div class="post-metadata">

**Author:** ![josh](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/josh/32/100_2.png) [@josh](https://discuss.pennylane.ai/u/josh)\
**Post date:** [August 29, 2021, 1:36pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/3 "2021-08-29T13:36:02Z")

</div>

I’m a bit late to the party, but wanted to point out that in addition to @anthayes92 excellent answer above, we also have a utility in PennyLane to convert Hamiltonian’s to sparse matrices:

```auto
>>> coeffs = [0.2, -0.543]
>>> ops = [
... qml.PauliX(0) @ qml.PauliZ(1),
... qml.PauliZ(0) @ qml.Hadamard(1)
... ]
>>> H = qml.Hamiltonian(coeffs, ops)
>>> Hmat = qml.utils.sparse_hamiltonian(H).real
>>> Hmat
<4x4 sparse matrix of type '<class 'numpy.float64'>'
        with 12 stored elements in COOrdinate format>

```

You can directly manipulate this sparse matrix using `scipy.sparse`, or you can convert it to a NumPy array:

```auto
>>> Hmat.toarray()
array([[-0.38395898, -0.38395898, 0.2 , 0.],
       [-0.38395898, 0.38395898, 0. , -0.2],
       [0.2 , 0. , 0.38395898, 0.38395898],
       [0. , -0.2 , 0.38395898, -0.38395898]])

```

---

<div class="post-metadata">

**Author:** ![Javier](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/javier/32/324_2.png) [@Javier](https://discuss.pennylane.ai/u/Javier)\
**Post date:** [August 30, 2021, 7:29am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/4 "2021-08-30T07:29:55Z")

</div>

Hi,

thank you very much for your answers! They are both super useful and exactly what I was looking for!

Cheers,  
Javier.

---

<div class="post-metadata">

**Author:** ![josh](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/josh/32/100_2.png) [@josh](https://discuss.pennylane.ai/u/josh)\
**Post date:** [August 30, 2021, 10:24am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/5 "2021-08-30T10:24:37Z")

</div>

No worries, glad they helped @Javier!

---

<div class="post-metadata">

**Author:** ![eigentejas](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/eigentejas/32/1445_2.png) [@eigentejas](https://discuss.pennylane.ai/u/eigentejas)\
**Post date:** [January 29, 2023, 7:36am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/6 "2023-01-29T07:36:43Z")

</div>

Hi,  
I think this doesn’t really work - if you chance the wires for the Paulis in the ops, the final Hamiltonian in numpy representation does not change! It seems like the whole method doesn’t care about what wires the gates are acting on, which means the final numpy representation is almost always wrong!

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [February 1, 2023, 12:12am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/7 "2023-02-01T00:12:53Z")

</div>

Hi @eigentejas, welcome to the Forum!

Please notice that this thread was from about 1.5 years ago and PennyLane has evolved a lot since then! 😀 Would you like to describe the problem you’re having? I might be able to help you. Please if possible also post:

- Your code so that I can try to replicate your issue
- The output of qml.about()
- Your full error traceback

I look forward to hearing back from you!

---

<div class="post-metadata">

**Author:** ![Lucas\_Tecot](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/lucas_tecot/32/1815_2.png) [@Lucas\_Tecot](https://discuss.pennylane.ai/u/Lucas_Tecot)\
**Post date:** [January 25, 2024, 3:36am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/8 "2024-01-25T03:36:19Z")

</div>

Along these lines, is compute\_matrix() in qml.Hamiltonian supported? I tried to use this to get the matrix and I got a pennylane.operation.MatrixUndefinedError. Because none of the options presented here seem to still work, at least for me.

---

<div class="post-metadata">

**Author:** ![isaacdevlugt](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/isaacdevlugt/32/1159_2.png) [@isaacdevlugt](https://discuss.pennylane.ai/u/isaacdevlugt)\
**Post date:** [January 26, 2024, 11:44pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/9 "2024-01-26T23:44:36Z")

</div>

Hey @Lucas_Tecot,

Indeed it’s not supported at the moment, but there is a way around this by looking at the `terms()` attribute that a Hamiltonian has in PEnnyLane:

```auto
>>> import pennylane as qml
>>> H = 3*qml.PauliY(0) + 0.5 * qml.PauliZ(0)
>>> H
<Hamiltonian: terms=2, wires=[0]>
>>> H.terms()
([3.0, 0.5], [PauliY(wires=[0]), PauliZ(wires=[0])])
>>> coeffs, ops = H.terms()[0], H.terms()[1]
>>> coeffs, ops
([3.0, 0.5], [PauliY(wires=[0]), PauliZ(wires=[0])])
>>> mat = [coeffs[i] * ops[i].compute_matrix() for i in range(len(coeffs))]
>>> mat
[array([[0.+0.j, 0.-3.j],
       [0.+3.j, 0.+0.j]]), array([[0.5, 0.],
       [0. , -0.5]])]
>>> from pennylane import numpy as np
>>> mat = np.dot(mat[0], mat[1])
>>> mat
tensor([[0.+0.j , 0.+1.5j],
        [0.+1.5j, 0.+0.j]], requires_grad=True)
>>>

```

Let me know if that helps!

---

<div class="post-metadata">

**Author:** ![Lucas\_Tecot](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/lucas_tecot/32/1815_2.png) [@Lucas\_Tecot](https://discuss.pennylane.ai/u/Lucas_Tecot)\
**Post date:** [January 27, 2024, 12:34am UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/10 "2024-01-27T00:34:15Z")

</div>

I actually had a friend recommend I just use qml.matrix(H), which I think works? Should that function work when inputing a Hamiltonian?

---

<div class="post-metadata">

**Author:** ![isaacdevlugt](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/isaacdevlugt/32/1159_2.png) [@isaacdevlugt](https://discuss.pennylane.ai/u/isaacdevlugt)\
**Post date:** [January 29, 2024, 3:41pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/11 "2024-01-29T15:41:55Z")

</div>

Oh! Yeah that does work 😅…

```auto
>>> qml.matrix(H)
array([[0.5+0.j, 0. -3.j],
       [0. +3.j, -0.5+0.j]])

```

Use that then! 😁

---

<div class="post-metadata">

**Author:** ![jeet\_sharma](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/jeet_sharma/32/2420_2.png) [@jeet\_sharma](https://discuss.pennylane.ai/u/jeet_sharma)\
**Post date:** [March 18, 2024, 1:13pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/12 "2024-03-18T13:13:32Z")

</div>

```
matrix += coeff * op.matrix
          ~~~~~~^~~~~~~~~~~

```

TypeError: unsupported operand type(s) for \*: ‘float’ and ‘method’

---

<div class="post-metadata">

**Author:** ![isaacdevlugt](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/isaacdevlugt/32/1159_2.png) [@isaacdevlugt](https://discuss.pennylane.ai/u/isaacdevlugt)\
**Post date:** [March 20, 2024, 2:00pm UTC](https://discuss.pennylane.ai/t/from-qml-hamiltonian-to-numpy-representation/1320/13 "2024-03-20T14:00:13Z")

</div>

Hey @jeet_sharma,

As the error suggests, `matrix` is a method, so you need to add parentheses after to call it.

```auto
matrix += coeff * op.matrix()

```

That should do it 🙂
