qml.utils.sparse_hamiltonian

sparse_hamiltonian(H)[source]

Computes the sparse matrix representation a Hamiltonian in the computational basis.

Parameters

H (Hamiltonian) – Hamiltonian operator for which the matrix representation should be computed

Returns

a sparse matrix in scipy coordinate list (COO) format with dimension \((2^n, 2^n)\), where \(n\) is the number of wires

Return type

coo_matrix

Example:

This function can be used by passing a qml.Hamiltonian object as:

>>> coeffs = [1, -0.45]
>>> obs = [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliY(0) @ qml.PauliZ(1)]
>>> H = qml.Hamiltonian(coeffs, obs)
>>> H_sparse = sparse_hamiltonian(H)
>>> H_sparse
<4x4 sparse matrix of type '<class 'numpy.complex128'>'
    with 2 stored elements in COOrdinate format>

The resulting sparse matrix can be either used directly or transformed into a numpy array:

>>> H_sparse.toarray()
array([[ 1.+0.j  ,  0.+0.j  ,  0.+0.45j,  0.+0.j  ],
       [ 0.+0.j  , -1.+0.j  ,  0.+0.j  ,  0.-0.45j],
       [ 0.-0.45j,  0.+0.j  , -1.+0.j  ,  0.+0.j  ],
       [ 0.+0.j  ,  0.+0.45j,  0.+0.j  ,  1.+0.j  ]])