Skip to content

Utilities

Helpers the state factories are built from.

ketbra(a, b) is the outer product \(|a\rangle\langle b|\), defaulting to \(|a\rangle\langle a|\).

upb(basis) turns an unextendible product basis \(\{|v_i\rangle\}_{i=1}^{k}\) in total dimension \(D\) into the bound entangled state on its orthogonal complement,

\[ \rho = \frac{1}{D - k}\Big(\mathbb{1} - \sum_{i=1}^{k} |v_i\rangle\langle v_i|\Big). \]

Each \(|v_i\rangle\langle v_i|\) is a product-state projector, which partial transposition leaves a product-state projector, so \(\rho\) is PPT; the basis being unextendible means no product vector lies in the range of \(\rho\), so by the range criterion it is entangled. Every UPB state in the library — Tiles, Pyramid, Parametrized, GenTiles1 and GenTiles2 — goes through it.

The rest are the small linear-algebra pieces the constructions need, written on plain NumPy so the package does not depend on a quantum-information toolbox: tensor, max_entangled, pauli, fourier, permute_systems, and partial_transpose with is_ppt for the PPT test, plus random_density_matrix for the random states. The test suite checks each of them entrywise against toqito.

References

ketbra

ketbra(a: ndarray, b: ndarray | None = None) -> np.ndarray

The outer product |a><b|.

Parameters:

Name Type Description Default
a ndarray

the "ket" vector.

required
b ndarray | None

the "bra" vector (its complex conjugate is used).

None

Returns:

Type Description
ndarray

the rank-1 operator |a><b|.

Source code in src/bound_entangled/utils/ketbra.py
def ketbra(a: np.ndarray, b: np.ndarray | None = None) -> np.ndarray:
    """The outer product |a><b|.

    Args:
        a: the "ket" vector.
        b: the "bra" vector (its complex conjugate is used).

    Returns:
        np.ndarray: the rank-1 operator |a><b|.
    """
    if b is None:
        b = a
    return np.outer(a, b.conj())

upb

upb(basis: list[ndarray]) -> np.ndarray

Bound entangled state built from an unextendible product basis (UPB).

The uniform mixture over the orthogonal complement of a UPB is PPT (each |v_i><v_i| being a product-state projector, partial transposition leaves it unchanged) yet has no product vector in its range, hence is entangled: a bound entangled state.

Reference: C. H. Bennett, D. P. DiVincenzo, T. Mor, P. W. Shor, J. A. Smolin, B. M. Terhal, "Unextendible Product Bases and Bound Entanglement", Phys. Rev. Lett. 82, 5385 (1999), https://arxiv.org/abs/quant-ph/9808030

Parameters:

Name Type Description Default
basis list[ndarray]

the product vectors (as column vectors) forming the UPB.

required

Returns:

Type Description
ndarray

the corresponding bound entangled density matrix.

Examples:

>>> from toqito.matrix_props import is_density
>>> from toqito.state_props import is_ppt, is_separable
>>> from bound_entangled.c3_otimes_c3.upb.pyramid_UPB import pyramid_basis
>>> state = upb(pyramid_basis())
>>> is_density(state)
True
>>> is_ppt(state, dim=[3, 3])
True
>>> sep, _ = is_separable(state, dim=[3, 3])
>>> sep
False

Every basis vector lies in the kernel, the defining property of the construction:

>>> import numpy as np
>>> bool(all(np.allclose(state @ v, 0) for v in pyramid_basis()))
True
Source code in src/bound_entangled/utils/upb.py
def upb(basis: list[np.ndarray]) -> np.ndarray:
    """Bound entangled state built from an unextendible product basis (UPB).

    The uniform mixture over the orthogonal complement of a UPB is PPT (each
    |v_i><v_i| being a product-state projector, partial transposition leaves
    it unchanged) yet has no product vector in its range, hence is entangled:
    a bound entangled state.

    Reference: C. H. Bennett, D. P. DiVincenzo, T. Mor, P. W. Shor, J. A.
    Smolin, B. M. Terhal, "Unextendible Product Bases and Bound Entanglement",
    Phys. Rev. Lett. 82, 5385 (1999), https://arxiv.org/abs/quant-ph/9808030

    Args:
        basis: the product vectors (as column vectors) forming the UPB.

    Returns:
        np.ndarray: the corresponding bound entangled density matrix.

    Examples:
        >>> from toqito.matrix_props import is_density
        >>> from toqito.state_props import is_ppt, is_separable
        >>> from bound_entangled.c3_otimes_c3.upb.pyramid_UPB import pyramid_basis
        >>> state = upb(pyramid_basis())
        >>> is_density(state)
        True
        >>> is_ppt(state, dim=[3, 3])
        True
        >>> sep, _ = is_separable(state, dim=[3, 3])
        >>> sep
        False

        Every basis vector lies in the kernel, the defining property of the
        construction:

        >>> import numpy as np
        >>> bool(all(np.allclose(state @ v, 0) for v in pyramid_basis()))
        True
    """
    d_total: int = basis[0].shape[0]
    rho = np.identity(d_total, dtype=np.complex128)
    for i in range(len(basis)):
        rho -= ketbra(basis[i])
    return rho / (d_total - len(basis))

