qml.SpecialUnitary

class SpecialUnitary(theta, wires, id=None)[source]

Bases: pennylane.operation.Operation

Gate from the group \(SU(N)\) with \(N=2^n\) for \(n\) qubits.

We use the following parametrization of a special unitary operator:

\[\begin{split}U(\bm{\theta}) &= \exp\{A(\bm{\theta})\}\\ A(\bm{\theta}) &= \sum_{m=1}^d i \theta_m P_m\\ P_m &\in \{I, X, Y, Z\}^{\otimes n} \setminus \{I^{\otimes n}\}\end{split}\]

This means, \(U(\bm{\theta})\) is the exponential of the operator \(A(\bm{\theta})\), which in turn is a linear combination of Pauli words with coefficients \(i\bm{\theta}\) and satisfies \(A(\bm{\theta})^\dagger=-A(\bm{\theta})\) (it is skew-Hermitian). Note that this gate takes an exponential number \(d=4^n-1\) of parameters. See below for more theoretical background and details regarding differentiability.

Details:

  • Number of wires: Any

  • Number of parameters: 1

  • Number of dimensions per parameter: (1,)

  • Gradient recipe:

\[\begin{split}\frac{\partial}{\partial\theta_\ell} f(U(\bm{\theta})) &= \sum_{m=1}^d 2i\omega_{\ell m} \frac{\mathrm{d}}{\mathrm{d} t} f\left(\exp\left\{-i\frac{t}{2}G_m\right\} U(\bm{\theta})\right)\\ &= \sum_{m=1}^d i\omega_{\ell m} \left[ f\left(\exp\left\{-i\frac{\pi}{4}G_m\right\} U(\bm{\theta})\right) -f\left(\exp\left\{i\frac{\pi}{4}G_m\right\} U(\bm{\theta})\right) \right]\end{split}\]

where \(f\) is an expectation value depending on \(U(\bm{\theta})\) and the derivative of the Pauli rotation gates \(\exp\left\{-i\frac{t}{2}G_m\right\}\) follows from the two-term parameter-shift rule (also see: PauliRot). For details on the gradient recipe, also consider the theoretical background section below.

Parameters
  • theta (tensor_like) – Pauli coordinates of the exponent \(A(\bm{\theta})\). See details below for the order of the Pauli words.

  • wires (Sequence[int] or int) – The wire(s) the operation acts on

  • id (str or None) – String representing the operation (optional)

Raises

ValueError – If the shape of the input does not match the Lie algebra dimension \(d=4^n-1\) for \(n\) wires.

Note

This operation should only be used to parametrize special unitaries that can not easily be represented by other operations, as it incurs computational cost that scale exponentially with the wires it acts on.

The parameter theta refers to all Pauli words (except for the identity) in lexicographical order, which looks like the following for one and two qubits:

>>> qml.ops.qubit.special_unitary.pauli_basis_strings(1) # 4**1-1 = 3 Pauli words
['X', 'Y', 'Z']
>>> qml.ops.qubit.special_unitary.pauli_basis_strings(2) # 4**2-1 = 15 Pauli words
['IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ']

See also

For more details on using this operator in applications, see the SU(N) gate demo.

Warning

This operation only is differentiable when using the JAX, Torch or TensorFlow interfaces, even when using hardware-compatible differentiation techniques like the parameter-shift rule.

Warning

This operation supports broadcasting and hardware-compatible differentiation techniques like the parameter-shift rule. However, the two features can not be used simultaneously.

Examples

Simple examples of this operation are single-qubit Pauli rotation gates, which can be created by setting all but one parameter \(\theta_m\) to zero:

>>> x = 0.412
>>> theta = x * np.array([1, 0, 0]) # The first entry belongs to the Pauli word "X"
>>> su = qml.SpecialUnitary(theta, wires=0)
>>> prot = qml.PauliRot(-2 * x, "X", wires=0) # PauliRot introduces a prefactor -0.5
>>> rx = qml.RX(-2 * x, 0) # RX introduces a prefactor -0.5
>>> qml.math.allclose(su.matrix(), prot.matrix())
True
>>> qml.math.allclose(su.matrix(), rx.matrix())
True

Note that for specific operations like the RX rotation gate above, it is strongly recommended to use the specialized implementation qml.RX rather than PauliRot or SpecialUnitary. However, SpecialUnitary gates go beyond such rotations: Multiple Pauli words can be activated simultaneously, giving access to more complex operations. For two qubits, this could look like this:

