qml.commutator¶
-
commutator
(op1, op2, pauli=False)[source]¶ Compute commutator between two operators in PennyLane
\[[O_1, O_2] = O_1 O_2 - O_2 O_1\]- Parameters
op1 (Union[Operator, PauliWord, PauliSentence]) – First operator
op2 (Union[Operator, PauliWord, PauliSentence]) – Second operator
pauli (bool) – When
True
, all results are passed as aPauliSentence
instance. Else, results are always returned asOperator
instances.
- Returns
The commutator
- Return type
Examples
You can compute commutators between operators in PennyLane.
>>> qml.commutator(X(0), Y(0)) 2j * Z(0)
>>> op1 = X(0) @ X(1) >>> op2 = Y(0) @ Y(1) >>> qml.commutator(op1, op2) 0 * I()
We can return a
PauliSentence
instance by settingpauli=True
.>>> op1 = X(0) @ X(1) >>> op2 = Y(0) + Y(1) >>> res = qml.commutator(op1, op2, pauli=True) >>> res 2j * X(1) @ Z(0) + 2j * Z(1) @ X(0) >>> isinstance(res, PauliSentence) True
We can also input
PauliWord
andPauliSentence
instances.>>> op1 = PauliWord({0:"X", 1:"X"}) >>> op2 = PauliWord({0:"Y"}) + PauliWord({1:"Y"}) >>> res = qml.commutator(op1, op2, pauli=True) >>> res 2j * Z(0) @ X(1) + 2j * X(0) @ Z(1) >>> isinstance(res, PauliSentence) True
Note that when
pauli=False
, even if Pauli operators are used as inputs,qml.commutator
returns Operators.>>> res = qml.commutator(op1, op2, pauli=False) >>> res 2j * (Z(0) @ X(1)) + 2j * (X(0) @ Z(1)) >>> isinstance(res, qml.operation.Operator) True
It is worth noting that computing commutators with Paulis is typically faster. Internally,
qml.commutator
uses theop.pauli_rep
whenever that is available for both operators.Usage Details
The input and result of
qml.commutator
is not recorded in a tape context (and inside aQNode
).with qml.tape.QuantumTape() as tape: a = qml.X(0) # gets recorded b = PauliWord({0:"Y"}) # does not get recorded comm = qml.commutator(a, b) # does not get recorded
In this example, we obtain
tape.operations = [qml.X(0)]
. When desired, we can still record the result of the commutator by usingapply()
, i.e.qml.apply(comm)
inside the recording context.A peculiarity worth repeating is how in a recording context every created operator is recorded.
with qml.tape.QuantumTape() as tape: comm = qml.commutator(qml.X(0), qml.Y(0))
In this example, both
PauliX
andPauliY
get recorded because they were created inside the recording context. To avoid this, create the input toqml.commutator
outside the recording context / qnode or insert an extrastop_recording()
context (seeQueuingManager
).