tensor

tensor(*arrays: ndarray) -> np.ndarray

The tensor (Kronecker) product of the given vectors or matrices, left to right.

Parameters:

Name Type Description Default
*arrays ndarray

the factors, in order.

()

Returns:

Type Description
ndarray

arrays[0] ⊗ arrays[1] ⊗ ....

Examples:

>>> import numpy as np
>>> tensor(np.array([1, 0]), np.array([0, 1]))
array([0, 1, 0, 0])
Source code in src/bound_entangled/utils/tensor.py
def tensor(*arrays: np.ndarray) -> np.ndarray:
    """The tensor (Kronecker) product of the given vectors or matrices, left to right.

    Args:
        *arrays: the factors, in order.

    Returns:
        np.ndarray: ``arrays[0] ⊗ arrays[1] ⊗ ...``.

    Examples:
        >>> import numpy as np
        >>> tensor(np.array([1, 0]), np.array([0, 1]))
        array([0, 1, 0, 0])
    """
    if not arrays:
        raise ValueError("tensor needs at least one factor")
    return reduce(np.kron, arrays)

max_entangled

max_entangled(dim: int) -> np.ndarray

The maximally entangled state (1/sqrt(d)) sum_i |ii> of C^d ⊗ C^d.

Parameters:

Name Type Description Default
dim int

the local dimension d.

required

Returns:

Type Description
ndarray

the normalized state as a (d², 1) column vector.

Examples:

>>> max_entangled(2).ravel() * np.sqrt(2)
array([1., 0., 0., 1.])
Source code in src/bound_entangled/utils/max_entangled.py
def max_entangled(dim: int) -> np.ndarray:
    """The maximally entangled state (1/sqrt(d)) sum_i |ii> of C^d ⊗ C^d.

    Args:
        dim: the local dimension d.

    Returns:
        np.ndarray: the normalized state as a (d², 1) column vector.

    Examples:
        >>> max_entangled(2).ravel() * np.sqrt(2)
        array([1., 0., 0., 1.])
    """
    if dim < 1:
        raise ValueError("dim must be a positive integer")
    psi = np.zeros((dim * dim, 1))
    psi[np.arange(dim) * (dim + 1), 0] = 1 / np.sqrt(dim)
    return psi

pauli

pauli(ind: int | list[int]) -> np.ndarray

A Pauli matrix, or a tensor product of them.

Indices follow 0 = I, 1 = X, 2 = Y, 3 = Z.

Parameters:

Name Type Description Default
ind int | list[int]

one index, or a list of indices for the product sigma_{ind[0]} ⊗ sigma_{ind[1]} ⊗ ...

required

Returns:

Type Description
ndarray

the 2x2 Pauli matrix, or the 2^n x 2^n product.

Examples:

>>> pauli(3).real
array([[ 1.,  0.],
       [ 0., -1.]])
>>> pauli([1, 3]).shape
(4, 4)
Source code in src/bound_entangled/utils/pauli.py
def pauli(ind: int | list[int]) -> np.ndarray:
    """A Pauli matrix, or a tensor product of them.

    Indices follow 0 = I, 1 = X, 2 = Y, 3 = Z.

    Args:
        ind: one index, or a list of indices for the product
            sigma_{ind[0]} ⊗ sigma_{ind[1]} ⊗ ...

    Returns:
        np.ndarray: the 2x2 Pauli matrix, or the 2^n x 2^n product.

    Examples:
        >>> pauli(3).real
        array([[ 1.,  0.],
               [ 0., -1.]])
        >>> pauli([1, 3]).shape
        (4, 4)
    """
    if isinstance(ind, (list, tuple)):
        return tensor(*(pauli(i) for i in ind))
    if ind not in (0, 1, 2, 3):
        raise ValueError(f"Pauli index must be 0, 1, 2 or 3, got {ind}")
    return _PAULIS[ind].copy()

fourier

fourier(dim: int) -> np.ndarray

The d x d discrete Fourier transform matrix, with entries omega^(jk) / sqrt(d).

