class_docstr: Tests for sparse hamiltonian observable
class_docstr_tok: ["Tests","for","sparse","hamiltonian","observable"]
docstr: Tests that gradients are computed correctly for a SparseHamiltonian observable.
docstr_tok: ["Tests","that","gradients","are","computed","correctly","for","a","SparseHamiltonian","observable","."]
code: def test_sparse_gradient(
      self, qubits, hamiltonian, expected_output, tol
  ):
      """Tests that gradients are computed correctly for a SparseHamiltonian observable."""
      dev = qml.device("default.qubit", wires=qubits, shots=None)
  
      hamiltonian = csr_matrix(hamiltonian)
  
      @qml.qnode(dev, diff_method="parameter-shift")
      def circuit(param):
          qml.PauliX(0)
          qml.PauliX(1)
          qml.DoubleExcitation(param, wires=[0, 1, 2, 3])
          return qml.expval(
              qml.SparseHamiltonian(hamiltonian, wires=range(qubits))
          )
  
      assert np.allclose(
          qml.grad(circuit, argnum=0)(0.0),
          expected_output,
          atol=tol,
          rtol=0,
      )
  
file_path: pennylane/tests/ops/qubit/test_sparse.py
imports: import pytest
  import numpy
  from scipy.sparse import coo_matrix, csr_matrix
  import pennylane
label_desc: Use image node_id 7 for calling the TestSparse obj's underlying member method code with example usage: obj.test_sparse_gradient(qubits, hamiltonian, expected_output, tol) and returns: qml