Skip to content

Commit

Permalink
qml.matrix accept single-wire operator class with no wire_order (#5359)
Browse files Browse the repository at this point in the history
**Context:**
An error is raised when the user calls
`qml.matrix(qml.Hadamard)(wires=[0])` for not providing `wire_order`.

**Description of the Change:**
`qml.matrix` will not raise an error if the callable is an Operator
class with `num_wires=1`

**Benefits:**
Fixes test case failure in lightning.

**Related GitHub Issues:**
#5328
  • Loading branch information
astralcai authored Mar 12, 2024
1 parent d5379ee commit 9d54b1c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pennylane/ops/functions/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 10 additions & 0 deletions tests/ops/functions/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down

0 comments on commit 9d54b1c

Please sign in to comment.