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 Returns: reversed mapping Return type: dict[b>set[a]]

_get_default_args
(func)[source]¶ Get the default arguments of a function.
Parameters: func (function) – a valid Python function Returns: dictionary containing the argument name and tuple (positional idx, default value) Return type: 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 ofExpectation
instances.  device (
Device
) – device to execute the function on

_current_context
= None¶ for building Operation sequences by executing quantum circuit functions
Type: QNode

variable_ops
= None¶ 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.
Type: dict[int>list[(int, int)]]

_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()
orQNode.jacobian()
is called. It executes the quantum function, stores the resulting sequence ofOperation
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 nonExpectations (default)'E'
: only return ExpectationsNone
: return all successors
Returns: successors in a topological order
Return type: 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 Returns: gradient method to be used Return type: 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 Returns: output expectation value(s) Return type: 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
Returns: expectation values
Return type: array[float]

jacobian
(params, which=None, *, method='B', h=1e07, 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, wheren = len(which)
.Analytic method (
'A'
). Works for all oneparameter gates where the generator only has two unique eigenvalues; this includes oneparameter 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 secondorder 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:  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.
Keyword Arguments:  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.
Returns: Jacobian matrix, with shape
(n_out, len(which))
, wherelen(which)
is the number of free parameters, andn_out
is the number of expectation values returned by the QNode.Return type: array[float]

_pd_finite_diff
(params, idx, h=1e07, 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.
Returns: partial derivative of the node.
Return type: 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
Returns: partial derivative of the node.
Return type: 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)
 func (callable) – a Python function containing