>>> wires = [0, 1]
# Activating the Pauli words ["IY", "IZ", "XX", "XY", "YY", "YZ", "ZY", "ZZ"]
>>> theta = 0.3 * np.array([0, 1, 2, 0, -1, 1, 0, 0, 0, 1, 1, 1, 0, 0, -1])
>>> len(theta) == 4 ** len(wires) - 1 # theta contains one parameter per Pauli word
True
>>> su = qml.SpecialUnitary(theta, wires=wires)
>>> su.matrix()
array([[ 0.56397118+0.52139241j,  0.30652227+0.02438052j,
         0.13555302+0.22630716j,  0.0689876 -0.49110826j],
       [-0.15454843+0.00998377j,  0.88294943+0.01496327j,
        -0.25396275-0.10785888j, -0.26041566+0.22857073j],
       [-0.2876174 -0.2443733j ,  0.25423439+0.05896445j,
         0.71621665+0.50686226j,  0.1380692 +0.02252197j],
       [-0.34495668-0.35307844j,  0.10817019-0.21404059j,
        -0.29040522+0.00830631j,  0.15015337-0.76933485j]])

The SpecialUnitary operation also can be differentiated with hardware-compatible differentiation techniques if the JAX, Torch or TensorFlow interface is used. See the theoretical background section below for details.

We consider special unitaries parametrized in the following way:

\[\begin{split}U(\bm{\theta}) &= \exp\{A(\bm{\theta})\}\\ A(\bm{\theta}) &= \sum_{m=1}^d i \theta_m G_m\\ G_m &\in \mathcal{P^{(n)}}=\{I, X, Y, Z\}^{\otimes n} \setminus \{I^{\otimes n}\}\end{split}\]

where \(n\) is the number of qubits and \(\theta_m\) are \(d=4^n-1\) real-valued parameters. This parametrization allows us to express any special unitary for the given number of qubits.

Note that this differs from a sequence of all possible Pauli rotation gates because for non-commuting Pauli words \(G_1, G_2\) we have \(\exp\{i\theta_1G_1\}\exp\{i\theta_2G_2\}\neq \exp\{i(\theta_1G_1+\theta_2G_2)\}\).

Differentiation

The partial derivatives of \(U(\bm{\theta})\) above can be expressed as

\[\begin{split}\frac{\partial}{\partial \theta_\ell} U(\bm{\theta}) &= U(\bm{\theta}) \frac{\mathrm{d}}{\mathrm{d}t}\exp\left(t\Omega_\ell(\bm{\theta})\right)\large|_{t=0}\\ &=U(\bm{\theta})\Omega_\ell(\bm{\theta})\end{split}\]

where \(\Omega_\ell(\bm{\theta})\) is the effective generator belonging to the partial derivative \(\partial_\ell U(\bm{\theta})\) at the parameters \(\bm{\theta}\). It can be computed via

\[\Omega_\ell(\bm{\theta}) = U(\bm{\theta})^\dagger \left(\frac{\partial}{\partial \theta_\ell}\mathfrak{Re}[U(\bm{\theta})] +i\frac{\partial}{\partial \theta_\ell}\mathfrak{Im}[U(\bm{\theta})]\right)\]

where we may compute the derivatives of the real and imaginary parts of \(U(\bm{\theta})\) using auto-differentiation.

Each effective generator \(\Omega_\ell(\bm{\theta})\) that reproduces a partial derivative can be decomposed in the Pauli basis of \(\mathfrak{su}(N)\) via

\[\Omega_\ell(\bm{\theta}) = \sum_{m=1}^d \omega_{\ell m}(\bm{\theta}) G_m.\]

As the Pauli words are orthonormal with respect to the trace, or Frobenius, inner product (rescaled by \(2^{-n}\)), we can compute the coefficients using this inner product (\(G_m\) is Hermitian, so we skip the adjoint \({}^\dagger\)):

\[\omega_{\ell m}(\bm{\theta}) = \frac{1}{2^n}\operatorname{tr} \left\{G_m \Omega_\ell(\bm{\theta}) \right\}\]

The coefficients satisfy \(\omega_{\ell m}^\ast=-\omega_{\ell m}\) because \(\Omega_\ell(\bm{\theta})\) is skew-Hermitian. Therefore they are purely imaginary.

