qml.operation.Operator

class Operator(*params, wires=None, id=None)[source]

Bases: abc.ABC

Base class representing quantum operators.

Operators are uniquely defined by their name, the wires they act on, their (trainable) parameters, and their (non-trainable) hyperparameters. The trainable parameters can be tensors of any supported auto-differentiation framework.

An operator can define any of the following representations:

Each representation method comes with a static method prefixed by compute_, which takes the signature (*parameters, **hyperparameters) (for numerical representations that do not need to know about wire labels) or (*parameters, wires, **hyperparameters), where parameters, wires, and hyperparameters are the respective attributes of the operator class.

Parameters
  • *params (tuple[tensor_like]) – trainable parameters

  • wires (Iterable[Any] or Any) – Wire label(s) that the operator acts on. If not given, args[-1] is interpreted as wires.

  • id (str) – custom label given to an operator instance, can be useful for some applications where the instance has to be identified

Example

A custom operator can be created by inheriting from Operator or one of its subclasses.

The following is an example for a custom gate that inherits from the Operation subclass. It acts by potentially flipping a qubit and rotating another qubit. The custom operator defines a decomposition, which the devices can use (since it is unlikely that a device knows a native implementation for FlipAndRotate). It also defines an adjoint operator.

import pennylane as qml


class FlipAndRotate(qml.operation.Operation):

    # Define how many wires the operator acts on in total.
    # In our case this may be one or two, which is why we
    # use the AnyWires Enumeration to indicate a variable number.
    num_wires = qml.operation.AnyWires

    # This attribute tells PennyLane what differentiation method to use. Here
    # we request parameter-shift (or "analytic") differentiation.
    grad_method = "A"

    def __init__(self, angle, wire_rot, wire_flip=None, do_flip=False, id=None):

        # checking the inputs --------------

        if do_flip and wire_flip is None:
            raise ValueError("Expected a wire to flip; got None.")

        #------------------------------------

        # do_flip is not trainable but influences the action of the operator,
        # which is why we define it to be a hyperparameter
        self._hyperparameters = {
            "do_flip": do_flip
        }

        # we extract all wires that the operator acts on,
        # relying on the Wire class arithmetic
        all_wires = qml.wires.Wires(wire_rot) + qml.wires.Wires(wire_flip)

        # The parent class expects all trainable parameters to be fed as positional
        # arguments, and all wires acted on fed as a keyword argument.
        # The id keyword argument allows users to give their instance a custom name.
        super().__init__(angle, wires=all_wires, id=id)

    @property
    def num_params(self):
        # if it is known before creation, define the number of parameters to expect here,
        # which makes sure an error is raised if the wrong number was passed. The angle
        # parameter is the only trainable parameter of the operation
        return 1

    @property
    def ndim_params(self):
        # if it is known before creation, define the number of dimensions each parameter
        # is expected to have. This makes sure to raise an error if a wrongly-shaped
        # parameter was passed. The angle parameter is expected to be a scalar
        return (0,)

    @staticmethod
    def compute_decomposition(angle, wires, do_flip):  # pylint: disable=arguments-differ
        # Overwriting this method defines the decomposition of the new gate, as it is
        # called by Operator.decomposition().
        # The general signature of this function is (*parameters, wires, **hyperparameters).
        op_list = []
        if do_flip:
            op_list.append(qml.X(wires[1]))
        op_list.append(qml.RX(angle, wires=wires[0]))
        return op_list

    def adjoint(self):
        # the adjoint operator of this gate simply negates the angle
        return FlipAndRotate(-self.parameters[0], self.wires[0], self.wires[1], do_flip=self.hyperparameters["do_flip"])

We can use the operation as follows:

from pennylane import numpy as np

dev = qml.device("default.qubit", wires=["q1", "q2", "q3"])

@qml.qnode(dev)
def circuit(angle):
    FlipAndRotate(angle, wire_rot="q1", wire_flip="q1")
    return qml.expval(qml.Z("q1"))
>>> a = np.array(3.14)
>>> circuit(a)
tensor(-0.99999873, requires_grad=True)

PennyLane operations are automatically registered as Pytrees .

For most operators, this process will happen automatically without need for custom implementations.

Customization of this process must occur if:

  • The data and hyperparameters are insufficient to reproduce the original operation via its initialization

  • The hyperparameters contain a non-hashable component, such as a list or dictionary.

Some examples include arithmetic operators, like Adjoint or Sum, or templates that perform preprocessing during initialization.

See the Operator._flatten and Operator._unflatten methods for more information.

