qilisdk.core.qtensor
Attributes
Classes
Enumeration of symbolic initial states that can be used to specify the initial state of an evolution without needing to construct the corresponding QTensor manually. |
|
Lightweight wrapper around sparse matrices representing quantum states or operators. |
Functions
|
Wrapper for backwards compatibility: see QTensor.ket(). |
|
Wrapper for backwards compatibility: see QTensor.bra(). |
|
Wrapper for backwards compatibility: see QTensor.expectation_value(). |
|
Wrapper for backwards compatibility: see QTensor.tensor_product(). |
|
Wrapper for backwards compatibility: see QTensor.reset_qubits(). |
|
Wrapper for backwards compatibility: see QTensor.zero(). |
|
Wrapper for backwards compatibility: see QTensor.basis_state(). |
|
Wrapper for QTensor.identity(). |
|
Wrapper for QTensor.ghz(). |
Module Contents
- Complex[fuente]
- NormTypes[fuente]
- QTensorType[fuente]
- class InitialState(*args, **kwds)[fuente]
Bases:
enum.EnumEnumeration of symbolic initial states that can be used to specify the initial state of an evolution without needing to construct the corresponding QTensor manually.
- UNIFORM = 'uniform'[fuente]
- ZERO = 'zero'[fuente]
- ONE = 'one'[fuente]
- as_qtensor(nqubits: int) QTensor[fuente]
Convert the symbolic initial state to a QTensor.
- Parámetros:
nqubits (
int) – The number of qubits in the system, which determines the size of the resulting QTensor.- Devuelve:
A QTensor representing the specified initial state for the given number of qubits.
- Tipo del valor devuelto:
- Muestra:
ValueError – If the symbolic initial state is not recognized.
- class QTensor(other: numpy.ndarray | scipy.sparse.sparray | scipy.sparse.spmatrix | list[list[qilisdk.core.types.Number]])[fuente]
Lightweight wrapper around sparse matrices representing quantum states or operators.
The QTensor class is a wrapper around sparse matrices (or NumPy arrays, which are converted to sparse matrices) that represent quantum states (kets, bras, or density matrices) or operators. It provides utility methods for common quantum operations such as taking the adjoint (dagger), computing tensor products, partial traces, and norms.
The internal data is stored as an Eigen matrix whose backend is chosen automatically from the shape and sparsity: row-major sparse (CSR) for bras and square operators, column-major sparse (CSC) for kets, or dense when the data is dense enough that sparse storage would waste memory. The expected shapes for the data are:
(2**N, 2**N) for operators or density matrices (or scalars),
(2**N, 1) for ket states,
(1, 2**N) for bra states.
Ejemplo
import numpy as np from qilisdk.core import QTensor ket = QTensor(np.array([[1.0], [0.0]])) density = ket * ket.adjoint()- Parámetros:
other (
np.ndarray | sparray | spmatrix | list[list[Number]]) – Dense or sparse matrix defining the quantum object. Expected shapes are(2**N, 2**N)for operators,(2**N, 1)for kets,(1, 2**N)for bras, or(1, 1)for scalars.- Muestra:
ValueError – If
datais not 2-D or does not correspond to valid qubit dimensions.
- property data: scipy.sparse.csr_matrix[fuente]
Get the contents of the QTensor as a SciPy sparse matrix.
The result is always a CSR matrix, regardless of the backend used internally (row-major sparse, column-major sparse, or dense).
- Devuelve:
The tensor’s contents as a SciPy CSR matrix.
- Tipo del valor devuelto:
csr_matrix
- property nqubits: int[fuente]
Compute the number of qubits represented by the QTensor.
- Devuelve:
The number of qubits if determinable; otherwise, -1.
- Tipo del valor devuelto:
int
- property shape: tuple[int, int][fuente]
Get the shape of the QTensor’s internal matrix.
- Devuelve:
The shape of the internal matrix.
- Tipo del valor devuelto:
tuple[int, …]
- dense() numpy.ndarray[fuente]
Get the dense (NumPy array) representation of the QTensor.
- Devuelve:
The dense array representation.
- Tipo del valor devuelto:
np.ndarray
- is_ket() bool[fuente]
Check if the QTensor represents a ket state.
- Devuelve:
True if the QTensor is a ket state, False otherwise.
- Tipo del valor devuelto:
bool
- is_bra() bool[fuente]
Check if the QTensor represents a bra state.
- Devuelve:
True if the QTensor is a bra state, False otherwise.
- Tipo del valor devuelto:
bool
- is_scalar() bool[fuente]
Check if the QTensor represents a scalar.
- Devuelve:
True if the QTensor is a scalar, False otherwise.
- Tipo del valor devuelto:
bool
- is_operator() bool[fuente]
Check if the QTensor represents an operator (square matrix).
- Devuelve:
True if the QTensor is an operator, False otherwise.
- Tipo del valor devuelto:
bool
- is_density_matrix(tol: float = get_settings().atol) bool[fuente]
Determine if the QTensor is a valid density matrix.
A valid density matrix must be square, Hermitian, positive semi-definite, and have a trace equal to 1.
- Parámetros:
tol (
float, optional) – The absolute tolerance for checking density matrix properties. Defaults to the global setting.- Devuelve:
True if the QTensor is a valid density matrix, False otherwise.
- Tipo del valor devuelto:
bool
- is_hermitian(tol: float = get_settings().atol) bool[fuente]
Check if the QTensor is Hermitian.
- Parámetros:
tol (
float, optional) – The absolute tolerance for checking Hermitian property. Defaults to the global setting.- Devuelve:
True if the QTensor is Hermitian, False otherwise.
- Tipo del valor devuelto:
bool
- is_unitary(tol: float = get_settings().atol) bool[fuente]
Check if the QTensor is unitary.
- Parámetros:
tol (
float, optional) – The absolute tolerance for checking unitarity. Defaults to the global setting.- Devuelve:
True if the QTensor is unitary, False otherwise.
- Tipo del valor devuelto:
bool
- is_symmetric(tol: float = get_settings().atol) bool[fuente]
Check if the QTensor is symmetric.
A matrix is symmetric if it is equal to its transpose (A == A^T) within a specified tolerance.
- Parámetros:
tol (
float, optional) – The absolute tolerance for checking symmetry. Defaults to the global setting.- Devuelve:
True if the QTensor is symmetric, False otherwise.
- Tipo del valor devuelto:
bool
- is_self_adjoint(tol: float = get_settings().atol) bool[fuente]
Check if the QTensor is self-adjoint (Hermitian).
A matrix is self-adjoint if it is equal to its conjugate transpose (A == A^†) within a specified tolerance.
- Parámetros:
tol (
float, optional) – The absolute tolerance for checking self-adjointness. Defaults to the global setting.- Devuelve:
True if the QTensor is self-adjoint, False otherwise.
- Tipo del valor devuelto:
bool
- adjoint() QTensor[fuente]
Compute the adjoint (conjugate transpose) of the QTensor.
- Devuelve:
A new QTensor that is the adjoint of this object.
- Tipo del valor devuelto:
- conjugate() QTensor[fuente]
Compute the complex conjugate of the QTensor.
- Devuelve:
A new QTensor that is the complex conjugate of this object.
- Tipo del valor devuelto:
- transpose() QTensor[fuente]
Compute the transpose of the QTensor.
- Devuelve:
A new QTensor that is the transpose of this object.
- Tipo del valor devuelto:
- dagger() QTensor[fuente]
Alias for adjoint() to provide a more familiar method name for quantum objects.
- Devuelve:
A new QTensor that is the adjoint of this object.
- Tipo del valor devuelto:
- trace() complex[fuente]
Compute the trace of the QTensor.
- Devuelve:
The trace of the QTensor.
- Tipo del valor devuelto:
complex
- dot(other: QTensor) qilisdk.core.types.Number[fuente]
Compute the dot product (inner product) between this QTensor and another.
For state vectors, this corresponds to the inner product. For operators, it corresponds to the Hilbert-Schmidt inner product.
- Parámetros:
other (
QTensor) – The other QTensor to compute the dot product with.- Devuelve:
The computed dot product, which may be a complex number.
- Tipo del valor devuelto:
Number
- ptrace(keep: list[int]) QTensor[fuente]
Wrapper for backwards compatibility: see partial_trace().
- Parámetros:
keep (
list[int]) – A list of indices corresponding to the subsystems to retain.- Devuelve:
A new QTensor representing the reduced density matrix for the subsystems specified in “keep”.
- Tipo del valor devuelto:
- Muestra:
ValueError – If there are duplicate indices in the “keep” list.
- partial_trace(keep: set[int]) QTensor[fuente]
Compute the partial trace over subsystems not in “keep”.
This method calculates the reduced density matrix by tracing out the subsystems that are not specified in the “keep” parameter.
- Parámetros:
keep (
set[int]) – A set of indices corresponding to the subsystems to retain.- Muestra:
ValueError – If the indices in “keep” are out of range.
- Devuelve:
A new QTensor representing the reduced density matrix.
- Tipo del valor devuelto:
- norm(order: NormTypes = 'auto') float[fuente]
Compute the norm of the QTensor.
If the order is left as «auto», the method will choose an appropriate norm based on the type of QTensor (i.e., trace for operators, frobenius for state vectors). Integers can also be supplied, where 1 corresponds to the L1 norm and 2 corresponds to the L2 (Frobenius) norm etc. Note that here «trace» refers to the trace of the matrix, whilst «nuclear» refers to the trace norm (sum of singular values).
- Parámetros:
order (
Literal[``»auto», ``"frobenius","trace","l1","l2","inf","nuclear"], optional) – The order of the norm. Defaults to «auto».- Devuelve:
The computed norm of the QTensor.
- Tipo del valor devuelto:
float
- Muestra:
ValueError – If an unsupported norm order is specified.
- eig() tuple[list[complex], list[QTensor]][fuente]
Compute the eigendecomposition of the QTensor and return the eigenvalues and eigenvectors. The eigendecomposition is only computed once and cached for future use.
- Devuelve:
A tuple containing a list of eigenvalues and a list of corresponding eigenvectors as QTensors.
- Tipo del valor devuelto:
tuple[list[complex], list[QTensor]]
- Muestra:
ValueError – If the QTensor is not a square matrix (i.e., not an operator).
- unit(order: NormTypes = 'auto') QTensor[fuente]
Wrapper for backwards compatibility: see normalized().
- normalized(order: NormTypes = 'auto') QTensor[fuente]
Normalize the QTensor.
Scales the QTensor so that its norm becomes 1, according to the specified norm order. See the norm() method for details on the supported norm orders and their behavior.
- expm() QTensor[fuente]
Wrapper for backwards compatibility: see exponential().
- Devuelve:
A new QTensor representing the matrix exponential.
- Tipo del valor devuelto:
- exp() QTensor[fuente]
Compute the matrix exponential of the QTensor.
- Devuelve:
A new QTensor representing the matrix exponential.
- Tipo del valor devuelto:
- inverse() QTensor[fuente]
Compute the matrix inverse of the QTensor.
- Devuelve:
A new QTensor representing the matrix inverse.
- Tipo del valor devuelto:
- Muestra:
ValueError – If the QTensor is not invertible.
- fidelity(other: QTensor) float[fuente]
Compute the fidelity between this QTensor and another QTensor.
The fidelity is a measure of similarity between two quantum states or operators. For state vectors, it is defined as \(F(\psi, \phi) = |⟨\psi|\phi⟩|^2\). For density matrices, it is defined as \(F(\rho, \sigma) = (\text{tr}(\sqrt{\sqrt{\rho} \sigma \sqrt{\rho}}))^2\).
- Parámetros:
other (
QTensor) – The other QTensor to compute the fidelity with.- Devuelve:
The fidelity between this QTensor and the other QTensor, ranging from 0 to 1.
- Tipo del valor devuelto:
float
- to_density_matrix(max_relative_correction: float = 0.1) QTensor[fuente]
Wrapper for backwards compatibility: see as_density_matrix().
- Devuelve:
A new QTensor representing the density matrix.
- Tipo del valor devuelto:
- as_density_matrix(max_relative_correction: float = 0.1) QTensor[fuente]
Convert the QTensor to a density matrix.
If the QTensor represents a state vector (ket or bra), this method calculates the corresponding density matrix by taking the outer product. If the QTensor is already a density matrix, it is returned unchanged. The resulting density matrix is normalized.
- Muestra:
ValueError – If the QTensor is a scalar, as a density matrix cannot be derived.
ValueError – If the QTensor is an operator that is not a density matrix.
- Devuelve:
A new QTensor representing the density matrix.
- Tipo del valor devuelto:
- classmethod tensor_product(others: list[QTensor]) QTensor[fuente]
Compute the tensor product of a list of QTensor.
- Parámetros:
others (
list[QTensor]) – A list of QTensors to tensor product.- Devuelve:
A new QTensor representing the tensor product.
- Tipo del valor devuelto:
- classmethod zero(nqubits: int) QTensor[fuente]
Create a QTensor representing the |0..0> statevector.
- classmethod ghz(nqubits: int) QTensor[fuente]
Create a GHZ state for the specified number of qubits.
- classmethod uniform(nqubits: int) QTensor[fuente]
Create a uniform superposition state for the specified number of qubits.
- classmethod basis_state(n: int, N: int) QTensor[fuente]
Generate the n’th basis vector representation, on a N-size Hilbert space (N=2**num_qubits).
This function creates a column vector (ket) representing the Fock state \(|n⟩\) in a Hilbert space of dimension N.
- Parámetros:
- Muestra:
ValueError – If n >= N.
- Devuelve:
A QTensor representing the n’th basis state on a N-size Hilbert space (N=2**num_qubits).
- Tipo del valor devuelto:
- reset_qubits(qubits: set[int]) QTensor[fuente]
Reset the specified qubits to the \(|0⟩\) state.
This method applies a reset operation to the specified qubits, effectively tracing out those qubits and replacing them with \(|0⟩\) states.
- Parámetros:
qubits (
set[int]) – A set of indices corresponding to the qubits to reset.- Devuelve:
A new QTensor representing the state after resetting the specified qubits.
- Tipo del valor devuelto:
- probabilities() list[float][fuente]
Compute the probabilities of measuring each basis state.
This method calculates the probabilities of obtaining each basis state upon measurement, which is given by the squared magnitudes of the coefficients in the state vector (for kets) or the diagonal elements (for density matrices).
- Devuelve:
A 1D array containing the probabilities of measuring each basis state.
- Tipo del valor devuelto:
np.ndarray
- sample(nshots: int = 1000, seed: int | None = None) dict[str, int][fuente]
Sample measurement outcomes in the computational basis.
- Parámetros:
nshots (
int) – The number of shots to draw. Defaults to 1000.seed (
int | None) – The random seed used for the sampling. If None, a random seed is generated.
- Devuelve:
A mapping from bitstring (with qubit zero first) to the number of times it was obtained.
- Tipo del valor devuelto:
dict[str, int]
- Muestra:
ValueError – If nshots is not positive, if this QTensor is neither a ket, bra, nor operator, or if the probabilities do not form a valid distribution.
- entropy_von_neumann() float[fuente]
Compute the von Neumann entropy of the QTensor.
This method calculates the von Neumann entropy, which is defined as S(rho) = -Tr(rho log(rho)), where rho is the density matrix represented by the QTensor.
- Devuelve:
The von Neumann entropy of the QTensor.
- Tipo del valor devuelto:
float
- entropy_renyi(alpha: float) float[fuente]
Compute the Rényi entropy of the QTensor for a given order alpha.
This method calculates the Rényi entropy, which is defined as \(S_\text{alpha}(\rho) = (1/(1-\alpha)) \text{log}(\text{tr}(\rho^\alpha))\), where rho is the density matrix represented by the QTensor and alpha is the order of the entropy.
- Parámetros:
alpha (
float) – The order of the Rényi entropy. Must be greater than 0 and not equal to 1.- Devuelve:
The Rényi entropy of the QTensor for the specified order alpha.
- Tipo del valor devuelto:
float
- magic(alpha: float = 2.0) float[fuente]
Compute the magic (non-stabilizerness) of a pure state via the stabilizer Rényi entropy (SRE).
The SRE quantifies how far a pure state \(|\psi⟩\) of \(N\) qubits departs from the set of stabilizer states. For a Rényi index \(\alpha > 0\), \(\alpha \neq 1\), it is defined as
\[M_\alpha(|\psi⟩) = \frac{1}{1 - \alpha} \log_2\!\left[\frac{1}{2^N} \sum_{P \in \mathcal{P}_N} ⟨\psi|P|\psi⟩^{2\alpha}\right],\]where the sum runs over all \(4^N\) Pauli strings \(P\). The value \(\alpha = 1\) is obtained via the limit \(\alpha \to 1\), giving the Shannon entropy of the Pauli distribution. The SRE is non-negative, vanishing if and only if \(|\psi⟩\) is a stabilizer state, is invariant under Clifford unitaries, and is additive under tensor products.
This is a numerically exact implementation of Algorithm 2 of Sierant, Valles-Muns and Garcia-Saez, «Computing quantum magic of state vectors», which exploits the fast Walsh-Hadamard transform to evaluate the SRE in \(O(N\,4^N)\) time and \(O(2^N)\) memory, an exponential speedup over the naive \(O(8^N)\) sweep over all Pauli strings.
- Parámetros:
alpha (
float, optional) – The Rényi index \(\alpha > 0\). Defaults to 2, the value for which the SRE is a stabilizer monotone and the most commonly used measure of magic.- Devuelve:
The stabilizer Rényi entropy \(M_\alpha(|\psi⟩)\).
- Tipo del valor devuelto:
float
- Muestra:
ValueError – If the QTensor is not a pure state (ket or bra), or if
alphais not positive.
- commutator(other: QTensor) QTensor[fuente]
Compute the commutator [A, B] = AB - BA with another QTensor.
- anticommutator(other: QTensor) QTensor[fuente]
Compute the anticommutator {A, B} = AB + BA with another QTensor.
- pow(exponent: float) QTensor[fuente]
Compute the integer power of the QTensor.
- Parámetros:
exponent (
float) – The exponent to raise the QTensor to.- Devuelve:
A new QTensor representing the result of raising this QTensor to the given power.
- Tipo del valor devuelto:
- Muestra:
ValueError – If the exponent is not a real number.
- sqrt() QTensor[fuente]
Compute the matrix square root of the QTensor.
- Devuelve:
A new QTensor representing the matrix square root.
- Tipo del valor devuelto:
- rank() int[fuente]
Compute the rank of the QTensor.
- Devuelve:
The rank of the QTensor.
- Tipo del valor devuelto:
int
- log() QTensor[fuente]
Compute the matrix logarithm of the QTensor.
- Devuelve:
A new QTensor representing the matrix logarithm.
- Tipo del valor devuelto:
- property eigenvalues: list[qilisdk.core.types.Number][fuente]
Get the eigenvalues of the QTensor. Note that this computes the eigendecomposition if it has not already been computed and cached.
- Devuelve:
A list of eigenvalues of the QTensor.
- Tipo del valor devuelto:
list[Number]
- property eigenvectors: list[QTensor][fuente]
Get the eigenvectors of the QTensor. Note that this computes the eigendecomposition if it has not already been computed and cached.
- Devuelve:
A list of QTensor objects representing the eigenvectors of the QTensor.
- Tipo del valor devuelto:
list[QTensor]
- expectation_value(other: QTensor | qilisdk.analog.Hamiltonian, nshots: int = 0) complex[fuente]
Compute the expectation value of another QTensor with respect to this QTensor.
For state vectors, this corresponds to \(⟨\psi|O|\psi⟩\). For operators, it corresponds to \(\text{tr}(\rho O)\).
With nshots > 0 the expectation value is estimated with shot noise. A QTensor observable is measured in its own eigenbasis, computing and caching its eigendecomposition if needed, whereas a Hamiltonian observable is handled matrix-free by measuring each of its Pauli terms with nshots shots.
- Parámetros:
other (
QTensor | Hamiltonian) – The other QTensor or Hamiltonian to compute the expectation value with.nshots (
int, optional) – The number of shots to use for a stochastic estimation of the expectation value. If 0 or negative, the exact expectation value is computed using the trace formula.
- Devuelve:
The computed expectation value, which may be a complex number.
- Tipo del valor devuelto:
complex
- draw(style: qilisdk.utils.visualization.style.QTensorStyle = QTensorStyle(), filepath: str | None = None) None[fuente]
Render the QTensor on the Bloch sphere with Matplotlib and optionally save it to a file.
Only single-qubit QTensors can be drawn, either as a state vector (ket or bra) or as a density matrix, the latter allowing one qubit of a larger state to be drawn after reducing it with
partial_trace(). The arrow is the Bloch vector (tr(rho X), tr(rho Y), tr(rho Z)), so a mixed state sits inside the sphere rather than on its surface. The state is rendered using the provided style configuration. Iffilepathis given, the resulting figure is saved to disk (the output format is inferred from the file extension, e.g..png,.pdf,.svg).- Parámetros:
style (
QTensorStyle) – Visual style configuration applied to the plot. If not provided, the defaultQTensorStyleis used.filepath (
str | None) – Destination file path for the rendered figure. IfNone, the figure is not saved.
- expect_val(operator: QTensor | qilisdk.analog.Hamiltonian, state: QTensor, nshots: int = 0) complex[fuente]
Wrapper for backwards compatibility: see QTensor.expectation_value().
- Parámetros:
state (
QTensor) – The state vector or density matrix to compute the expectation value with respect to.operator (
QTensor) – The operator for which to compute the expectation value.nshots (
int, optional) – The number of shots to use for a stochastic estimation of the expectation value. If 0 or negative, the exact expectation value is computed using the trace formula.
- Devuelve:
The computed expectation value, which may be a complex number.
- Tipo del valor devuelto:
complex
- tensor_prod(states: list[QTensor]) QTensor[fuente]
Wrapper for backwards compatibility: see QTensor.tensor_product().
- Parámetros:
states (
list[QTensor]) – A list of QTensors to tensor product.- Devuelve:
A new QTensor representing the tensor product.
- Tipo del valor devuelto:
- reset_qubits(state: QTensor, qubits: list[int]) QTensor[fuente]
Wrapper for backwards compatibility: see QTensor.reset_qubits().
- basis_state(n: int, N: int) QTensor[fuente]
Wrapper for backwards compatibility: see QTensor.basis_state().