Now we turn to the derivative of an expectation value-based function which uses a circuit with a SpecialUnitary operation. Absorbing the remaining circuit into the quantum state \(\rho\) and the observable \(H\), this can be written as

\[\begin{split}f(U(\bm{\theta})) &= \operatorname{Tr}\left\{H U(\bm{\theta})\rho U^\dagger(\bm{\theta})\right\}\\ \partial_\ell f(U(\bm{\theta})) &= \operatorname{Tr}\left\{H U(\bm{\theta}) [\Omega_\ell(\bm{\theta}),\rho] U^\dagger(\bm{\theta})\right\}\end{split}\]

Inserting the decomposition for the effective generator from above, we may rewrite this as a combination of derivatives of Pauli rotation gates:

\[\begin{split}\partial_\ell f(U(\bm{\theta})) &= \operatorname{Tr}\left\{H U(\bm{\theta}) \left[\sum_{m=1}^d \omega_{\ell m}(\bm{\theta}) G_m,\rho\right] U^\dagger(\bm{\theta})\right\}\\ &= \sum_{m=1}^d 2i\omega_{\ell m}(\bm{\theta}) \frac{\mathrm{d}}{\mathrm{d}t}f\left(R_{G_m}(t)U(\bm{\theta})\right)\bigg|_{t=0}.\end{split}\]

Here we abbreviated a Pauli rotation gate as \(R_{G_m}(t) = \exp\{-i\frac{t}{2} G_m\}\). As all partial derivatives are combinations of these Pauli rotation derivatives, we may write the gradient of \(f\) as

\[\nabla f(U(\bm{\theta})) = \overline{\omega}(\bm{\theta}) \cdot \bm{\mathrm{d}f}\]

where we defined the matrix \(\overline{\omega_{\ell m}}=2i\omega_{\ell m}\) and the vector of Pauli rotation derivatives \(\mathrm{d}f_m=\frac{\mathrm{d}}{\mathrm{d}t} f\left(R_{G_m}(t)U(\bm{\theta})\right)\bigg|_{t=0}\). These derivatives can be computed with the standard parameter-shift rule because Pauli words satisfy the condition \(G_m^2=1\) (see e.g. Mitarai et al. (2018)). Provided that we can implement the SpecialUnitary gate itself, this allows us to compute \(\bm{\mathrm{d}f}\) in a hardware-compatible manner using \(2d\) quantum circuits.

Note that for SpecialUnitary we frequently handle objects that have one or multiple dimensions of exponentially large size \(d=4^n-1\), and that the number of quantum circuits for the differentiation scales accordingly. This strongly affects the number of qubits to which we can apply a SpecialUnitary gate in practice.

arithmetic_depth

Arithmetic depth of the operator.

basis

The basis of an operation, or for controlled gates, of the target operation.

batch_size

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

control_wires

Control wires of the operator.

grad_method

Gradient computation method.

grad_recipe

Gradient recipe for the parameter-shift method.

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 that the operator depends on.

num_params

Number of trainable parameters that the operator depends on.

num_wires

Number of wires that the operator acts on.

parameter_frequencies

Returns the frequencies for each operator parameter with respect to an expectation value of the form \(\langle \psi | U(\mathbf{p})^\dagger \hat{O} U(\mathbf{p})|\psi\rangle\).

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.

basis

The basis of an operation, or for controlled gates, of the target operation. If not None, should take a value of "X", "Y", or "Z".

For example, X and CNOT have basis = "X", whereas ControlledPhaseShift and RZ have basis = "Z".

Type

str or None

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

control_wires

Control wires of the operator.

For operations that are not controlled, this is an empty Wires object of length 0.

Returns

The control wires of the operation.

Return type

Wires

grad_method = None

Gradient computation method.

grad_recipe = None

Gradient recipe for the parameter-shift method.

This is a tuple with one nested list per operation parameter. For parameter \(\phi_k\), the nested list contains elements of the form \([c_i, a_i, s_i]\) where \(i\) is the index of the term, resulting in a gradient recipe of

\[\frac{\partial}{\partial\phi_k}f = \sum_{i} c_i f(a_i \phi_k + s_i).\]

