qml.ops.op_math.LinearCombination¶
- class LinearCombination(coeffs, observables, grouping_type=None, method='lf', _grouping_indices=None, _pauli_rep=None, id=None)[source]¶
Bases:
pennylane.ops.op_math.sum.Sum
Operator representing a linear combination of operators.
The
LinearCombination
is represented as a linear combination of other operators, e.g., \(\sum_{k=0}^{N-1} c_k O_k\), where the \(c_k\) are trainable parameters.- Parameters
coeffs (tensor_like) – coefficients of the
LinearCombination
expressionobservables (Iterable[Observable]) – observables in the
LinearCombination
expression, of same length ascoeffs
grouping_type (str) – If not
None
, compute and store information on how to group commuting observables upon initialization. This information may be accessed when aQNode
containing thisLinearCombination
is executed on devices. The string refers to the type of binary relation between Pauli words. Can be'qwc'
(qubit-wise commuting),'commuting'
, or'anticommuting'
.method (str) – The graph colouring heuristic to use in solving minimum clique cover for grouping, which can be
'lf'
(Largest First),'rlf'
(Recursive Largest First),'dsatur'
(Degree of Saturation), or'gis'
(IndependentSet). Defaults to'lf'
. Ignored ifgrouping_type=None
.id (str) – name to be assigned to this
LinearCombination
instance
See also
rustworkx.ColoringStrategy for more information on the
('lf', 'dsatur', 'gis')
strategies.Example:
A
LinearCombination
can be created by simply passing the list of coefficients as well as the list of observables:>>> coeffs = [0.2, -0.543] >>> obs = [qml.X(0) @ qml.Z(1), qml.Z(0) @ qml.Hadamard(2)] >>> H = qml.ops.LinearCombination(coeffs, obs) >>> print(H) 0.2 * (X(0) @ Z(1)) + -0.543 * (Z(0) @ Hadamard(wires=[2]))
The coefficients can be a trainable tensor, for example:
>>> coeffs = tf.Variable([0.2, -0.543], dtype=tf.double) >>> obs = [qml.X(0) @ qml.Z(1), qml.Z(0) @ qml.Hadamard(2)] >>> H = qml.ops.LinearCombination(coeffs, obs) >>> print(H) 0.2 * (X(0) @ Z(1)) + -0.543 * (Z(0) @ Hadamard(wires=[2]))
A
LinearCombination
can store information on which commuting observables should be measured together in a circuit:>>> obs = [qml.X(0), qml.X(1), qml.Z(0)] >>> coeffs = np.array([1., 2., 3.]) >>> H = qml.ops.LinearCombination(coeffs, obs, grouping_type='qwc') >>> H.grouping_indices ((0, 1), (2,))
This attribute can be used to compute groups of coefficients and observables:
>>> grouped_coeffs = [coeffs[list(indices)] for indices in H.grouping_indices] >>> grouped_obs = [[H.ops[i] for i in indices] for indices in H.grouping_indices] >>> grouped_coeffs [array([1., 2.]), array([3.])] >>> grouped_obs [[X(0), X(1)], [Z(0)]]
Devices that evaluate a
LinearCombination
expectation by splitting it into its local observables can use this information to reduce the number of circuits evaluated.Note that one can compute the
grouping_indices
for an already initializedLinearCombination
by using thecompute_grouping
method.Attributes
Arithmetic depth of the operator.
Return the coefficients defining the LinearCombination.
Create data property
Return the eigendecomposition of the matrix specified by the operator.
Return the grouping indices attribute.
bool(x) -> bool
bool(x) -> bool
bool(x) -> bool
Boolean expression that indicates if the factors have overlapping wires.
bool(x) -> bool
Integer hash that uniquely represents the operator.
Dictionary of non-trainable variables that this operation depends on.
Custom string to label a specific operator instance.
If all of the terms in the sum are hermitian, then the Sum is hermitian.
String for the name of the operator.
Number of trainable parameters that the operator depends on.
Number of wires the operator acts on.
Return the operators defining the LinearCombination.
Groups all operands of the composite operator that act on overlapping wires.
Trainable parameters that the operator depends on.
A
PauliSentence
representation of the Operator, orNone
if it doesn't have one.The sorted union of wires from all operators.
- arithmetic_depth¶
- basis¶
- batch_size = None¶
- coeffs¶
Return the coefficients defining the LinearCombination.
- Returns
coefficients in the LinearCombination expression
- Return type
Iterable[float])
- data¶
Create data property
- eigendecomposition¶
Return the eigendecomposition of the matrix specified by the operator.
This method uses pre-stored eigenvalues for standard observables where possible and stores the corresponding eigenvectors from the eigendecomposition.
It transforms the input operator according to the wires specified.
- Returns
- dictionary containing the eigenvalues and the
eigenvectors of the operator.
- Return type
dict[str, array]
- grad_method = 'A'¶
- grouping_indices¶
Return the grouping indices attribute.
- Returns
indices needed to form groups of commuting observables
- Return type
list[list[int]]
- has_adjoint¶
- has_decomposition = False¶
- has_diagonalizing_gates¶
- has_generator = False¶
- has_matrix¶
- has_overlapping_wires¶
Boolean expression that indicates if the factors have overlapping wires.
- has_sparse_matrix¶
- hash¶
- hyperparameters¶
Dictionary of non-trainable variables that this operation depends on.
- Type
dict
- id¶
Custom string to label a specific operator instance.
- is_hermitian¶
If all of the terms in the sum are hermitian, then the Sum is hermitian.
- name¶
- ndim_params = None¶
- num_params¶
- num_wires = -1¶
Number of wires the operator acts on.
- ops¶
Return the operators defining the LinearCombination.
- Returns
observables in the LinearCombination expression
- Return type
Iterable[Observable])
- overlapping_ops¶
Groups all operands of the composite operator that act on overlapping wires.
- Returns
List of lists of operators that act on overlapping wires. All the inner lists commute with each other.
- Return type
List[List[Operator]]
- parameters¶
Trainable parameters that the operator depends on.
- pauli_rep¶
A
PauliSentence
representation of the Operator, orNone
if it doesn’t have one.
Methods
adjoint
()Create an operation that is the adjoint of this one.
compare
(other)Determines mathematical equivalence between operators
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_grouping
([grouping_type, method])Compute groups of operators and coefficients corresponding to commuting observables of this
LinearCombination
.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).
Representation of the operator as a product of other operators.
Sequence of gates that diagonalize the operator in the computational basis.
eigvals
()Return the eigenvalues of the specified operator.
Generator of an operator that is in single-parameter-form.
label
([decimals, base_label, cache])How the composite operator is represented in diagrams and drawings.
map_wires
(wire_map)Returns a copy of the current
LinearCombination
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])Queues a
qml.ops.LinearCombination
instancesimplify
([cutoff])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
()Retrieve the coefficients and operators of the
LinearCombination
.- 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.
- Returns
The adjointed operation.
- compare(other)[source]¶
Determines mathematical equivalence between operators
LinearCombination
and other operators are equivalent if they mathematically represent the same operator (their matrix representations are equal), acting on the same wires.Warning
This method does not compute explicit matrices but uses the underlyding operators and coefficients for comparisons. When both operators consist purely of Pauli operators, and therefore have a valid
op.pauli_rep
, the comparison is cheap. When that is not the case (e.g. one of the operators contains aHadamard
gate), it can be more expensive as it involves mathematical simplification of both operators.- Returns
True if equivalent.
- Return type
(bool)
Examples
>>> H = qml.ops.LinearCombination( ... [0.5, 0.5], ... [qml.PauliZ(0) @ qml.PauliY(1), qml.PauliY(1) @ qml.PauliZ(0) @ qml.Identity("a")] ... ) >>> obs = qml.PauliZ(0) @ qml.PauliY(1) >>> print(H.compare(obs)) True
>>> H1 = qml.ops.LinearCombination([1, 1], [qml.PauliX(0), qml.PauliZ(1)]) >>> H2 = qml.ops.LinearCombination([1, 1], [qml.PauliZ(0), qml.PauliX(1)]) >>> H1.compare(H2) False
>>> ob1 = qml.ops.LinearCombination([1], [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
- Parameters
*params (list) – trainable parameters of the operator, as stored in the
parameters
attributewires (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.
See also
- Parameters
params (list) – trainable parameters of the operator, as stored in the
parameters
attributewires (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.
See also
- 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
- compute_grouping(grouping_type='qwc', method='lf')[source]¶
Compute groups of operators and coefficients corresponding to commuting observables of this
LinearCombination
.Note
If grouping is requested, the computed groupings are stored as a list of list of indices in
LinearCombination.grouping_indices
.- Parameters
grouping_type (str) – The type of binary relation between Pauli words used to compute the grouping. Can be
'qwc'
,'commuting'
, or'anticommuting'
. Defaults to'qwc'
.method (str) – The graph colouring heuristic to use in solving minimum clique cover for grouping, which can be
'lf'
(Largest First) or'rlf'
(Recursive Largest First). Defaults to'lf'
.
Example
import pennylane as qml a = qml.X(0) b = qml.prod(qml.X(0), qml.X(1)) c = qml.Z(0) obs = [a, b, c] coeffs = [1.0, 2.0, 3.0] op = qml.ops.LinearCombination(coeffs, obs)
>>> op.grouping_indices is None True >>> op.compute_grouping(grouping_type="qwc") >>> op.grouping_indices ((2,), (0, 1))
- 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
- 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
- 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()¶
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.See also
- 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.See also
- Returns
a list of operators
- Return type
list[Operator] or None
- eigvals()[source]¶
Return the eigenvalues of the specified operator.
This method uses pre-stored eigenvalues for standard observables where possible and stores the corresponding eigenvectors from the eigendecomposition.
- Returns
array containing the eigenvalues of the operator
- Return type
array
- 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
Hamiltonian
andSparseHamiltonian
respectively).The default value to return is
None
, indicating that the operation has no defined generator.
- label(decimals=None, base_label=None, cache=None)¶
How the composite operator is represented in diagrams and drawings.
- Parameters
decimals (int) – If
None
, no parameters are included. Else, how to round the parameters. Defaults toNone
.base_label (Iterable[str]) – Overwrite the non-parameter component of the label. Must be same length as
operands
attribute. Defaults toNone
.cache (dict) – Dictionary that carries information between label calls in the same drawing. Defaults to
None
.
- Returns
label to use in drawings
- Return type
str
Example (using the Sum composite operator)
>>> op = qml.S(0) + qml.X(0) + qml.Rot(1,2,3, wires=[1]) >>> op.label() '(S+X)+Rot' >>> op.label(decimals=2, base_label=[["my_s", "my_x"], "inc_rot"]) '(my_s+my_x)+inc_rot\n(1.00,\n2.00,\n3.00)'
- map_wires(wire_map)[source]¶
Returns a copy of the current
LinearCombination
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
LinearCombination
- Return type
- 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
- Parameters
wire_order (Iterable) – global wire order, must contain all wire labels from the
wires (operator's) –
- 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'>)[source]¶
Queues a
qml.ops.LinearCombination
instance
- simplify(cutoff=1e-12)[source]¶
Reduce the depth of nested operators to the minimum.
- Returns
simplified operator
- Return type
- 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.See also
- 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]¶
Retrieve the coefficients and operators of the
LinearCombination
.- Returns
list of coefficients \(c_i\) and list of operations \(O_i\)
- Return type
tuple[list[tensor_like or float], list[Operation]]
Example
>>> coeffs = [1., 2., 3.] >>> ops = [X(0), X(0) @ X(1), X(1) @ X(2)] >>> op = qml.ops.LinearCombination(coeffs, ops) >>> op.terms() ([1.0, 2.0, 3.0], [X(0), X(0) @ X(1), X(1) @ X(2)])