Parameters:

Name Type Description Default
dim int

the dimension d, with omega = exp(2 pi i / d).

required

Returns:

Type Description
ndarray

the unitary Fourier matrix.

Examples:

>>> u = fourier(3)
>>> bool(np.allclose(u @ u.conj().T, np.identity(3)))
True
Source code in src/bound_entangled/utils/fourier.py
def fourier(dim: int) -> np.ndarray:
    """The d x d discrete Fourier transform matrix, with entries omega^(jk) / sqrt(d).

    Args:
        dim: the dimension d, with omega = exp(2 pi i / d).

    Returns:
        np.ndarray: the unitary Fourier matrix.

    Examples:
        >>> u = fourier(3)
        >>> bool(np.allclose(u @ u.conj().T, np.identity(3)))
        True
    """
    k = np.arange(dim)
    return np.exp(2j * np.pi * np.outer(k, k) / dim) / np.sqrt(dim)

permute_systems

permute_systems(mat: ndarray, perm: list[int], dim: list[int]) -> np.ndarray

Reorder the subsystems of an operator on C^dim[0] ⊗ C^dim[1] ⊗ ...

Subsystem i of the result is subsystem perm[i] of mat, so perm = [0, 2, 1, 3] turns an ABA'B' ordering into AA'BB'.

Parameters:

Name Type Description Default
mat ndarray

a square matrix on the tensor product of the subsystems.

required
perm list[int]

the new order of the subsystems.

required
dim list[int]

the dimension of each subsystem, in the current order.

required

Returns:

Type Description
ndarray

the matrix with its subsystems reordered.

Examples:

Swapping the two factors of a product operator swaps the factors:

>>> import numpy as np
>>> a, b = np.diag([1.0, 2.0]), np.diag([1.0, 3.0, 5.0])
>>> bool(np.allclose(permute_systems(np.kron(a, b), [1, 0], [2, 3]), np.kron(b, a)))
True
Source code in src/bound_entangled/utils/permute_systems.py
def permute_systems(mat: np.ndarray, perm: list[int], dim: list[int]) -> np.ndarray:
    """Reorder the subsystems of an operator on C^dim[0] ⊗ C^dim[1] ⊗ ...

    Subsystem ``i`` of the result is subsystem ``perm[i]`` of ``mat``, so
    ``perm = [0, 2, 1, 3]`` turns an ABA'B' ordering into AA'BB'.

    Args:
        mat: a square matrix on the tensor product of the subsystems.
        perm: the new order of the subsystems.
        dim: the dimension of each subsystem, in the current order.

    Returns:
        np.ndarray: the matrix with its subsystems reordered.

    Examples:
        Swapping the two factors of a product operator swaps the factors:

        >>> import numpy as np
        >>> a, b = np.diag([1.0, 2.0]), np.diag([1.0, 3.0, 5.0])
        >>> bool(np.allclose(permute_systems(np.kron(a, b), [1, 0], [2, 3]), np.kron(b, a)))
        True
    """
    n = len(dim)
    if sorted(perm) != list(range(n)):
        raise ValueError(f"{perm} is not a permutation of the {n} subsystems")
    total = int(np.prod(dim))
    if mat.shape != (total, total):
        raise ValueError(f"matrix of shape {mat.shape} does not match subsystem dimensions {dim}")
    out = mat.reshape(list(dim) * 2).transpose(list(perm) + [n + p for p in perm])
    return out.reshape(total, total)

partial_transpose

partial_transpose(mat: ndarray, dim: list[int]) -> np.ndarray

The partial transpose of an operator on C^dim[0] ⊗ C^dim[1] over the second system.

Parameters:

Name Type Description Default
mat ndarray

a square matrix on C^dim[0] ⊗ C^dim[1].

required
dim list[int]

the two local dimensions [d_A, d_B].

required

Returns:

Type Description
ndarray

(1 ⊗ T)(mat).

Examples:

The partial transpose of the projector onto the two-qubit maximally entangled state is half the swap operator:

>>> import numpy as np
>>> phi = np.array([1, 0, 0, 1]) / np.sqrt(2)
>>> np.rint(partial_transpose(np.outer(phi, phi), [2, 2]) * 2).astype(int)
array([[1, 0, 0, 0],
       [0, 0, 1, 0],
       [0, 1, 0, 0],
       [0, 0, 0, 1]])