If None, the default gradient recipe containing the two terms \([c_0, a_0, s_0]=[1/2, 1, \pi/2]\) and \([c_1, a_1, s_1]=[-1/2, 1, -\pi/2]\) is assumed for every parameter.

Type

tuple(Union(list[list[float]], None)) or None

has_adjoint = True
has_decomposition = True
has_diagonalizing_gates = False
has_generator = False
has_matrix = True
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 = (1,)

Number of dimensions per trainable parameter that the operator depends on.

Type

tuple[int]

num_params = 1

Number of trainable parameters that the operator depends on.

Type

int

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

Number of wires that the operator acts on.

Type

int

parameter_frequencies

Returns the frequencies for each operator parameter with respect to an expectation value of the form \(\langle \psi | U(\mathbf{p})^\dagger \hat{O} U(\mathbf{p})|\psi\rangle\).

These frequencies encode the behaviour of the operator \(U(\mathbf{p})\) on the value of the expectation value as the parameters are modified. For more details, please see the pennylane.fourier module.

Returns

Tuple of frequencies for each parameter. Note that only non-negative frequency values are returned.

Return type

list[tuple[int or float]]

Example

>>> op = qml.CRot(0.4, 0.1, 0.3, wires=[0, 1])
>>> op.parameter_frequencies
[(0.5, 1), (0.5, 1), (0.5, 1)]

For operators that define a generator, the parameter frequencies are directly related to the eigenvalues of the generator:

>>> op = qml.ControlledPhaseShift(0.1, wires=[0, 1])
>>> op.parameter_frequencies
[(1,)]
>>> gen = qml.generator(op, format="observable")
>>> gen_eigvals = qml.eigvals(gen)
>>> qml.gradients.eigvals_to_frequencies(tuple(gen_eigvals))
(1.0,)

For more details on this relationship, see eigvals_to_frequencies().

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(theta, num_wires)

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.

get_one_parameter_coeffs(interface)

Compute the Pauli basis coefficients of the generators of one-parameter groups that reproduce the partial derivatives of a special unitary gate.

get_one_parameter_generators([interface])

Compute the generators of one-parameter groups that reproduce the partial derivatives of a special unitary gate.

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.

single_qubit_rot_angles()

The parameters required to implement a single-qubit gate as an equivalent Rot gate, up to a global phase.

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)

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)

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)

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(theta, num_wires)[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.

See also

matrix()

Parameters
  • theta (tensor_like) – Pauli coordinates of the exponent \(A(\theta)\).

  • num_wires (int) – The number of wires the matrix acts on.

Returns

canonical matrix of the special unitary corresponding to theta. It

has the shape (2**num_wires, 2**num_wires).

Return type

tensor_like

Compute the matrix of an element in SU(N), given by the Pauli basis coordinated of the associated Lie algebra element. The \(4^n-1\) Pauli basis elements of the Lie algebra \(\mathfrak{su}(N)\) for \(n\) qubits are \(P_m\in\{I, X, Y, Z\}^{\otimes n}\setminus\{I^{\otimes n}\}\), and the special unitary matrix is computed as

\[U(\theta) = \exp(i\sum_{m=1}^d \theta_m P_m)\]

See the main class documentation above for the ordering of Pauli words.

Note

Note that this method internally handles a complex-valued tensor of size (4**num_wires, 2**num_wires, 2**num_wires), which requires at least 4 ** (2 * num_wires - 13) GB of memory (at default precision).

Example

>>> theta = np.array([0.5, 0.1, -0.3])
>>> qml.SpecialUnitary.compute_matrix(theta, num_wires=1)
array([[ 0.83004499-0.28280371j,  0.0942679 +0.47133952j],
       [-0.0942679 +0.47133952j,  0.83004499+0.28280371j]])
static compute_sparse_matrix(*params, **hyperparams)

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\]

This Operation is decomposed into the corresponding QubitUnitary.

Returns

decomposition of the operator

Return type

list[Operator]

Example:

>>> theta = np.array([0.5, 0.1, -0.3])
>>> qml.SpecialUnitary(theta, wires=[0]).decomposition()
[QubitUnitary(array([[ 0.83004499-0.28280371j,  0.0942679 +0.47133952j],
    [-0.0942679 +0.47133952j,  0.83004499+0.28280371j]]), wires=[0])]
diagonalizing_gates()

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

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

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

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.

get_one_parameter_coeffs(interface)[source]

