Repository: PennyLaneAI/pennylane
Pull request #3888 (2023-03-10 19:19:32)

`SparseHamiltonian` uses `AnyWires
Updated `SparseHamiltonian` to use `AnyWires` instead of `AllWires`.

mudit2812: [sc-34240]
codecov[bot]: ## [Codecov](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3888?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
> Merging [#3888](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3888?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (b83209a) into [master](https://codecov.io/gh/PennyLaneAI/pennylane/commit/2dde0ed367c216ff8a41dbb3b86b5e63582f5ac5?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (2dde0ed) will **not change** coverage.
> The diff coverage is `100.00%`.

```diff
@@           Coverage Diff           @@
##           master    #3888   +/-   ##
=======================================
  Coverage   99.71%   99.71%           
=======================================
  Files         341      341           
  Lines       29698    29698           
=======================================
  Hits        29612    29612           
  Misses         86       86           
```


| [Impacted Files](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3888?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) | Coverage Δ | |
|---|---|---|
| [pennylane/ops/qubit/observables.py](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3888?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#diff-cGVubnlsYW5lL29wcy9xdWJpdC9vYnNlcnZhYmxlcy5weQ==) | `100.00% <100.00%> (ø)` | |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI)


Patch:
diff --git a/doc/releases/changelog-dev.md b/doc/releases/changelog-dev.md
index 4a04092bf..801a0ad16 100644
--- a/doc/releases/changelog-dev.md
+++ b/doc/releases/changelog-dev.md
@@ -57,6 +57,10 @@
   to be set as trainable), and therefore the derivatives are computed more efficiently.
   [(#3697)](https://github.com/PennyLaneAI/pennylane/pull/3697)
 
+* `qml.SparseHamiltonian` can now be applied to any wires in a circuit rather than being restricted to all wires
+  in the circuit.
+  [(#3888)](https://github.com/PennyLaneAI/pennylane/pull/3888)
+
 * Added `max_distance` keyword argument to `qml.pulse.rydberg_interaction` to allow removal of negligible contributions
   from atoms beyond `max_distance`from each other.
   [(#3889)](https://github.com/PennyLaneAI/pennylane/pull/3889)
diff --git a/pennylane/ops/qubit/observables.py b/pennylane/ops/qubit/observables.py
index 03537767f..819bf14a4 100644
--- a/pennylane/ops/qubit/observables.py
+++ b/pennylane/ops/qubit/observables.py
@@ -23,7 +23,7 @@ import numpy as np
 from scipy.sparse import csr_matrix
 
 import pennylane as qml
-from pennylane.operation import AllWires, AnyWires, Observable
+from pennylane.operation import AnyWires, Observable
 from pennylane.wires import Wires
 
 from .matrix_ops import QubitUnitary
@@ -209,13 +209,9 @@ class SparseHamiltonian(Observable):
         ``SparseHamiltonian`` observables can only be used to return expectation values.
         Variances and samples are not supported.
 
-    .. note::
-
-        Note that the ``SparseHamiltonian`` observable should not be used with a subset of wires.
-
     **Details:**
 
-    * Number of wires: All
+    * Number of wires: Any
     * Number of parameters: 1
     * Gradient recipe: None
 
@@ -242,7 +238,7 @@ class SparseHamiltonian(Observable):
     >>> Hmat = H.sparse_matrix()
     >>> H_sparse = qml.SparseHamiltonian(Hmat, wires)
     """
-    num_wires = AllWires
+    num_wires = AnyWires
     num_params = 1
     """int: Number of trainable parameters that the operator depends on."""
 


Test patch:
diff --git a/tests/ops/qubit/test_sparse.py b/tests/ops/qubit/test_sparse.py
index da13e17b9..93cf75456 100644
--- a/tests/ops/qubit/test_sparse.py
+++ b/tests/ops/qubit/test_sparse.py
@@ -138,6 +138,28 @@ class TestSparse:
 
         assert np.allclose(qml.grad(circuit, argnum=0)(0.0), expected_output, atol=tol, rtol=0)
 
+    def test_sparse_no_all_wires_error(self, tol):
+        """Tests that SparseHamiltonian can be used as expected when the operator wires don't cover
+        all device wires."""
+        dev = qml.device("default.qubit", wires=6, shots=None)
+
+        hamiltonian = qml.SparseHamiltonian(csr_matrix(H_hydrogen), wires=range(4))
+
+        @qml.qnode(dev, diff_method="parameter-shift")
+        def circuit():
+            qml.PauliX(0)
+            qml.PauliX(1)
+            qml.PauliZ(1)
+            return qml.expval(hamiltonian)
+
+        expected_state = np.zeros((64, 1))
+        expected_state[48, 0] = -1
+
+        expected = (
+            expected_state.conj().T @ qml.matrix(hamiltonian, wire_order=range(6)) @ expected_state
+        )
+        assert np.allclose(circuit(), expected, atol=tol, rtol=0)
+
     @pytest.mark.parametrize(
         "qubits, operations, hamiltonian, expected_output",
         [