>>> op = qml.PauliRot(1.2, "XY", wires=(0,1))
>>> op._flatten()
((1.2,), (Wires([0, 1]), (('pauli_word', 'XY'),)))
>>> qml.PauliRot._unflatten(*op._flatten())
PauliRot(1.2, XY, wires=[0, 1])

Many quantum functions are executed repeatedly at different parameters, which can be done with parameter broadcasting. For usage details and examples see the QNode documentation.

In order to support parameter broadcasting with an operator class, the following steps are necessary:

  1. Define the class attribute ndim_params, a tuple that indicates the expected number of dimensions for each operator argument without broadcasting. For example, FlipAndRotate above has ndim_params = (0,) for a single scalar argument. An operator taking a matrix argument and a scalar would have ndim_params = (2, 0). Note that ndim_params does not require the size of the axes.

  2. Make the representations of the operator broadcasting-compatible. Typically, one or multiple of the methods compute_matrix, compute_eigvals and compute_decomposition are defined by an operator, and these need to work with the original input and output as well as with broadcasted inputs and outputs that have an additional, leading axis. See below for an example.

  3. Make sure that validation within the above representation methods and __init__—if it is overwritten by the operator class—allow for broadcasted inputs. For custom operators this usually is a minor step or not necessary at all.

  4. For proper registration, add the name of the operator to supports_broadcasting in the file pennylane/ops/qubit/attributes.py.

  5. Make sure that the operator’s _check_batching method is called in all places required. This is typically done automatically but needs to be assured. See further below for details.

Examples

Consider an operator with the same matrix as qml.RX. A basic variant of compute_matrix (which will not be compatible with all autodifferentiation frameworks or backpropagation) is

@staticmethod
def compute_matrix(theta):
    '''Broadcasting axis ends up in the wrong position.'''
    c = qml.math.cos(theta / 2)
    s = qml.math.sin(theta / 2)
    return qml.math.array([[c, -1j * s], [-1j * s, c]])

If we passed a broadcasted argument theta of shape (batch_size,) to this method, which would have one instead of zero dimensions, cos and sin would correctly be applied elementwise. We would also obtain the correct matrix with shape (2, 2, batch_size). However, the broadcasting axis needs to be the first axis by convention, so that we need to move the broadcasting axis–if it exists–to the front before returning the matrix:

@staticmethod
def compute_matrix(theta):
    '''Broadcasting axis ends up in the correct leading position.'''
    c = qml.math.cos(theta / 2)
    s = qml.math.sin(theta / 2)
    mat = qml.math.array([[c, -1j * s], [-1j * s, c]])
    # Check whether the input has a broadcasting axis
    if qml.math.ndim(theta)==1:
        # Move the broadcasting axis to the first position
        return qml.math.moveaxis(mat, 2, 0)
    return mat

Adapting compute_eigvals to broadcasting looks similar.

Usually no major changes are required for compute_decomposition, but we need to take care of the correct mapping of input arguments to the operators in the decomposition. As an example, consider the operator that represents a layer of RX rotations with individual angles for each rotation. Without broadcasting, it takes one onedimensional array, i.e. ndim_params=(1,). Its decomposition, which is a convenient way to support this custom operation on all devices that implement RX, might look like this:

@staticmethod
def compute_decomposition(theta, wires):
    '''Iterate over the first axis of theta.'''
    decomp_ops = [qml.RX(x, wires=w) for x, w in zip(theta, wires)]
    return decomp_ops

If theta is a broadcasted argument, its first axis is the broadcasting axis and we would like to iterate over the second axis within the for loop instead. This is easily achieved by adding a transposition of theta that switches the axes in this case. Conveniently this does not have any effect in the non-broadcasted case, so that we do not need to handle two cases separately.

@staticmethod
def compute_decomposition(theta, wires):
    '''Iterate over the last axis of theta, which is also the first axis
    or the second axis without and with broadcasting, respectively.'''
    decomp_ops = [qml.RX(x, wires=w) for x, w in zip(qml.math.T(theta), wires)]
    return decomp_ops

The ``_check_batching`` method

Each operator determines whether it is used with a batch of parameters within the _check_batching method, by comparing the shape of the input data to the expected shape. Therefore, it is necessary to call _check_batching on any new input parameters passed to the operator. By default, any class inheriting from Operator will do so the first time its batch_size property is accessed.