Compute the Pauli basis coefficients of the generators of one-parameter groups that reproduce the partial derivatives of a special unitary gate.

Parameters

interface (str) – The auto-differentiation framework to be used for the computation.

Returns

The Pauli basis coefficients of the effective generators that reproduce the partial derivatives of the special unitary gate defined by theta. There are \(d=4^n-1\) generators for \(n\) qubits and \(d\) Pauli coefficients per generator, so that the output shape is (4**num_wires-1, 4**num_wires-1).

Return type

tensor_like

Given a generator \(\Omega\) of a one-parameter group that reproduces a partial derivative of a special unitary gate, it can be decomposed in the Pauli basis of \(\mathfrak{su}(N)\) via

\[\Omega = \sum_{m=1}^d \omega_m P_m\]

where \(d=4^n-1\) is the size of the basis for \(n\) qubits and \(P_m\) are the Pauli words making up the basis. As the Pauli words are orthonormal with respect to the trace or Frobenius inner product (rescaled by \(2^n\)), we can compute the coefficients using this inner product (\(P_m\) is Hermitian, so we skip the adjoint \({}^\dagger\)):

\[\omega_m = \frac{1}{2^n}\operatorname{tr}\left[P_m \Omega \right]\]

The coefficients satisfy \(\omega_m^\ast=-\omega_m\) because \(\Omega\) is skew-Hermitian. Therefore they are purely imaginary.

Warning

An auto-differentiation framework is required by this function. The matrix exponential is not differentiable in Autograd. Therefore this function only supports JAX, Torch and Tensorflow.

get_one_parameter_generators(interface=None)[source]

Compute the generators of one-parameter groups that reproduce the partial derivatives of a special unitary gate.

Parameters

interface (str) – The auto-differentiation framework to be used for the computation. Has to be one of ["jax", "tensorflow", "tf", "torch"].

Raises
  • NotImplementedError – If the chosen interface is "autograd". Autograd does not support differentiation of linalg.expm.

  • ValueError – If the chosen interface is not supported.

Returns

The generators for one-parameter groups that reproduce the partial derivatives of the special unitary gate. There are \(d=4^n-1\) generators for \(n\) qubits, so that the output shape is (4**num_wires-1, 2**num_wires, 2**num_wires).

Return type

tensor_like

Consider a special unitary gate parametrized in the following way:

\[\begin{split}U(\theta) &= \exp\{A(\theta)\}\\ A(\theta) &= \sum_{m=1}^d i \theta_m P_m\\ P_m &\in \{I, X, Y, Z\}^{\otimes n} \setminus \{I^{\otimes n}\}\end{split}\]

Then the partial derivatives of the gate can be shown to be given by

\[\frac{\partial}{\partial \theta_\ell} U(\theta) = U(\theta) \frac{\mathrm{d}}{\mathrm{d}t}\exp\left(t\Omega_\ell(\theta)\right)\large|_{t=0}\]

where \(\Omega_\ell(\theta)\) is the one-parameter generator belonging to the partial derivative \(\partial_\ell U(\theta)\) at the parameters \(\theta\). It can be computed via

\[\Omega_\ell(\theta) = U(\theta)^\dagger \left(\frac{\partial}{\partial \theta_\ell}\mathfrak{Re}[U(\theta)] +i\frac{\partial}{\partial \theta_\ell}\mathfrak{Im}[U(\theta)]\right)\]

where we may compute the derivatives \(\frac{\partial}{\partial \theta_\ell} U(\theta)\) using auto-differentiation.

Warning

An auto-differentiation framework is required for this function. The matrix exponential is not differentiable in Autograd. Therefore this function only supports JAX, Torch and TensorFlow.

label(decimals=None, base_label=None, cache=None)

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)

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)

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)

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

Append the operator to the Operator queue.

simplify()

Reduce the depth of nested operators to the minimum.

Returns

simplified operator

Return type

Operator

single_qubit_rot_angles()

The parameters required to implement a single-qubit gate as an equivalent Rot gate, up to a global phase.

Returns

A list of values \([\phi, \theta, \omega]\) such that \(RZ(\omega) RY(\theta) RZ(\phi)\) is equivalent to the original operation.

Return type

tuple[float, float, float]

sparse_matrix(wire_order=None)

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

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]]

Contents

Using PennyLane

Release news

Development

API

Internals