qp.BasisRotation¶
- class BasisRotation(unitary_matrix, wires, check=False)[source]¶
Bases:
Operator2Implements a circuit that performs an exact single-body basis rotation using Givens rotations and phase shifts.
The
BasisRotationtemplate performs the following unitary transformation \(U(u)\) determined by the single-particle fermionic generators as given in arXiv:1711.04789:\[U(u) = \exp{\left( \sum_{pq} \left[\log u \right]_{pq} (a_p^\dagger a_q - a_q^\dagger a_p) \right)}.\]The unitary \(U(u)\) is implemented efficiently by performing its Givens decomposition into a sequence of
PhaseShiftandSingleExcitationgates using the construction scheme given in Optica, 3, 1460 (2016). For real-valued, i.e., orthogonal \(u\), onlySingleExcitationgates are required, except for aPauliZphase flip for \(\operatorname{det}(u)=-1\).See also
givens_decomposition()for the underlying matrix factorization.- Parameters:
wires (Iterable[Any]) – wires that the operator acts on
unitary_matrix (array) – matrix specifying the basis transformation
check (bool) – test unitarity of the provided unitary_matrix
- Raises:
ValueError – if the provided matrix is not square.
ValueError – if length of the wires is less than two.
Available decompositions
Resources are general, for \(N \times N\) matrix \(u\) (
unitary_matrix) on \(N\) wires. Each circuit shows one example of the rule. Use a rule when decomposing withqp.decompose:qp.decompose(gate_set=..., fixed_decomps={qp.BasisRotation: "<name>"})
_real_basis_rotation_decompExample: \(N=3\), with \(\det u = -1\) for the real-valued rule
Requires real-valued \(u\)
Gate
Count
Example
\([\det u = -1]\)
1
\(N(N-1)/2\)
3
where \([\cdot]\) is 1 if the condition holds and 0 otherwise
_complex_basis_rotation_decompExample: \(N=3\), with \(\det u = -1\) for the real-valued rule
Requires complex-valued \(u\)
Usage Details
The
BasisRotationtemplate can be used to implement the evolution \(e^{iH}\) where \(H = \sum_{pq} V_{pq} a^\dagger_p a_q\) and \(V\) is an \(N \times N\) Hermitian matrix. When the unitary matrix \(u\) is the transformation matrix that diagonalizes \(V\), the evolution is:\[e^{i \sum_{pq} V_{pq} a^\dagger_p a_q} = U(u)^\dagger \prod_k e^{i\lambda_k \sigma_z^k} U(u),\]where \(\lambda_k\) denotes the eigenvalues of matrix \(V\), the Hamiltonian coefficients matrix.
>>> V = np.array([[ 0.53672126+0.j , -0.1126064 -2.41479668j], ... [-0.1126064 +2.41479668j, 1.48694623+0.j ]]) >>> eigen_vals, eigen_vecs = np.linalg.eigh(V) >>> umat = eigen_vecs.T >>> wires = range(len(umat)) >>> def circuit(): ... qp.adjoint(qp.BasisRotation)(wires=wires, unitary_matrix=umat) ... for idx, eigenval in enumerate(eigen_vals): ... qp.RZ(eigenval, wires=[idx]) ... qp.BasisRotation(wires=wires, unitary_matrix=umat) >>> circ_unitary = qp.matrix(circuit, wire_order=wires)() >>> np.round(circ_unitary/circ_unitary[0][0], 3) array([[ 1. -0.j , -0. +0.j , -0. +0.j , -0. +0.j ], [-0. +0.j , -0.516-0.596j, -0.302-0.536j, -0. +0.j ], [-0. +0.j , 0.35 +0.506j, -0.311-0.724j, -0. +0.j ], [-0. +0.j , -0. +0.j , -0. +0.j , -0.438+0.899j]])
The
BasisRotationis implemented withPhaseShiftandSingleExcitationgates:>>> @qp.transforms._tape_decompose(gate_set=qp.gate_sets.ALL_OPS) ... def circ(): ... qp.BasisRotation(wires=wires, unitary_matrix=umat) >>> print(qp.draw(circ)()) 0: ──Rϕ(-1.52)─╭G(1.38)──Rϕ(-1.62)─┤ 1: ──Rϕ(1.62)──╰G(1.38)────────────┤
For real-valued matrices, the decomposition only consists of
SingleExcitationgates, except for onePauliZgate to account for negative determinants:>>> from scipy.stats import ortho_group >>> O = ortho_group.rvs(4, random_state=51) >>> @qp.transforms._tape_decompose(gate_set=qp.gate_sets.ALL_OPS) ... def circ(): ... qp.BasisRotation(wires=range(4), unitary_matrix=O) >>> print(qp.draw(circ)()) 0: ──Z───────╭G(-3.19)───────────╭G(2.63)──┤ 1: ─╭G(3.13)─╰G(-3.19)─╭G(-2.68)─╰G(2.63)──┤ 2: ─╰G(3.13)─╭G(2.98)──╰G(-2.68)─╭G(-5.70)─┤ 3: ──────────╰G(2.98)────────────╰G(-5.70)─┤
Theory
The basis rotation performed by
BasisRotationimplements a transformation in the qubit Hilbert space that corresponds to a simple basis change of fermionic creation operators, translated to qubits via the Jordan-Wigner mapping. The old fermionic creation operators \(a_p^\dagger\) and the new creation operators \(b_p^\dagger\) are related to each other by the following equation:\[b_p^\dagger = \sum_{q}u_{pq} a_q^\dagger.\]The effect of \(U(u)\), the rotation in qubit Hilbert space, is then
\[U(u) A_p^\dagger U(u)^\dagger = B_p^\dagger,\]where \(A_p^\dagger\) and \(B_p^\dagger\) are the original and transformed creation operators under the Jordan-Wigner transformation, respectively.
Underlying matrix factorization
The rotation is irreducibly represented as a unitary \(N\times N\) matrix \(u\), which can be factorized into nearest-neighbour Givens rotations and individual phase shifts. Such a factorization of \(u\) is implemented in
givens_decomposition().The Givens rotations take the form
\[\begin{split}T_{k}(\theta) = \begin{pmatrix} 1 & 0 & \cdots & 0 & 0 & \cdots & 0 & 0 \\ 0 & 1 & & & & & 0 & 0 \\ \vdots & & \ddots & & & & & \vdots \\ 0 & & & \cos(\theta) & -\sin(\theta) & & & 0 \\ 0 & & & \sin(\theta) & \cos(\theta) & & & 0 \\ \vdots & & & & & \ddots & & \vdots \\ 0 & 0 & & & & & 1 & 0 \\ 0 & 0 & \cdots & 0 & 0 & \cdots & 0 & 1 \\ \end{pmatrix},\end{split}\]where the four non-trivial entries are at indices \(k\) and \(k+1\). It will also be useful to look at the generator of \(T_{k}\):
\[T_k(\theta) = \exp(\theta E_{k,k+1}),\]where \(E_{k,\ell}\) is a matrix that is zero everywhere except for a \(-1\) in position \((k,\ell)\) and a \(1\) in position \((\ell,k)\). The phase shifts in the decomposition read
\[P_{j}(\phi) = \operatorname{diag}(1,\cdots, 1, e^{i\phi}, 1, \cdots, 1),\]with the single non-trivial entry at index \(j\). Such a phase shift is generated in the following form:
\[P_j(\phi) = \exp(i \phi D_{j}),\]where \(D_j\) is zero everywhere except for a \(1\) in position \((j,j)\).
Next, we consider multiple Lie algebras generated by the \(E_{k,k+1}\) and \(D_j\), and in particular the full Lie algebra \(\mathfrak{g}\) generated by all of them:
\[\begin{split}\langle\{E_{k,k+1}\}_k\rangle_\text{Lie} &= \text{span}_{\mathbb{R}}\{E_{k,\ell} | 1\leq k<\ell\leq N\}\cong\mathfrak{so}(N)\\ \langle\{D_{j}\}_j\rangle_\text{Lie} &= \text{span}_{\mathbb{R}}\{D_{j} | 1\leq j\leq N\}\cong\mathfrak{u}(1)^N\\ \mathfrak{g}=\langle\{D_{j}\}_j\cup\{E_{k,k+1}\}_k\rangle_\text{Lie} &=\text{span}_{\mathbb{R}}\left(\{E_{k,\ell}, F_{k,\ell}| 1\leq k<\ell \leq N\}\cup\{D_{j}\}_j\right) \cong \mathfrak{u}(N).\end{split}\]The full algebra \(\mathfrak{g}\) contains the matrices \(F_{k,\ell}\) that look like the matrices \(E_{k,\ell}\), but without any minus sign. There are
N(N-1) / 2matrices \(E\) and \(F\) each, andNmatrices \(D\). So that all taken together span the \(N^2\)-dimensional algebra \(\mathfrak{u}(N)\).Mapping the matrix factorization to a circuit
The factorization of \(u\) can be mapped to a quantum circuit by identifying:
\[\begin{split}T_{k}(\theta) &\mapsto \texttt{SingleExcitation}(2\theta,\texttt{wires=[k, k+1]}),\\ P_{j}(\phi) &\mapsto \texttt{PhaseShift}(\phi, \texttt{wires=[j]}).\end{split}\]This identification is a group homomorphism, which is proven in arXiv:1711.04789. We can understand this by looking at the algebra to which this mapping sends the algebra \(\mathfrak{g}\) from above. The
SingleExcitationgates have the generators \(\hat{E}_{k,k+1}=\tfrac{i}{2}(X_k Y_{k+1} - Y_k X_{k+1})\) (note the additional prefactor of \(2\) from the mapping):>>> qp.generator(qp.SingleExcitation(0.2512, [0, 1])) (X(0) @ Y(1) + -1.0 * (Y(0) @ X(1)), np.float64(0.25))
Similarly, the
PhaseShiftgates have the generators \(\hat{D}_j=\tfrac{i}{2}(\mathbb{I}-Z_j)=i|1\rangle\langle 1|_j\):>>> qp.generator(qp.PhaseShift(0.742, [0])) (Projector(array([1]), wires=[0]), 1.0)
It turns out that these generators \(\hat{E}_{k,k+1}\) and \(\hat{D}_j\) have commutation relations equivalent to those of the irreducible matrices above, with a crucial feature in how the identification \(E_{k,k+1}\mapsto \hat{E}_{k,k+1}\) generalizes. One could try to map, say, \(E_{2, 4}\) to \(\tfrac{i}{2}(X_2 Y_4 -Y_2 X_4)\), but this will not be consistent with the operators and commutation relations in the algebra. Instead, we need to insert strings of Pauli \(Z\) operators whenever the interaction encoded by the generator is not between nearest neighbours, so that \(E_{2,4}\) maps to \(\tfrac{i}{2}(X_2 Z_3 Y_4 -Y_2 Z_3 X_4)\), which we also denote as \(\tfrac{i}{2}(\overline{X_2 Y_4} -\overline{Y_2 X_4})\). Then we have
\[\begin{split}E_{k,\ell} & \mapsto \hat{E}_{k,\ell} = \tfrac{i}{2}(\overline{X_kY_\ell}-\overline{Y_kX_\ell}),\\ F_{k,\ell} & \mapsto \hat{F}_{k,\ell} = \tfrac{i}{2}(\overline{X_kX_\ell}+\overline{Y_kY_\ell}),\\ D_{j} & \mapsto \hat{D}_{j} = \tfrac{i}{2}(\mathbb{I}-Z_j).\end{split}\]The fact that we need to use \(\overline{X_kY_\ell}\) instead of \(X_kY_\ell\) is a consequence of mapping fermions onto qubits via the Jordan-Wigner transformation. Depending on the application, the relative signs between operators in this mapping need to be evaluated with extra care.
Real rotation matrices
It is common for the orbital rotation matrix implemented by
BasisRotationto be real-valued and thus orthogonal. The generators \(E_{k,k+1}\) generate the Lie algebra \(\mathfrak{so}(N)\), which means that the Givens rotations \(T_k\) are sufficient to factorize the full rotation, and onlySingleExcitationgates are needed in the quantum circuit. A small exception occurs for orthogonal matrices that are not special orthogonal (unit determinant), i.e., that have determinant \(-1\). For those, the sign of one row or column of the matrix can be inverted, corresponding to a phase flip gatePauliZin the circuit. The new matrix then has a unit determinant and can be implemented exclusively withSingleExcitationgates.Attributes
The expected types for the arguments of an operator.
Dictionary mapping argument names to their values.
Arithmetic depth of the operator.
Batch size of the operator if it is used with broadcasted parameters.
partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords.
The names of arguments that are treated as compilable static arguments.
Dictionary mapping compilable argument names to their values.
Legacy Operator compatibility view of dynamic numerical arguments.
The names of arguments that are treated as dynamic.
Dictionary mapping dynamic argument names to their values.
Compute 'grad_recipe' lazily.
Whether the expected signature of an operator is fixed.
The names of arguments that represent dynamic data wrapped in static structures (known as Pytrees).
Dictionary mapping hybrid argument names to their values.
Legacy Operator compatibility view of non-dynamic, non-wire constructor arguments.
Whether this operator contains only abstract data.
This property determines if an operator is verified to be Hermitian.
Operator name.
Number of dimensions per trainable parameter of the operator.
Number of trainable parameters.
Legacy Operator compatibility view of dynamic numerical arguments as a list.
A
PauliSentencerepresentation of the Operator, orNoneif it doesn't have one.The names of arguments that are treated as static.
Dictionary mapping static argument names to their values.
partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords.
The names of arguments corresponding to wires.
Dictionary mapping wire argument names to their values.
The expected number of wire labels for each wire argument.
Wires that the operator acts on.
- arg_specs = {'wires': AbstractWires(-1)}¶
The expected types for the arguments of an operator. This attribute is optional—not setting it has no loss of functionality. If set, it can be used to perform automatic validation of an operators inputs during construction. Additionally, when defining decomposition rules for an operator, operator types with
arg_specsthat spans all the arguments with static types can be placed in the rules’ resources without needing to fully construct abstract operators.Note
A type that is listed in ‘arg_specs’ says what an argument is allowed to be, not what it actually is. For example, if arg_specs contains Complex[-1, -1], the Operator can still be instantiated with a real float64 array, which will then be reported as complex even though it holds real data.
The decomposition graph goes by the reported type, so real and complex inputs will look like the same operator and share one rule. To let them decompose differently, leave the argument out of
arg_specsand give each rule aregister_conditionthat checks the type. For a concrete example seeBasisRotation.
- arguments¶
Dictionary mapping argument names to their values.
- arithmetic_depth¶
Arithmetic depth of the operator.
- batch_size¶
Batch size of the operator if it is used with broadcasted parameters.
The
batch_sizeis determined based onndim_paramsand 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 isNone.- Returns:
Size of the parameter broadcasting dimension if present, else
None.- Return type:
int or None
- check¶
partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords.
- compilable_argnames = ('check',)¶
The names of arguments that are treated as compilable static arguments. Compilable static arguments are a subset of static arguments—arguments whose concrete values are known when compiling the program. But, unlike
static_argnames, they are lowered to the compiler intermediate representation, making their values visible to the compiler, which may be useful if the compiler needs to interact with such values. Such values may include numbers, strings, and lists, tuples, or dictionaries thereof. This feature is opt-in; if any static arguments are not guaranteed to be compilable, it is safer to place them instatic_argnames.Note
An operator can only specify
static_argnamesandhybrid_argnames, orcompilable_argnames, but not both; if any static or hybrid arguments are not or cannot be lowered to the IR, then all static and hybrid arguments are assumed to not be lowerable.
- compilable_args¶
Dictionary mapping compilable argument names to their values.
- data¶
Legacy Operator compatibility view of dynamic numerical arguments.
- dynamic_argnames = ('unitary_matrix',)¶
The names of arguments that are treated as dynamic. Dynamic arguments are numerical arguments whose concrete values may not be known at compile-time, such as rotation angles, matrices, etc., and may include trainable data. Additionally, dynamic arguments are the only ones used to infer
batch_size, necessary for broadcasting support.Inputs for these arguments must be scalars, arrays, or castable to arrays (e.g. multi- dimensional lists with homogenous shapes), and operator constructors will be responsible for “canonicalizing” them (such as casting a list input to an array). At compile-time, the concrete values of these arguments are assumed to be unknown—only their shapes and data types are known.
- dynamic_args¶
Dictionary mapping dynamic argument names to their values.
- grad_method = None¶
- grad_recipe¶
Compute ‘grad_recipe’ lazily.
- has_adjoint = False¶
- has_decomposition = True¶
- has_diagonalizing_gates = False¶
- has_fixed_sig = False¶
Whether the expected signature of an operator is fixed. If
True, then the operator’s signature will always be fully known. When defining decomposition rules for an operator, operator types with fixed signatures can be placed in the rules’ resources without needing to fully construct abstract operators. This is set automatically whenarg_specscovers every dynamic and wire argument, there are no hybrid, static, or compilable arguments, and every declared type is fully fixed (no unknown array shapes or wire counts).
- has_generator = False¶
- has_matrix = False¶
- has_sparse_matrix = False¶
- hybrid_argnames = ()¶
The names of arguments that represent dynamic data wrapped in static structures (known as Pytrees). Names in this category must be disjoint from
dynamic_argnames,static_argnames, andcompilable_argnames, but may overlap withwire_argnameswhen those arguments contain nested structures of wires. Examples of hybrid arguments include collections of wires or dynamic arrays, operators, etc.Note
An operator can only specify
static_argnamesandhybrid_argnames, orcompilable_argnames, but not both; if any static or hybrid arguments are not or cannot be lowered to the IR, then all static and hybrid arguments are assumed to not be lowerable.
- hybrid_args¶
Dictionary mapping hybrid argument names to their values.
- hyperparameters¶
Legacy Operator compatibility view of non-dynamic, non-wire constructor arguments.
- is_fully_abstract¶
Whether this operator contains only abstract data.
- is_verified_hermitian¶
This property determines if an operator is verified to be Hermitian.
Note
This property provides a fast, non-exhaustive check used for internal optimizations. It relies on quick, provable shortcuts (e.g., operator properties) rather than a full, computationally expensive check.
For a definitive check, use the
pennylane.is_hermitian()function. Please note that this comes with increased computational cost.- Returns:
The property will return
Trueif the operator is guaranteed to be Hermitian andFalseif the check is inconclusive and the operator may or may not be Hermitian.- Return type:
bool
Consider this operator,
>>> op = (qp.X(0) @ qp.Y(0) - qp.X(0) @ qp.Z(0)) * 1j
In this case, Hermicity cannot be verified and leads to an inconclusive result:
>>> op.is_verified_hermitian # inconclusive False
However, using
pennylane.is_hermitian()will give the correct answer:>>> qp.is_hermitian(op) # definitive True
- name¶
Operator name.
- 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.
- parameters¶
Legacy Operator compatibility view of dynamic numerical arguments as a list.
- pauli_rep¶
A
PauliSentencerepresentation of the Operator, orNoneif it doesn’t have one.
- static_argnames = ()¶
The names of arguments that are treated as static. Static arguments are those whose concrete values are known when compiling the program. Arguments specified here are not lowered to a compiler intermediate representation (IR). Alternatively, if an argument is of a type that can be lowered, it can be moved to
compilable_argnames.Note
An operator can only specify
static_argnamesandhybrid_argnames, orcompilable_argnames, but not both; if any static or hybrid arguments are not or cannot be lowered to the IR, then all static and hybrid arguments are assumed to not be lowerable.
- static_args¶
Dictionary mapping static argument names to their values.
- unitary_matrix¶
partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords.
- wire_argnames = ('wires',)¶
The names of arguments corresponding to wires. Values for these arguments are automatically wrapped in
Wiresobjects by theOperator2constructor. If an argument is expected to be a structure that wraps wires (known as pytrees), such as a list of wire registers, make sure to include its name inhybrid_argnamesas well. Additionally,Operator2does not descend into the pytree structure of such arguments, so subclasses must ensure every wire leaf inside a hybrid wire argument is already aWiresobject before forwarding it tosuper().__init__.The order in which names appear in
wire_argnamesdetermines the order in which their wires appear inop.wires(seeOperator2.wires). For hybrid wire arguments, the containedWiresleaves are ordered by pytree traversal order. Wires contributed by arguments which are themselvesOperator2objects are appended after allwire_argnameswires. The special names"work_wires"and"work_wire"may be included inwire_argnamesbut their values are excluded fromop.wires.
- wire_args¶
Dictionary mapping wire argument names to their values.
- wire_sizes = (None,)¶
The expected number of wire labels for each wire argument. If any wire arguments support an arbitrary size,
Nonemust be used. By default, all wire arguments are assumed to support arbitrary sizes. For hybrid wire arguments, the wire size must always beNone. Specifying wire sizes allows for additional automatic validation to be implemented, but, specifying it is optional if such validation is not needed.
- wires¶
Wires that the operator acts on.
By default, the returned
Wiresare collected from the operator’s arguments in the following order:For each name in
wire_argnames(in declaration order):If the name is not in
hybrid_argnames, the canonical value of that argument is added.If the name is in
hybrid_argnames, everyWiresleaf of the argument’s pytree is added in pytree traversal order.
After all
wire_argnameshave been processed, for each name inhybrid_argnamesthat is not inwire_argnames, the wires of anyOperator2leaves inside that argument are appended to the end in pytree traversal order.
Duplicate wires are removed while preserving the first occurrence, so the final result is the ordered union of all wires above.
Note
By default, work wires are not included in
op.wires. In particular, wire arguments namedwork_wiresorwork_wireare excluded.Note
This property may be overridden by developers if the default behaviour is not desired, for reasons such as including work wires or changing the order of the wires.
- Returns:
wires
- Return type:
Methods
adjoint()Create an operation that is the adjoint of this one.
compute_decomposition(*args, **kwargs)Representation of the operator as a product of other operators (static method).
compute_diagonalizing_gates(*args, **kwargs)Sequence of gates that diagonalize the operator in the computational basis (static method).
compute_eigvals(*args, **kwargs)Eigenvalues of the operator in the computational basis (static method).
compute_matrix(*args, **kwargs)Representation of the operator as a canonical matrix in the computational basis (static method).
compute_sparse_matrix(*args[, format])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()Eigenvalues of the operator in the computational basis.
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 new 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, format])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()¶
Create an operation that is the adjoint of this one. Used to simplify
Adjointoperators constructed byadjoint(). TODO: [sc-120844] Fix docstring after Adjoint is addedAdjointed operations are the conjugated and transposed version of the original operation. Adjointed ops are equivalent to the inverted operation for unitary gates.
Operator2.adjointcan be optionally defined by Operator developers, whileadjoint()is the entry point for constructing generic adjoint representations.- Returns:
The adjointed operation.
>>> from pennylane.core.operator import Operator2 >>> class MyClass(Operator2): ... dynamic_argnames = ("phi",) ... ... def __init__(self, phi, wires): ... super().__init__(phi, wires) ... ... def adjoint(self): ... return self ... >>> op = MyClass(0.5, wires=0).adjoint() >>> op MyClass(0.5, wires=[0])
- classmethod compute_decomposition(*args, **kwargs)¶
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_decompositionmethod.See also
- Parameters:
*args (tuple) – Positional arguments of the operator
**kwargs (dict) – Keyword arguments of the operator
- Returns:
decomposition of the operator
- Return type:
list[Operator2]
- static compute_diagonalizing_gates(*args, **kwargs)¶
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:
*args (tuple) – Positional arguments of the operator
**kwargs (dict) – Keyword arguments of the operator
- Returns:
list of diagonalizing gates
- Return type:
list[.Operator2]
- static compute_eigvals(*args, **kwargs)¶
Eigenvalues of the operator in the computational basis (static method).
If
diagonalizing_gatesare 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:
*args (tuple) – Positional arguments of the operator
**kwargs (dict) – Keyword arguments of the operator
- Returns:
eigenvalues
- Return type:
tensor_like
- static compute_matrix(*args, **kwargs)¶
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:
*args (tuple) – Positional arguments of the operator
**kwargs (dict) – Keyword arguments of the operator
- Returns:
matrix representation
- Return type:
tensor_like
- static compute_sparse_matrix(*args, format='csr', **kwargs)¶
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:
*args (tuple) – Positional arguments of the operator
format (str) – format of the returned scipy sparse matrix, for example ‘csr’
**kwargs (dict) – Keyword arguments of the operator
- 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
DecompositionUndefinedErroris raised if no representation by decomposition is defined.See also
- Returns:
decomposition of the operator
- Return type:
list[Operator2]
- 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
DiagGatesUndefinedErroris raised if no representation by decomposition is defined.See also
- Returns:
a list of operators
- Return type:
list[.Operator2] or None
- eigvals()¶
Eigenvalues of the operator in the computational basis.
If
diagonalizing_gatesare 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
EigvalsUndefinedErroris raised if the eigenvalues have not been defined and cannot be inferred from the matrix representation.See also
- Returns:
eigenvalues
- Return type:
tensor_like
- 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
LinearCombinationandSparseHamiltonianrespectively).
- 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 = qp.RX(1.23456, wires=0) >>> op.label() 'RX' >>> op.label(base_label="my_label") 'my_label' >>> op = qp.RX(1.23456, wires=0) >>> op.label() 'RX' >>> op.label(decimals=2) 'RX\n(1.23)' >>> op.label(base_label="my_label") 'my_label' >>> op.label(decimals=2, base_label="my_label") 'my_label\n(1.23)'
Note that by default, operator wires and static inputs are not included in the label. To override this behaviour,
Operator2subclasses must override thelabelmethod.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 = qp.QubitUnitary(np.eye(2), wires=0) >>> cache = {'matrices': []} >>> op2.label(cache=cache) 'U\n(M0)' >>> cache['matrices'] [array([[1., 0.], [0., 1.]])] >>> op3 = qp.QubitUnitary(np.eye(4), wires=(0,1)) >>> op3.label(cache=cache) 'U\n(M1)' >>> cache['matrices'] [array([[1., 0.], [0., 1.]]), array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]])]
- map_wires(wire_map)¶
Returns a new 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:
.Operator2
- matrix(wire_order=None)¶
Representation of the operator as a matrix in the computational basis.
If
wire_orderis 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
MatrixUndefinedErroris 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 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. This method is used to simplify
Powinstances created bypow()orop ** power. TODO: [sc-120843] Fix docstring after Pow is addedOperator2.powcan be optionally defined by Operator developers, whilepow()orop ** powerare the entry point for constructing generic powers to exponents.- Parameters:
z (float) – exponent for the operator
- Returns:
list[
Operator2]
>>> from pennylane.core.operator import Operator2 >>> class MyClass(Operator2): ... dynamic_argnames = ("phi",) ... ... def __init__(self, phi, wires): ... super().__init__(phi, wires) ... ... def pow(self, z): ... return [MyClass(self.phi*z, self.wires)] ... >>> MyClass(0.5, 0).pow(2) [MyClass(1.0, wires=[0])]
- queue(context=<class 'pennylane.core.queuing.QueuingManager'>)¶
Append the operator to the Operator queue.
- simplify()¶
Reduce the depth of nested operators to the minimum.
- Returns:
simplified operator
- Return type:
.Operator2
- sparse_matrix(wire_order=None, format='csr')¶
Representation of the operator as a sparse matrix in the computational basis.
If
wire_orderis 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
SparseMatrixUndefinedErroris 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
format (str) – format of the returned scipy sparse matrix, for example ‘csr’
- 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
TermsUndefinedErroris 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[.Operator2]]