_check_batching modifies the following instance attributes:

  • _ndim_params: The number of dimensions of the parameters passed to _check_batching. For an Operator that does _not_ set the ndim_params attribute, _ndim_params is used as a surrogate, interpreting any parameters as “not broadcasted”. This attribute should be understood as temporary and likely should not be used in other contexts.

  • _batch_size: If the Operator is broadcasted: The batch size/size of the broadcasting axis. If it is not broadcasted: None. An Operator that does not support broadcasting will report to not be broadcasted independently of the input.

These two properties are defined lazily, and accessing the public version of either one of them (in other words, without the leading underscore) for the first time will trigger a call to _check_batching, which validates and sets these properties.

arithmetic_depth

Arithmetic depth of the operator.

batch_size

Batch size of the operator if it is used with broadcasted parameters.

has_adjoint

has_decomposition

has_diagonalizing_gates

has_generator

has_matrix

hash

Integer hash that uniquely represents the operator.

hyperparameters

Dictionary of non-trainable variables that this operation depends on.

id

Custom string to label a specific operator instance.

is_hermitian

This property determines if an operator is hermitian.

name

String for the name of the operator.

ndim_params

Number of dimensions per trainable parameter of the operator.

num_params

Number of trainable parameters that the operator depends on.

num_wires

Number of wires the operator acts on.

parameters

Trainable parameters that the operator depends on.

pauli_rep

A PauliSentence representation of the Operator, or None if it doesn’t have one.

wires

Wires that the operator acts on.

arithmetic_depth

Arithmetic depth of the operator.

batch_size

Batch size of the operator if it is used with broadcasted parameters.

The batch_size is determined based on ndim_params and the provided parameters for the operator. If (some of) the latter have an additional dimension, and this dimension has the same size for all parameters, its size is the batch size of the operator. If no parameter has an additional dimension, the batch size is None.

Returns

Size of the parameter broadcasting dimension if present, else None.

Return type

int or None

has_adjoint = False
has_decomposition = False
has_diagonalizing_gates = False
has_generator = False
has_matrix = False
hash

Integer hash that uniquely represents the operator.

Type

int

hyperparameters

Dictionary of non-trainable variables that this operation depends on.

Type

dict

id

Custom string to label a specific operator instance.

is_hermitian

This property determines if an operator is hermitian.

name

String for the name of the operator.

ndim_params

Number of dimensions per trainable parameter of the operator.

By default, this property returns the numbers of dimensions of the parameters used for the operator creation. If the parameter sizes for an operator subclass are fixed, this property can be overwritten to return the fixed value.

Returns

Number of dimensions for each trainable parameter.

Return type

tuple

num_params

Number of trainable parameters that the operator depends on.

By default, this property returns as many parameters as were used for the operator creation. If the number of parameters for an operator subclass is fixed, this property can be overwritten to return the fixed value.

Returns

number of parameters

Return type

int

num_wires: Union[int, pennylane.operation.WiresEnum] = -1

Number of wires the operator acts on.

parameters

Trainable parameters that the operator depends on.

pauli_rep

A PauliSentence representation of the Operator, or None if it doesn’t have one.

wires

Wires that the operator acts on.

Returns

wires

Return type

Wires

adjoint()

Create an operation that is the adjoint of this one.

compute_decomposition(*params[, wires])

Representation of the operator as a product of other operators (static method).

compute_diagonalizing_gates(*params, wires, …)

Sequence of gates that diagonalize the operator in the computational basis (static method).

compute_eigvals(*params, **hyperparams)

Eigenvalues of the operator in the computational basis (static method).

compute_matrix(*params, **hyperparams)

Representation of the operator as a canonical matrix in the computational basis (static method).

compute_sparse_matrix(*params, **hyperparams)

Representation of the operator as a sparse matrix in the computational basis (static method).

decomposition()

Representation of the operator as a product of other operators.

diagonalizing_gates()

Sequence of gates that diagonalize the operator in the computational basis.

eigvals()

Eigenvalues of the operator in the computational basis.

expand()

Returns a tape that contains the decomposition of the operator.

generator()

Generator of an operator that is in single-parameter-form.

label([decimals, base_label, cache])

A customizable string representation of the operator.

map_wires(wire_map)

Returns a copy of the current operator with its wires changed according to the given wire map.

matrix([wire_order])

Representation of the operator as a matrix in the computational basis.

pow(z)

A list of new operators equal to this one raised to the given power.

queue([context])

Append the operator to the Operator queue.

simplify()

Reduce the depth of nested operators to the minimum.

sparse_matrix([wire_order])

Representation of the operator as a sparse matrix in the computational basis.

terms()

Representation of the operator as a linear combination of other operators.

adjoint()[source]

Create an operation that is the adjoint of this one.

