qml.operation.Tensor

class Tensor(*args)[source]

Bases: pennylane.operation.Observable

Container class representing tensor products of observables.

To create a tensor, simply initiate it like so:

>>> T = Tensor(qml.PauliX(0), qml.Hermitian(A, [1, 2]))

You can also create a tensor from other Tensors:

>>> T = Tensor(T, qml.PauliZ(4))

The @ symbol can be used as a tensor product operation:

>>> T = qml.PauliX(0) @ qml.Hadamard(2)

batch_size

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

data

Raw parameters of all constituent observables in the tensor product.

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

All observables must be hermitian

name

All constituent observable names making up the tensor product.

ndim_params

Number of dimensions per trainable parameter of the operator.

non_identity_obs

Returns the non-identity observables contained in the tensor product.

num_params

Raw parameters of all constituent observables in the tensor product.

num_wires

Number of wires the tensor product acts on.

parameters

Evaluated parameter values of all constituent observables in the tensor product.

return_type

Measurement type that this observable is called with.

tensor

wires

All wires in the system the tensor product acts on.

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

data

parameters of the operator

Type

list[Any]

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

All observables must be hermitian

name

All constituent observable names making up the tensor product.

Returns

list containing all observable names

Return type

list[str]

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

non_identity_obs

Returns the non-identity observables contained in the tensor product.

Returns

list containing the non-identity observables in the tensor product

Return type

list[Observable]

num_params

Raw parameters of all constituent observables in the tensor product.

Returns

flattened list containing all dependent parameters

Return type

list[Any]

num_wires

Number of wires the tensor product acts on.

Returns

number of wires

Return type

int

parameters

Evaluated parameter values of all constituent observables in the tensor product.

Returns

nested list containing the parameters per observable in the tensor product

Return type

list[list[Any]]

return_type = None

Measurement type that this observable is called with.

Type

None or ObservableReturnTypes

tensor = True
wires

All wires in the system the tensor product acts on.

Returns

wires addressed by the observables in the tensor product

Return type

Wires

adjoint()

Create an operation that is the adjoint of this one.

check_wires_partial_overlap()

Tests whether any two observables in the Tensor have partially overlapping wires and raise a warning if they do.

compare(other)

Compares with another Hamiltonian, Tensor, or Observable, to determine if they are equivalent.

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

compute_terms(*params, **hyperparams)

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

decomposition()

Representation of the operator as a product of other operators.

diagonalizing_gates()

Return the gate set that diagonalizes a circuit according to the specified tensor observable.

eigvals()

Return the eigenvalues of the specified tensor product observable.

expand()

Returns a tape that has recorded the decomposition of the operator.

generator()

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

label([decimals, base_label, cache])

How the operator is represented in diagrams and drawings.

matrix([wire_order])

Matrix representation of the Tensor operator in the computational basis.

pow(z)

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

prune()

Returns a pruned tensor product of observables by removing Identity instances from the observables building up the Tensor.

queue([context, init])

Append the operator to the Operator queue.

sparse_matrix([wires, format])

Computes, by default, a scipy.sparse.csr_matrix representation of this Tensor.

terms()

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

adjoint()

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.

Parameters

do_queue – Whether to add the adjointed gate to the context queue.

Returns

The adjointed operation.

check_wires_partial_overlap()[source]

Tests whether any two observables in the Tensor have partially overlapping wires and raise a warning if they do.

Note

Fully overlapping wires, i.e., observables with same (sets of) wires are not reported, as the matrix method is well-defined and implemented for this scenario.

compare(other)

Compares with another Hamiltonian, Tensor, or Observable, to determine if they are equivalent.

Observables/Hamiltonians are equivalent if they represent the same operator (their matrix representations are equal), and they are defined on the same wires.

Warning

The compare method does not check if the matrix representation of a Hermitian observable is equal to an equivalent observable expressed in terms of Pauli matrices. To do so would require the matrix form of Hamiltonians and Tensors be calculated, which would drastically increase runtime.

Returns

True if equivalent.

Return type

(bool)

Examples

>>> ob1 = qml.PauliX(0) @ qml.Identity(1)
>>> ob2 = qml.Hamiltonian([1], [qml.PauliX(0)])
>>> ob1.compare(ob2)
True
>>> ob1 = qml.PauliX(0)
>>> ob2 = qml.Hermitian(np.array([[0, 1], [1, 0]]), 0)
>>> ob1.compare(ob2)
False
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\).

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\), 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.

See also

eigvals() and eigvals()

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)

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

matrix representation

Return type

tensor_like

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

static compute_terms(*params, **hyperparams)

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

\[O = \sum_i c_i O_i\]

See also

terms()

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

list of coefficients and list of operations

