# The quantum node object¶

Module name: pennylane.qnode

The QNode class is used to construct quantum nodes, encapsulating a quantum function or variational circuit and the computational device it is executed on.

The computational device is an instance of the Device class, and can represent either a simulator or hardware device. They can be instantiated using the device() loader. PennyLane comes included with some basic devices; additional devices can be installed as plugins (see Plugins and ecosystem for more details).

## Quantum circuit functions¶

The quantum circuit function encapsulated by the QNode must be of the following form:

def my_quantum_function(x, y):
qml.RZ(x, wires=0)
qml.CNOT(wires=[0,1])
qml.RY(y, wires=1)
return qml.expval.PauliZ(0)


Quantum circuit functions are a restricted subset of Python functions, adhering to the following constraints:

• The body of the function must consist of only supported PennyLane operations, one per line.
• The function must always return either a single or a tuple of expectation values.
• Classical processing of function arguments, either by arithmetic operations or external functions, is not allowed. One current exception is simple scalar multiplication.

Note

The quantum operations cannot be used outside of a quantum circuit function, as all Operations require a QNode in order to perform queuing on initialization.

Note

Expectation values must come after all other operations at the end of the circuit function as part of the return statement, and cannot appear in the middle.

After the device and quantum circuit function are defined, a QNode object must be created which wraps this function and binds it to the device. Once created, the QNode can be used to evaluate the specified quantum circuit function on the particular device.

For example:

device = qml.device('default.qubit', wires=2)
qnode1 = qml.QNode(my_quantum_function, device)
result = qnode1(np.pi/4, 0.7)


Note

The qnode() decorator is provided as a convenience to automate the process of creating quantum nodes. The decorator is used as follows:

@qml.qnode(device)
def my_quantum_function(x, y):
qml.RZ(x, wires=0)
qml.CNOT(wires=[0,1])
qml.RY(y, wires=1)
return qml.expval.PauliZ(0)

result = my_quantum_function(np.pi/4, 0.7)


## Auxiliary functions¶

 _inv_dict(d) Reverse a dictionary mapping. _get_default_args(func) Get the default arguments of a function.

## QNode methods¶

 __call__(*args, **kwargs) Wrapper for evaluate(). evaluate(**kwargs) Evaluates the quantum function on the specified device. evaluate_obs(obs, args, **kwargs) Evaluate the expectation values of the given observables. jacobian(params[, which, method, h, order]) Compute the Jacobian of the QNode.

## QNode internal methods¶

 construct(args, **kwargs) Constructs a representation of the quantum circuit. _best_method(idx) Determine the correct gradient computation method for a free parameter. _append_op(op) Appends a quantum operation into the circuit queue. _op_successors(o_idx[, only]) Successors of the given operation in the quantum circuit. _pd_finite_diff(params, idx[, h, order, y0]) Partial derivative of the node using the finite difference method. _pd_analytic(params, idx[, force_order2]) Partial derivative of the node using the analytic method.

### Code details¶

exception QuantumFunctionError[source]

Exception raised when an illegal operation is defined in a quantum function.

__weakref__

list of weak references to the object (if defined)

_inv_dict(d)[source]

Reverse a dictionary mapping.

Returns multimap where the keys are the former values, and values are sets of the former keys.

Parameters: d (dict[a->b]) – mapping to reverse reversed mapping dict[b->set[a]]
_get_default_args(func)[source]

Get the default arguments of a function.

Parameters: func (function) – a valid Python function dictionary containing the argument name and tuple (positional idx, default value) dict
class QNode(func, device)[source]

Quantum node in the hybrid computational graph.

Parameters: func (callable) – a Python function containing Operation constructor calls, returning a tuple of Expectation instances. device (Device) – device to execute the function on
_current_context = None

QNode – for building Operation sequences by executing quantum circuit functions

__init__(func, device)[source]

Initialize self. See help(type(self)) for accurate signature.

variable_ops = None

dict[int->list[(int, int)]] – Mapping from free parameter index to the list of Operations (in this circuit) that depend on it.

The first element of the tuple is the index of the Operation in the program queue, the second the index of the parameter within the Operation.

__str__()[source]

String representation

__repr__()[source]

REPL representation

_append_op(op)[source]

Appends a quantum operation into the circuit queue.

Parameters: op (Operation) – quantum operation to be added to the circuit
construct(args, **kwargs)[source]

Constructs a representation of the quantum circuit.

The user should never have to call this method.

This method is called automatically the first time QNode.evaluate() or QNode.jacobian() is called. It executes the quantum function, stores the resulting sequence of Operation instances, and creates the variable mapping.