Source code in src/bound_entangled/utils/partial_transpose.py
def partial_transpose(mat: np.ndarray, dim: list[int]) -> np.ndarray:
    """The partial transpose of an operator on C^dim[0] ⊗ C^dim[1] over the second system.

    Args:
        mat: a square matrix on C^dim[0] ⊗ C^dim[1].
        dim: the two local dimensions [d_A, d_B].

    Returns:
        np.ndarray: (1 ⊗ T)(mat).

    Examples:
        The partial transpose of the projector onto the two-qubit maximally
        entangled state is half the swap operator:

        >>> import numpy as np
        >>> phi = np.array([1, 0, 0, 1]) / np.sqrt(2)
        >>> np.rint(partial_transpose(np.outer(phi, phi), [2, 2]) * 2).astype(int)
        array([[1, 0, 0, 0],
               [0, 0, 1, 0],
               [0, 1, 0, 0],
               [0, 0, 0, 1]])
    """
    d_a, d_b = dim
    if mat.shape != (d_a * d_b, d_a * d_b):
        raise ValueError(f"matrix of shape {mat.shape} does not match dimensions {dim}")
    return mat.reshape(d_a, d_b, d_a, d_b).transpose(0, 3, 2, 1).reshape(d_a * d_b, d_a * d_b)

is_ppt

is_ppt(mat: ndarray, dim: list[int], tol: float | None = None) -> bool

Whether a bipartite operator has a positive partial transpose.

Parameters:

Name Type Description Default
mat ndarray

a square matrix on C^dim[0] ⊗ C^dim[1].

required
dim list[int]

the two local dimensions [d_A, d_B].

required
tol float | None

eigenvalues down to -tol count as non-negative. Defaults to the square root of machine epsilon.

None

Returns:

Type Description
bool

True if every eigenvalue of the partial transpose is >= -tol.

Examples:

>>> import numpy as np
>>> phi = np.array([1, 0, 0, 1]) / np.sqrt(2)
>>> is_ppt(np.outer(phi, phi), [2, 2])
False
>>> is_ppt(np.identity(4) / 4, [2, 2])
True
Source code in src/bound_entangled/utils/partial_transpose.py
def is_ppt(mat: np.ndarray, dim: list[int], tol: float | None = None) -> bool:
    """Whether a bipartite operator has a positive partial transpose.

    Args:
        mat: a square matrix on C^dim[0] ⊗ C^dim[1].
        dim: the two local dimensions [d_A, d_B].
        tol: eigenvalues down to -tol count as non-negative. Defaults to the
            square root of machine epsilon.

    Returns:
        bool: True if every eigenvalue of the partial transpose is >= -tol.

    Examples:
        >>> import numpy as np
        >>> phi = np.array([1, 0, 0, 1]) / np.sqrt(2)
        >>> is_ppt(np.outer(phi, phi), [2, 2])
        False
        >>> is_ppt(np.identity(4) / 4, [2, 2])
        True
    """
    if tol is None:
        tol = float(np.sqrt(np.finfo(float).eps))
    pt = partial_transpose(mat, dim)
    return bool(np.linalg.eigvalsh((pt + pt.conj().T) / 2).min() >= -tol)

random_density_matrix

random_density_matrix(dim: int, seed: int | None = None) -> np.ndarray

A random density matrix drawn from the Hilbert-Schmidt measure.

Draws a complex Ginibre matrix G with standard normal entries and returns G G^dagger / tr(G G^dagger).

Parameters:

Name Type Description Default
dim int

the dimension of the density matrix.

required
seed int | None

seed for the random number generator, for reproducible draws.

None

Returns:

Type Description
ndarray

a dim x dim density matrix.

Examples:

>>> import numpy as np
>>> rho = random_density_matrix(4, seed=0)
>>> bool(np.isclose(np.trace(rho).real, 1)), bool(np.linalg.eigvalsh(rho).min() >= 0)
(True, True)
Source code in src/bound_entangled/utils/random_density_matrix.py
def random_density_matrix(dim: int, seed: int | None = None) -> np.ndarray:
    """A random density matrix drawn from the Hilbert-Schmidt measure.

    Draws a complex Ginibre matrix G with standard normal entries and returns
    G G^dagger / tr(G G^dagger).

    Args:
        dim: the dimension of the density matrix.
        seed: seed for the random number generator, for reproducible draws.

    Returns:
        np.ndarray: a dim x dim density matrix.

    Examples:
        >>> import numpy as np
        >>> rho = random_density_matrix(4, seed=0)
        >>> bool(np.isclose(np.trace(rho).real, 1)), bool(np.linalg.eigvalsh(rho).min() >= 0)
        (True, True)
    """
    gen = np.random.default_rng(seed)
    gin = gen.standard_normal((dim, dim)) + 1j * gen.standard_normal((dim, dim))
    rho = gin @ gin.conj().T
    return rho / np.trace(rho)