Adjointed operations are the conjugated and transposed version of the original operation. Adjointed ops are equivalent to the inverted operation for unitary gates.

Returns

The adjointed operation.

static compute_decomposition(*params, wires=None, **hyperparameters)[source]

Representation of the operator as a product of other operators (static method).

\[O = O_1 O_2 \dots O_n.\]

Note

Operations making up the decomposition should be queued within the compute_decomposition method.

See also

decomposition().

Parameters
  • *params (list) – trainable parameters of the operator, as stored in the parameters attribute

  • wires (Iterable[Any], Wires) – wires that the operator acts on

  • **hyperparams (dict) – non-trainable hyperparameters of the operator, as stored in the hyperparameters attribute

Returns

decomposition of the operator

Return type

list[Operator]

static compute_diagonalizing_gates(*params, wires, **hyperparams)[source]

Sequence of gates that diagonalize the operator in the computational basis (static method).

Given the eigendecomposition \(O = U \Sigma U^{\dagger}\) where \(\Sigma\) is a diagonal matrix containing the eigenvalues, the sequence of diagonalizing gates implements the unitary \(U^{\dagger}\).

The diagonalizing gates rotate the state into the eigenbasis of the operator.

Parameters
  • params (list) – trainable parameters of the operator, as stored in the parameters attribute

  • wires (Iterable[Any], Wires) – wires that the operator acts on

  • hyperparams (dict) – non-trainable hyperparameters of the operator, as stored in the hyperparameters attribute

Returns

list of diagonalizing gates

Return type

list[Operator]

static compute_eigvals(*params, **hyperparams)[source]

Eigenvalues of the operator in the computational basis (static method).

If diagonalizing_gates are specified and implement a unitary \(U^{\dagger}\), the operator can be reconstructed as

\[O = U \Sigma U^{\dagger},\]

where \(\Sigma\) is the diagonal matrix containing the eigenvalues.

Otherwise, no particular order for the eigenvalues is guaranteed.

Parameters
  • *params (list) – trainable parameters of the operator, as stored in the parameters attribute

  • **hyperparams (dict) – non-trainable hyperparameters of the operator, as stored in the hyperparameters attribute

Returns

eigenvalues

Return type

tensor_like

static compute_matrix(*params, **hyperparams)[source]

Representation of the operator as a canonical matrix in the computational basis (static method).

The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order.

Parameters
  • *params (list) – trainable parameters of the operator, as stored in the parameters attribute

  • **hyperparams (dict) – non-trainable hyperparameters of the operator, as stored in the hyperparameters attribute

Returns

matrix representation

Return type

tensor_like

static compute_sparse_matrix(*params, **hyperparams)[source]

Representation of the operator as a sparse matrix in the computational basis (static method).

The canonical matrix is the textbook matrix representation that does not consider wires. Implicitly, this assumes that the wires of the operator correspond to the global wire order.

See also

sparse_matrix()

Parameters
  • *params (list) – trainable parameters of the operator, as stored in the parameters attribute

  • **hyperparams (dict) – non-trainable hyperparameters of the operator, as stored in the hyperparameters attribute

Returns

sparse matrix representation

Return type

scipy.sparse._csr.csr_matrix

decomposition()[source]

Representation of the operator as a product of other operators.

\[O = O_1 O_2 \dots O_n\]

A DecompositionUndefinedError is raised if no representation by decomposition is defined.

Returns

decomposition of the operator

Return type

list[Operator]

diagonalizing_gates()[source]

Sequence of gates that diagonalize the operator in the computational basis.

Given the eigendecomposition \(O = U \Sigma U^{\dagger}\) where \(\Sigma\) is a diagonal matrix containing the eigenvalues, the sequence of diagonalizing gates implements the unitary \(U^{\dagger}\).

The diagonalizing gates rotate the state into the eigenbasis of the operator.

A DiagGatesUndefinedError is raised if no representation by decomposition is defined.

Returns

a list of operators

Return type

list[Operator] or None

eigvals()[source]

Eigenvalues of the operator in the computational basis.

If diagonalizing_gates are specified and implement a unitary \(U^{\dagger}\), the operator can be reconstructed as

\[O = U \Sigma U^{\dagger},\]

where \(\Sigma\) is the diagonal matrix containing the eigenvalues.

Otherwise, no particular order for the eigenvalues is guaranteed.

Note

When eigenvalues are not explicitly defined, they are computed automatically from the matrix representation. Currently, this computation is not differentiable.

A EigvalsUndefinedError is raised if the eigenvalues have not been defined and cannot be inferred from the matrix representation.

Returns

eigenvalues