Parameters: args (tuple) – Represent the free parameters passed to the circuit. Here we are not concerned with their values, but with their structure. Each free param is replaced with a Variable instance.

Note

Additional keyword arguments may be passed to the quantum circuit function, however PennyLane does not support differentiating with respect to keyword arguments. Instead, keyword arguments are useful for providing data or ‘placeholders’ to the quantum circuit function.

_op_successors(o_idx, only='G')[source]

Successors of the given operation in the quantum circuit.

Parameters: o_idx (int) – index of the operation in the operation queue only (str) – the type of successors to return. 'G': only return non-Expectations (default) 'E': only return Expectations None: return all successors successors in a topological order list[Operation]
_best_method(idx)[source]

Determine the correct gradient computation method for a free parameter.

Use the analytic method iff every gate that depends on the parameter supports it. If not, use the finite difference method.

Note that If even one gate does not support differentiation, we cannot differentiate with respect to this parameter at all.

Parameters: idx (int) – free parameter index gradient method to be used str
__call__(*args, **kwargs)[source]

Wrapper for evaluate().

evaluate(**kwargs)

Evaluates the quantum function on the specified device.

Parameters: args (tuple) – input parameters to the quantum function output expectation value(s) float, array[float]
evaluate_obs(obs, args, **kwargs)[source]

Evaluate the expectation values of the given observables.

Assumes construct() has already been called.

Parameters: obs (Iterable[Expectation]) – observables to measure args (array[float]) – circuit input parameters expectation values array[float]
jacobian(params, which=None, *, method='B', h=1e-07, order=1, **kwargs)[source]

Compute the Jacobian of the QNode.

Returns the Jacobian of the parametrized quantum circuit encapsulated in the QNode.

The Jacobian can be computed using several methods:

• Finite differences ('F'). The first order method evaluates the circuit at $$n+1$$ points of the parameter space, the second order method at $$2n$$ points, where n = len(which).

• Analytic method ('A'). Works for all one-parameter gates where the generator only has two unique eigenvalues; this includes one-parameter qubit gates, as well as Gaussian circuits of order one or two. Additionally, can be used in CV systems for Gaussian circuits containing first- and second-order observables.

The circuit is evaluated twice for each incidence of each parameter in the circuit.

• Best known method for each parameter ('B'): uses the analytic method if possible, otherwise finite difference.

Note

The finite difference method is sensitive to statistical noise in the circuit output, since it compares the output at two points infinitesimally close to each other. Hence the ‘F’ method requires exact expectation values, i.e., shots=0.

Parameters: Keyword Arguments: params (nested Sequence[Number], Number) – point in parameter space at which to evaluate the gradient which (Sequence[int], None) – return the Jacobian with respect to these parameters. None (the default) means with respect to all parameters. Note that keyword arguments to the QNode are always treated as fixed values and not included in the Jacobian calculation. method (str) – Jacobian computation method, see above. h (float) – finite difference method step size order (int) – finite difference method order, 1 or 2 shots (int) – How many times the circuit should be evaluated (or sampled) to estimate the expectation values. For simulator backends, 0 yields the exact result. Jacobian matrix, with shape (n_out, len(which)), where len(which) is the number of free parameters, and n_out is the number of expectation values returned by the QNode. array[float]
_pd_finite_diff(params, idx, h=1e-07, order=1, y0=None, **kwargs)[source]

Partial derivative of the node using the finite difference method.

Parameters: params (array[float]) – point in parameter space at which to evaluate the partial derivative idx (int) – return the partial derivative with respect to this parameter h (float) – step size order (int) – finite difference method order, 1 or 2 y0 (float) – Value of the circuit at params. Should only be computed once. partial derivative of the node. float
_pd_analytic(params, idx, force_order2=False, **kwargs)[source]

Partial derivative of the node using the analytic method.

The 2nd order method can handle also first order observables, but 1st order method may be more efficient unless it’s really easy to experimentally measure arbitrary 2nd order observables.

Parameters: params (array[float]) – point in free parameter space at which to evaluate the partial derivative idx (int) – return the partial derivative with respect to this free parameter partial derivative of the node. float
to_torch()[source]

Convert the standard PennyLane QNode into a TorchQNode().

to_tfe()[source]

Convert the standard PennyLane QNode into a TFEQNode().

__weakref__

list of weak references to the object (if defined)

QNode_vjp(ans, self, args, **kwargs)[source]

Returns the vector Jacobian product operator for a QNode, as a function of the QNode evaluation for specific argnums at the specified parameter values.

This function is required for integration with Autograd.