qp.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 aPauliSentenceinstance. Else, results are always returned asOperatorinstances.
- Returns:
The commutator
- Return type:
~Operator or ~PauliSentence
Examples
You can compute commutators between operators in PennyLane.
>>> qp.commutator(qp.X(0), qp.Y(0)) 2j * Z(0)
>>> op1 = qp.X(0) @ qp.X(1) >>> op2 = qp.Y(0) @ qp.Y(1) >>> qp.commutator(op1, op2) 0 * I()
We can return a
PauliSentenceinstance by settingpauli=True.>>> op1 = qp.X(0) @ qp.X(1) >>> op2 = qp.Y(0) + qp.Y(1) >>> res = qp.commutator(op1, op2, pauli=True) >>> res 2j * Z(0) @ X(1) + 2j * X(0) @ Z(1) >>> isinstance(res, PauliSentence) True
We can also input
PauliWordandPauliSentenceinstances.>>> op1 = PauliWord({0:"X", 1:"X"}) >>> op2 = PauliWord({0:"Y"}) + PauliWord({1:"Y"}) >>> res = qp.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,qp.commutatorreturns Operators.>>> res = qp.commutator(op1, op2, pauli=False) >>> res 2j * (Z(0) @ X(1)) + 2j * (X(0) @ Z(1)) >>> isinstance(res, qp.operation.Operator) True
It is worth noting that computing commutators with Paulis is typically faster. Internally,
qp.commutatoruses theop.pauli_repwhenever that is available for both operators.Usage Details
The input and result of
qp.commutatoris not recorded in a tape context (and inside aQNode).with qp.tape.QuantumTape() as tape: a = qp.X(0) # gets recorded b = PauliWord({0:"Y"}) # does not get recorded comm = qp.commutator(a, b) # does not get recorded
In this example, we obtain
tape.operations = [qp.X(0)]. When desired, we can still record the result of the commutator by usingapply(), i.e.qp.apply(comm)inside the recording context.A peculiarity worth repeating is how in a recording context every created operator is recorded.
with qp.tape.QuantumTape() as tape: comm = qp.commutator(qp.X(0), qp.Y(0))
In this example, both
PauliXandPauliYget recorded because they were created inside the recording context. To avoid this, create the input toqp.commutatoroutside the recording context / qnode or insert an extrastop_recording()context (seeQueuingManager).