Return type

tensor_like

expand()[source]

Returns a tape that contains the decomposition of the operator.

Warning

This function is deprecated and will be removed in version 0.39. The same behaviour can be achieved simply through ‘qml.tape.QuantumScript(self.decomposition())’.

Returns

quantum tape

Return type

QuantumTape

generator()[source]

Generator of an operator that is in single-parameter-form.

For example, for operator

\[U(\phi) = e^{i\phi (0.5 Y + Z\otimes X)}\]

we get the generator

>>> U.generator()
  0.5 * Y(0) + Z(0) @ X(1)

The generator may also be provided in the form of a dense or sparse Hamiltonian (using Hermitian and SparseHamiltonian respectively).

The default value to return is None, indicating that the operation has no defined generator.

label(decimals=None, base_label=None, cache=None)[source]

A customizable string representation of the operator.

Parameters
  • decimals=None (int) – If None, no parameters are included. Else, specifies how to round the parameters.

  • base_label=None (str) – overwrite the non-parameter component of the label

  • cache=None (dict) – dictionary that carries information between label calls in the same drawing

Returns

label to use in drawings

Return type

str

Example:

>>> op = qml.RX(1.23456, wires=0)
>>> op.label()
"RX"
>>> op.label(base_label="my_label")
"my_label"
>>> op = qml.RX(1.23456, wires=0, id="test_data")
>>> op.label()
"RX("test_data")"
>>> op.label(decimals=2)
"RX\n(1.23,"test_data")"
>>> op.label(base_label="my_label")
"my_label("test_data")"
>>> op.label(decimals=2, base_label="my_label")
"my_label\n(1.23,"test_data")"

If the operation has a matrix-valued parameter and a cache dictionary is provided, unique matrices will be cached in the 'matrices' key list. The label will contain the index of the matrix in the 'matrices' list.

>>> op2 = qml.QubitUnitary(np.eye(2), wires=0)
>>> cache = {'matrices': []}
>>> op2.label(cache=cache)
'U(M0)'
>>> cache['matrices']
[tensor([[1., 0.],
 [0., 1.]], requires_grad=True)]
>>> op3 = qml.QubitUnitary(np.eye(4), wires=(0,1))
>>> op3.label(cache=cache)
'U(M1)'
>>> cache['matrices']
[tensor([[1., 0.],
        [0., 1.]], requires_grad=True),
tensor([[1., 0., 0., 0.],
        [0., 1., 0., 0.],
        [0., 0., 1., 0.],
        [0., 0., 0., 1.]], requires_grad=True)]
map_wires(wire_map)[source]

Returns a copy of the current operator with its wires changed according to the given wire map.

Parameters

wire_map (dict) – dictionary containing the old wires as keys and the new wires as values

Returns

new operator

Return type

Operator

matrix(wire_order=None)[source]

Representation of the operator as a matrix in the computational basis.

If wire_order is provided, the numerical representation considers the position of the operator’s wires in the global wire order. Otherwise, the wire order defaults to the operator’s wires.

If the matrix depends on trainable parameters, the result will be cast in the same autodifferentiation framework as the parameters.

A MatrixUndefinedError is raised if the matrix representation has not been defined.

See also

compute_matrix()

Parameters

wire_order (Iterable) – global wire order, must contain all wire labels from the operator’s wires

Returns

matrix representation

Return type

tensor_like

pow(z)[source]

A list of new operators equal to this one raised to the given power.

Parameters

z (float) – exponent for the operator

Returns

list[Operator]

queue(context=<class 'pennylane.queuing.QueuingManager'>)[source]

Append the operator to the Operator queue.

simplify()[source]

Reduce the depth of nested operators to the minimum.

Returns

simplified operator

Return type

Operator

sparse_matrix(wire_order=None)[source]

Representation of the operator as a sparse matrix in the computational basis.

If wire_order is provided, the numerical representation considers the position of the operator’s wires in the global wire order. Otherwise, the wire order defaults to the operator’s wires.

A SparseMatrixUndefinedError is raised if the sparse matrix representation has not been defined.

Parameters

wire_order (Iterable) – global wire order, must contain all wire labels from the operator’s wires

Returns

sparse matrix representation

Return type

scipy.sparse._csr.csr_matrix

terms()[source]

Representation of the operator as a linear combination of other operators.

\[O = \sum_i c_i O_i\]

A TermsUndefinedError is raised if no representation by terms is defined.

Returns

list of coefficients \(c_i\) and list of operations \(O_i\)

Return type

tuple[list[tensor_like or float], list[Operation]]