diff --git a/doc/releases/changelog-dev.md b/doc/releases/changelog-dev.md index 7c259a4d363..2a70356a3ca 100644 --- a/doc/releases/changelog-dev.md +++ b/doc/releases/changelog-dev.md @@ -122,9 +122,11 @@ * `qml.matrix()` called on the following will raise an error if `wire_order` is not specified: * tapes with more than one wire. * quantum functions. + * Operator class where ``num_wires`` does not equal to 1 * QNodes if the device does not have wires specified. * PauliWords and PauliSentences with more than one wire. [(#5328)](https://github.com/PennyLaneAI/pennylane/pull/5328) + [(#5359)](https://github.com/PennyLaneAI/pennylane/pull/5359) * ``qml.pauli.pauli_mult`` and ``qml.pauli.pauli_mult_with_phase`` are now removed. Instead, you should use ``qml.simplify(qml.prod(pauli_1, pauli_2))`` to get the reduced operator. [(#5324)](https://github.com/PennyLaneAI/pennylane/pull/5324) diff --git a/pennylane/ops/functions/matrix.py b/pennylane/ops/functions/matrix.py index cd3681eb1ec..37cb1bc1df7 100644 --- a/pennylane/ops/functions/matrix.py +++ b/pennylane/ops/functions/matrix.py @@ -200,7 +200,7 @@ def circuit(): ) elif callable(op): - if wire_order is None: + if getattr(op, "num_wires", 0) != 1 and wire_order is None: raise ValueError("wire_order is required by qml.matrix() for quantum functions.") else: diff --git a/tests/ops/functions/test_matrix.py b/tests/ops/functions/test_matrix.py index 0462a3447f9..f84229d6b35 100644 --- a/tests/ops/functions/test_matrix.py +++ b/tests/ops/functions/test_matrix.py @@ -836,6 +836,16 @@ def circuit(): with pytest.raises(ValueError, match=r"wire_order is required"): _ = qml.matrix(circuit) + def test_op_class(self): + """Tests that an error is raised when calling qml.matrix without wire_order + on an operator class with multiple wires.""" + + with pytest.raises(ValueError, match=r"wire_order is required"): + _ = qml.matrix(qml.CNOT)(wires=[0, 1]) + + # No error should be raised if the operator class has only one wire. + _ = qml.matrix(qml.Hadamard)(wires=0) + def test_no_error_cases(self): """Test that an error is not raised when calling qml.matrix on an operator, a single-wire tape, or a QNode with a device that provides wires."""