qml.transforms.hamiltonian_expand

hamiltonian_expand(tape)[source]

Returns a list of tapes, and a classical processing function, for computing the expectation value of a Hamiltonian.

Parameters

tape (QuantumTape) – of the Hamiltonian.

Returns

Returns a tuple containing a list of quantum tapes to be evaluated, and a function to be applied to these tape executions to compute the expectation value.

Return type

tuple[list[QuantumTape], function]

Example

Given a Hamiltonian,

H = qml.PauliY(2) @ qml.PauliZ(1) + 0.5 * qml.PauliZ(2) + qml.PauliZ(1)

and a tape of the form,

with qml.tape.QuantumTape() as tape:
    qml.Hadamard(wires=0)
    qml.CNOT(wires=[0, 1])
    qml.PauliX(wires=2)

    qml.expval(H)

We can use the hamiltonian_expand transform to generate new tapes and a classical post-processing function for computing the expectation value of the Hamiltonian.

>>> tapes, fn = qml.transforms.hamiltonian_expand(tape)

We can evaluate these tapes on a device:

>>> dev = qml.device("default.qubit", wires=3)
>>> res = dev.batch_execute(tapes)

Applying the processing function results in the expectation value of the Hamiltonian:

>>> fn(res)
-0.5

Warning

Note that defining Hamiltonians inside of QNodes using arithmetic can lead to errors. See Hamiltonian for more information.