qilisdk.common.qtensor

Attributes

Complex

Classes

QTensor

Lightweight wrapper around sparse matrices representing quantum states or operators.

Functions

basis_state(→ QTensor)

Generate the n'th basis vector representation, on a N-size Hilbert space (N=2**num_qubits).

ket(→ QTensor)

Generate a ket state for a multi-qubit system.

bra(→ QTensor)

Generate a bra state for a multi-qubit system.

tensor_prod(→ QTensor)

Calculate the tensor product of a list of QTensors.

expect_val(→ Complex)

Calculate the expectation value of an operator with respect to a quantum state.

Module Contents

Complex[source]
class QTensor(data: numpy.ndarray | scipy.sparse.sparray | scipy.sparse.spmatrix)[source]

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 a SciPy CSR (Compressed Sparse Row) matrix for efficient arithmetic and manipulation. 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.

Converts a NumPy array to a CSR matrix if needed and validates the shape of the input. The input must represent a valid quantum state or operator with appropriate dimensions.

Example

import numpy as np
from qilisdk.common import QTensor

ket = QTensor(np.array([[1.0], [0.0]]))
density = ket * ket.adjoint()
Parameters:

data (np.ndarray | sparray | spmatrix) – 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.

Raises:

ValueError – If data is not 2-D or does not correspond to valid qubit dimensions.

property data: scipy.sparse.csr_matrix[source]

Get the internal sparse matrix representation of the QTensor.

Returns:

The internal representation as a CSR matrix.

Return type:

csc_matrix

property nqubits: int[source]

Compute the number of qubits represented by the QTensor.

Returns:

The number of qubits if determinable; otherwise, -1.

Return type:

int

property shape: tuple[int, int][source]

Get the shape of the QTensor’s internal matrix.

Returns:

The shape of the internal matrix.

Return type:

tuple[int, …]

property dense: numpy.ndarray[source]

Get the dense (NumPy array) representation of the QTensor.

Returns:

The dense array representation.

Return type:

np.ndarray

is_ket() bool[source]
is_bra() bool[source]
is_scalar() bool[source]
is_operator() bool[source]
adjoint() QTensor[source]

Compute the adjoint (conjugate transpose) of the QTensor.

Returns:

A new QTensor that is the adjoint of this object.

Return type:

QTensor

trace() complex[source]
ptrace(keep: list[int], dims: list[int] | None = None) QTensor[source]

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. The input ‘dims’ represents the dimensions of each subsystem (optional), and ‘keep’ indicates the indices of those subsystems to be retained.

If the QTensor is a ket or bra, it will first be converted to a density matrix.

Parameters:
  • keep (list[int]) – A list of indices corresponding to the subsystems to retain. The order of the indices in ‘keep’ is not important, since dimensions will be returned in the tensor original order, but the indices must be unique.

  • dims (list[int], optional) – A list specifying the dimensions of each subsystem. If not specified, a density matrix of qubit states is assumed, and the dimensions are inferred accordingly (i.e. we split the state in dim 2 states).

Raises:
  • ValueError – If the product of the dimensions in dims does not match the shape of the QTensor’s dense representation or if any dimension is non-positive.

  • ValueError – If the indices in ‘keep’ are not unique or are out of range.

  • ValueError – If the QTensor is not a valid density matrix or state vector.

  • ValueError – If the number of subsystems exceeds the available ASCII letters.

Returns:

A new QTensor representing the reduced density matrix

for the subsystems specified in ‘keep’.

Return type:

QTensor

norm(order: int | Literal['fro', 'tr'] = 1) float[source]

Compute the norm of the QTensor.

For density matrices, the norm order can be specified. For state vectors, the norm is computed accordingly.

Parameters:

order (int or {"fro", "tr"}, optional) – The order of the norm. Only applies if the QTensor represents a density matrix. Other than all the orders accepted by scipy, it also accepts ‘tr’ for the trace norm. Defaults to 1.

Raises:

ValueError – If the QTensor is not a valid density matrix or state vector,

Returns:

The computed norm of the QTensor.

Return type:

float

unit(order: int | Literal['fro', 'tr'] = 'tr') QTensor[source]

Normalize the QTensor.

Scales the QTensor so that its norm becomes 1, according to the specified norm order.

Parameters:

order (int or {"fro", "tr"}, optional) – The order of the norm to use for normalization. Only applies if the QTensor represents a density matrix. Other than all the orders accepted by scipy, it also accepts ‘tr’ for the trace norm. Defaults to “tr”.

Raises:

ValueError – If the norm of the QTensor is 0, making normalization impossible.

Returns:

A new QTensor that is the normalized version of this object.

Return type:

QTensor

expm() QTensor[source]

Compute the matrix exponential of the QTensor.

Returns:

A new QTensor representing the matrix exponential.

Return type:

QTensor

to_density_matrix() QTensor[source]

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.

Raises:
  • 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.

Returns:

A new QTensor representing the density matrix.

Return type:

QTensor

is_density_matrix(tol: float = 1e-08) bool[source]

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.

Parameters:

tol (float, optional) – The numerical tolerance for verifying Hermiticity, eigenvalue non-negativity, and trace. Defaults to 1e-8.

Returns:

True if the QTensor is a valid density matrix, False otherwise.

Return type:

bool

is_hermitian(tol: float = 1e-08) bool[source]

Check if the QTensor is Hermitian.

Parameters:

tol (float, optional) – The numerical tolerance for verifying Hermiticity. Defaults to 1e-8.

Returns:

True if the QTensor is Hermitian, False otherwise.

Return type:

bool

basis_state(n: int, N: int) QTensor[source]

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.

Parameters:
  • n (int) – The desired number state (from 0 to N-1).

  • N (int) – The dimension of the Hilbert space, has a value 2**num_qubits.

Raises:

ValueError – If n >= N.

Returns:

A QTensor representing the |n⟩’th basis state on a N-size Hilbert space (N=2**num_qubits).

Return type:

QTensor

ket(*state: int) QTensor[source]

Generate a ket state for a multi-qubit system.

This function creates a tensor product of individual qubit states (kets) based on the input values. Each input must be either 0 or 1. For example, ket(0, 1) creates a two-qubit ket state |0⟩ ⊗ |1⟩.

Parameters:

*state (int) – A sequence of integers representing the state of each qubit (0 or 1).

Raises:

ValueError – If any of the provided qubit states is not 0 or 1.

Returns:

A QTensor representing the multi-qubit ket state.

Return type:

QTensor

bra(*state: int) QTensor[source]

Generate a bra state for a multi-qubit system.

This function creates a tensor product of individual qubit states (bras) based on the input values. Each input must be either 0 or 1. For example, bra(0, 1) creates a two-qubit bra state ⟨0| ⊗ ⟨1|.

Parameters:

*state (int) – A sequence of integers representing the state of each qubit (0 or 1).

Returns:

A QTensor representing the multi-qubit bra state.

Return type:

QTensor

tensor_prod(operators: list[QTensor]) QTensor[source]

Calculate the tensor product of a list of QTensors.

This function computes the tensor (Kronecker) product of all input QTensors, resulting in a composite QTensor that represents the combined state or operator.

Parameters:

operators (list[QTensor]) – A list of QTensors to be combined via tensor product.

Returns:

A new QTensor representing the tensor product of the inputs.

Return type:

QTensor

Raises:

ValueError – If operators list is empty.

expect_val(operator: QTensor, state: QTensor) Complex[source]

Calculate the expectation value of an operator with respect to a quantum state.

Computes the expectation value ⟨state| operator |state⟩. The function handles both pure state vectors and density matrices appropriately.

Parameters:
  • operator (QTensor) – The quantum operator represented as a QTensor.

  • state (QTensor) – The quantum state or density matrix represented as a QTensor.

Raises:
  • ValueError – If the operator is not a square matrix.

  • ValueError – If the state provided is not a valid quantum state.

Returns:

The expectation value. The result is guaranteed to be real if the operator is Hermitian, and may be complex otherwise.

Return type:

Complex