cost_layer(gamma, hamiltonian)[source]

Applies the QAOA cost layer corresponding to a cost Hamiltonian.

For the cost Hamiltonian \(H_C\), this is defined as the following unitary:

\[U_C \ = \ e^{-i \gamma H_C}\]

where \(\gamma\) is a variational parameter.

  • gamma (int or float) – The variational parameter passed into the cost layer

  • hamiltonian (Hamiltonian) – The cost Hamiltonian


ValueError – if the terms of the supplied cost Hamiltonian are not exclusively products of diagonal Pauli gates

We first define a cost Hamiltonian:

from pennylane import qaoa
import pennylane as qml

cost_h = qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliZ(0) @ qml.PauliZ(1)])

We can then pass it into qaoa.cost_layer, within a quantum circuit:

dev = qml.device('default.qubit', wires=2)

def circuit(gamma):

    for i in range(2):

    cost_layer(gamma, cost_h)

    return [qml.expval(qml.PauliZ(wires=i)) for i in range(2)]

which gives us a circuit of the form:

>>> circuit(0.5)
>>> print(circuit.draw())
0: ──H──RZ(1)──╭RZ(1)──┤ ⟨Z⟩
1: ──H─────────╰RZ(1)──┤ ⟨Z⟩