qml.sum

sum(x)[source]

Lazily sum the constituent QNodes of a QNodeCollection.

Parameters

x (QNodeCollection) – a QNode collection of independent QNodes.

See also

apply(), dot()

Example:

We can create a QNodeCollection using map():

>>> dev = qml.device("default.qubit", wires=2)
>>> obs_list = [qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)]
>>> qnodes = qml.map(qml.templates.StronglyEntanglingLayers, obs_list, dev, interface="torch")

For the cost function, we now sum the results of all QNodes in the collection:

>>> cost = qml.sum(qnodes)

This is a lazy summation — no QNode evaluation has yet occured. Evaluation only occurs when the returned function cost is evaluated:

>>> np.random.seed(42)
>>> shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=3, n_wires=2)
>>> x = np.random.random(shape)
>>> cost(x)
tensor(0.9177, dtype=torch.float64)