qml.apply

apply(func, qnode_collection)[source]

Apply a function to the constituent QNodes of a QNodeCollection.

Parameters
  • func (callable) – A function to be applied to the QNodeCollection results. This function must be supported by the corresponding QNodeCollection interface; i.e., a torch QNodeCollection can only be acted on functions that accept torch.tensor objects.

  • qnode_collection (QNodeCollection) – a QNode collection.

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")

As we are using the 'torch' interface, we now apply torch.sum to the QNodeCollection:

>>> cost = qml.apply(torch.sum, qnodes)

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

>>> x = qml.init.strong_ent_layers_normal(3, 2)
>>> cost(x)
tensor(0.9092, dtype=torch.float64, grad_fn=<SumBackward0>)