Return type

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

decomposition()

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]

Return the gate set that diagonalizes a circuit according to the specified tensor observable.

This method uses pre-stored eigenvalues for standard observables where possible and stores the corresponding eigenvectors from the eigendecomposition.

Returns

list containing the gates diagonalizing the tensor observable

Return type

list

eigvals()[source]

Return the eigenvalues of the specified tensor product observable.

This method uses pre-stored eigenvalues for standard observables where possible.

Returns

array containing the eigenvalues of the tensor product observable

Return type

array[float]

expand()

Returns a tape that has recorded the decomposition of the operator.

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) [Y0]
+ (1.0) [Z0 X1]

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]

How the operator is represented in diagrams and drawings.

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

  • base_label=None (Iterable[str]) – overwrite the non-parameter component of the label. Must be same length as obs attribute.

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

Returns

label to use in drawings

Return type

str

>>> T = qml.PauliX(0) @ qml.Hadamard(2)
>>> T.label()
'X@H'
>>> T.label(base_label=["X0", "H2"])
'X0@H2'
matrix(wire_order=None)[source]

Matrix representation of the Tensor operator in the computational basis.

Note

The wire_order argument is added for compatibility, but currently not implemented. The Tensor class is planned to be removed soon.

Parameters

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

Returns

matrix representation

Return type

array

Example

>>> O = qml.PauliZ(0) @ qml.PauliZ(2)
>>> O.matrix()
array([[ 1,  0,  0,  0],
       [ 0, -1,  0,  0],
       [ 0,  0, -1,  0],
       [ 0,  0,  0,  1]])

To get the full \(2^3\times 2^3\) Hermitian matrix acting on the 3-qubit system, the identity on wire 1 must be explicitly included:

>>> O = qml.PauliZ(0) @ qml.Identity(1) @ qml.PauliZ(2)
>>> O.matrix()
array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0., -1.,  0., -0.,  0., -0.,  0., -0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 0., -0.,  0., -1.,  0., -0.,  0., -0.],
       [ 0.,  0.,  0.,  0., -1., -0., -0., -0.],
       [ 0., -0.,  0., -0., -0.,  1., -0.,  0.],
       [ 0.,  0.,  0.,  0., -0., -0., -1., -0.],
       [ 0., -0.,  0., -0., -0.,  0., -0.,  1.]])
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]

prune()[source]

Returns a pruned tensor product of observables by removing Identity instances from the observables building up the Tensor.

The return_type attribute is preserved while pruning.

If the tensor product only contains one observable, then this observable instance is returned.

Note that, as a result, this method can return observables that are not a Tensor instance.

Example:

Pruning that returns a Tensor:

>>> O = qml.PauliZ(0) @ qml.Identity(1) @ qml.PauliZ(2)
>>> O.prune()
<pennylane.operation.Tensor at 0x7fc1642d1590
>>> [(o.name, o.wires) for o in O.prune().obs]
[('PauliZ', [0]), ('PauliZ', [2])]

Pruning that returns a single observable:

>>> O = qml.PauliZ(0) @ qml.Identity(1)
>>> O_pruned = O.prune()
>>> (O_pruned.name, O_pruned.wires)
('PauliZ', [0])
Returns

the pruned tensor product of observables

Return type

Observable

queue(context=<class 'pennylane.queuing.QueuingContext'>, init=False)[source]

Append the operator to the Operator queue.

sparse_matrix(wires=None, format='csr')[source]

Computes, by default, a scipy.sparse.csr_matrix representation of this Tensor.

This is useful for larger qubit numbers, where the dense matrix becomes very large, while consisting mostly of zero entries.

Parameters
  • wires (Iterable) – Wire labels that indicate the order of wires according to which the matrix is constructed. If not provided, self.wires is used.

  • format – the output format for the sparse representation. All scipy sparse formats are accepted.

Returns

sparse matrix representation

Return type

scipy.sparse._csr.csr_matrix

Example

Consider the following tensor:

>>> t = qml.PauliX(0) @ qml.PauliZ(1)

Without passing wires, the sparse representation is given by:

>>> print(t.sparse_matrix())
(0, 2)  1
(1, 3)  -1
(2, 0)  1
(3, 1)  -1

If we define a custom wire ordering, the matrix representation changes accordingly: >>> print(t.sparse_matrix(wires=[1, 0])) (0, 1) 1 (1, 0) 1 (2, 3) -1 (3, 2) -1

We can also enforce implicit identities by passing wire labels that are not present in the constituent operations:

>>> res = t.sparse_matrix(wires=[0, 1, 2])
>>> print(res.shape)
(8, 8)
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.

See also

compute_terms()

Returns

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

Return type

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