Skip to content

psiqit.info

Auto-generated documentation for the psiqit.info module.

psiqit.info

PSIQIT - Python Scientific Quantum Information Toolkit Information Theory Module

This module provides quantum information theory tools including entropy measures and entanglement measures.

Submodules:

entropy.py - Entropy measures (Shannon, von Neumann, Rényi, etc.) entanglement.py - Entanglement measures (concurrence, negativity, etc.)

EntanglementResult dataclass

Result container for entanglement measures

Attributes:

Name Type Description
value float

Numerical value of the entanglement measure

measure str

Name of the measure used

is_entangled bool

Whether the state is entangled

details Dict[str, Any]

Additional information

dims Optional[List[int]]

Subsystem dimensions

Source code in psiqit\info\entanglement.py
@dataclass
class EntanglementResult:
    """
    Result container for entanglement measures

    Attributes:
        value: Numerical value of the entanglement measure
        measure: Name of the measure used
        is_entangled: Whether the state is entangled
        details: Additional information
        dims: Subsystem dimensions
    """
    value: float = 0.0
    measure: str = ""
    is_entangled: bool = False
    details: Dict[str, Any] = field(default_factory=dict)
    dims: Optional[List[int]] = None

    def __repr__(self) -> str:
        return f"EntanglementResult(value={self.value:.6f}, measure={self.measure}, is_entangled={self.is_entangled})"

    def __str__(self) -> str:
        lines = [
            "Entanglement Results:",
            f"  Measure: {self.measure}",
            f"  Value: {self.value:.6f}",
            f"  Is Entangled: {self.is_entangled}",
        ]
        if self.dims:
            lines.append(f"  Dimensions: {self.dims}")
        if self.details:
            lines.append(f"  Details: {self.details}")
        return "\n".join(lines)

shannon_entropy(probabilities, base='e')

Compute Shannon entropy of a probability distribution

H = -Σ p_i log(p_i)

Parameters:

Name Type Description Default
probabilities ndarray

Probability distribution (must sum to 1)

required
base str

Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

'e'

Returns:

Name Type Description
float float

Shannon entropy

Example

probs = [0.5, 0.5] print(shannon_entropy(probs)) # 0.693147... print(shannon_entropy(probs, base='2')) # 1.0

Source code in psiqit\info\entropy.py
def shannon_entropy(probabilities: np.ndarray, base: str = 'e') -> float:
    """
    Compute Shannon entropy of a probability distribution

    H = -Σ p_i log(p_i)

    Args:
        probabilities: Probability distribution (must sum to 1)
        base: Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

    Returns:
        float: Shannon entropy

    Example:
        >>> probs = [0.5, 0.5]
        >>> print(shannon_entropy(probs))  # 0.693147...
        >>> print(shannon_entropy(probs, base='2'))  # 1.0
    """
    probs = np.array(probabilities, dtype=float)

    # Normalize if needed
    total = np.sum(probs)
    if total > 0 and abs(total - 1.0) > 1e-10:
        probs = probs / total
        logger.debug("Probabilities normalized to sum to 1")

    # Remove zero probabilities
    probs = probs[probs > 0]

    if len(probs) == 0:
        return 0.0

    # Choose logarithm
    log_func = {'e': np.log, '2': np.log2, '10': np.log10}.get(base)
    if log_func is None:
        raise ValueError(f"Unknown base: {base}. Use 'e', '2', or '10'")

    entropy = -np.sum(probs * log_func(probs))
    return float(entropy)

von_neumann_entropy(rho, base='e')

Compute von Neumann entropy of a density matrix

S(ρ) = -Tr(ρ log ρ)

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required
base str

Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

'e'

Returns:

Name Type Description
float float

von Neumann entropy

Source code in psiqit\info\entropy.py
def von_neumann_entropy(rho: Union[np.ndarray, Matrix], base: str = 'e') -> float:
    """
    Compute von Neumann entropy of a density matrix

    S(ρ) = -Tr(ρ log ρ)

    Args:
        rho: Density matrix
        base: Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

    Returns:
        float: von Neumann entropy
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    # Check if valid density matrix (skip is_positive check for numpy arrays)
    if isinstance(rho, Matrix) and not rho.is_square:
        logger.warning("Matrix is not square")

    # Compute eigenvalues
    eigvals = np.linalg.eigvalsh(rho_data)
    eigvals = eigvals[eigvals > 1e-12]

    if len(eigvals) == 0:
        return 0.0

    # Choose logarithm
    log_func = {'e': np.log, '2': np.log2, '10': np.log10}.get(base)
    if log_func is None:
        raise ValueError(f"Unknown base: {base}. Use 'e', '2', or '10'")

    entropy = -np.sum(eigvals * log_func(eigvals))
    return float(entropy)

renyi_entropy(rho, alpha=2, base='e')

Compute Rényi entropy of order α

S_α(ρ) = (1/(1-α)) log(Tr(ρ^α))

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required
alpha float

Order parameter (α > 0, α ≠ 1)

2
base str

Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

'e'

Returns:

Name Type Description
float float

Rényi entropy

Example

rho = np.array([[0.5, 0], [0, 0.5]]) print(renyi_entropy(rho, alpha=2)) # 0.693147...

Source code in psiqit\info\entropy.py
def renyi_entropy(
    rho: Union[np.ndarray, Matrix],
    alpha: float = 2,
    base: str = 'e'
) -> float:
    """
    Compute Rényi entropy of order α

    S_α(ρ) = (1/(1-α)) log(Tr(ρ^α))

    Args:
        rho: Density matrix
        alpha: Order parameter (α > 0, α ≠ 1)
        base: Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

    Returns:
        float: Rényi entropy

    Example:
        >>> rho = np.array([[0.5, 0], [0, 0.5]])
        >>> print(renyi_entropy(rho, alpha=2))  # 0.693147...
    """
    if alpha <= 0:
        raise ValueError(f"Alpha must be positive, got {alpha}")

    if abs(alpha - 1.0) < 1e-12:
        # α → 1 gives von Neumann entropy
        return von_neumann_entropy(rho, base)

    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    # Compute eigenvalues
    eigvals = np.linalg.eigvalsh(rho_data)
    eigvals = eigvals[eigvals > 1e-12]

    if len(eigvals) == 0:
        return 0.0

    # Tr(ρ^α) = Σ λ_i^α
    trace_alpha = np.sum(eigvals ** alpha)

    # Choose logarithm
    log_func = {'e': np.log, '2': np.log2, '10': np.log10}.get(base)
    if log_func is None:
        raise ValueError(f"Unknown base: {base}. Use 'e', '2', or '10'")

    entropy = (1 / (1 - alpha)) * log_func(trace_alpha)
    return float(entropy)

collision_entropy(rho, base='e')

Compute collision entropy (Rényi entropy of order 2)

S_2(ρ) = -log(Tr(ρ^2))

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required
base str

Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

'e'

Returns:

Name Type Description
float float

Collision entropy

Example

rho = np.array([[0.5, 0], [0, 0.5]]) print(collision_entropy(rho)) # 0.693147...

Source code in psiqit\info\entropy.py
def collision_entropy(rho: Union[np.ndarray, Matrix], base: str = 'e') -> float:
    """
    Compute collision entropy (Rényi entropy of order 2)

    S_2(ρ) = -log(Tr(ρ^2))

    Args:
        rho: Density matrix
        base: Logarithm base: 'e' (natural), '2' (bits), or '10' (dits)

    Returns:
        float: Collision entropy

    Example:
        >>> rho = np.array([[0.5, 0], [0, 0.5]])
        >>> print(collision_entropy(rho))  # 0.693147...
    """
    return renyi_entropy(rho, alpha=2, base=base)

partial_trace(matrix, dims, keep)

Compute partial trace of a bipartite or multipartite system

Parameters:

Name Type Description Default
matrix Union[ndarray, Matrix]

Full density matrix (or operator)

required
dims List[int]

List of subsystem dimensions

required
keep List[int]

List of subsystem indices to keep (trace out the rest)

required

Returns:

Type Description
ndarray

np.ndarray: Reduced density matrix

Example

2-qubit system: dims = [2, 2]

rho = np.array([[0.5, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0.5]]) rho_a = partial_trace(rho, [2, 2], [0]) print(rho_a) # Reduced state of first qubit

Source code in psiqit\info\entropy.py
def partial_trace(
    matrix: Union[np.ndarray, Matrix],
    dims: List[int],
    keep: List[int]
) -> np.ndarray:
    """
    Compute partial trace of a bipartite or multipartite system

    Args:
        matrix: Full density matrix (or operator)
        dims: List of subsystem dimensions
        keep: List of subsystem indices to keep (trace out the rest)

    Returns:
        np.ndarray: Reduced density matrix

    Example:
        >>> # 2-qubit system: dims = [2, 2]
        >>> rho = np.array([[0.5, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0.5]])
        >>> rho_a = partial_trace(rho, [2, 2], [0])
        >>> print(rho_a)  # Reduced state of first qubit
    """
    if isinstance(matrix, Matrix):
        mat = matrix.data
    else:
        mat = np.array(matrix, dtype=complex)

    n_subsystems = len(dims)
    total_dim = np.prod(dims)

    if mat.shape != (total_dim, total_dim):
        raise ValueError(f"Matrix shape {mat.shape} does not match dimensions {dims}")

    # Determine which subsystems to keep
    if not keep:
        return np.array([[1.0]])

    # For bipartite systems (2 subsystems)
    if n_subsystems == 2:
        dim_a, dim_b = dims

        if keep == [0]:
            # Keep subsystem A, trace out B
            rho_reduced = np.zeros((dim_a, dim_a), dtype=complex)
            for i in range(dim_b):
                # Create basis state |i⟩_B
                ket_i = np.zeros((dim_b, 1), dtype=complex)
                ket_i[i, 0] = 1.0
                bra_i = ket_i.conj().T

                # Partial trace: ⟨i|_B ρ |i⟩_B
                # Reshape ρ as (dim_a, dim_b, dim_a, dim_b)
                rho_reshaped = mat.reshape(dim_a, dim_b, dim_a, dim_b)

                # Take elements where B indices are i
                rho_reduced += rho_reshaped[:, i, :, i]
            return rho_reduced

        elif keep == [1]:
            # Keep subsystem B, trace out A
            rho_reduced = np.zeros((dim_b, dim_b), dtype=complex)
            for i in range(dim_a):
                # Create basis state |i⟩_A
                ket_i = np.zeros((dim_a, 1), dtype=complex)
                ket_i[i, 0] = 1.0
                bra_i = ket_i.conj().T

                # Partial trace: ⟨i|_A ρ |i⟩_A
                rho_reshaped = mat.reshape(dim_a, dim_b, dim_a, dim_b)
                rho_reduced += rho_reshaped[i, :, i, :]
            return rho_reduced

        else:
            raise ValueError(f"Invalid keep indices: {keep}. For bipartite, use [0] or [1]")

    # For multipartite systems (3 or more subsystems)
    # This is a more general implementation
    # We'll use the method of tracing out subsystems one by one

    # Start with the full matrix
    result = mat.copy()
    current_dims = dims.copy()

    # Trace out subsystems from the end
    for idx in sorted(trace_out, reverse=True):
        dim = current_dims[idx]

        # Reshape to separate the subsystem to trace
        # This is complex for general cases, so we use a simpler approach
        # For now, we only support bipartite systems
        raise NotImplementedError("Partial trace for multipartite systems (n>2) is not fully implemented")

    return result

mutual_information(rho_ab, dim_a, dim_b, base='e')

Compute mutual information between two subsystems

I(A:B) = S(ρ_A) + S(ρ_B) - S(ρ_AB)

Parameters:

Name Type Description Default
rho_ab Union[ndarray, Matrix]

Joint density matrix of system AB

required
dim_a int

Dimension of subsystem A

required
dim_b int

Dimension of subsystem B

required
base str

Logarithm base

'e'

Returns:

Name Type Description
float float

Mutual information

Source code in psiqit\info\entropy.py
def mutual_information(
    rho_ab: Union[np.ndarray, Matrix],
    dim_a: int,
    dim_b: int,
    base: str = 'e'
) -> float:
    """
    Compute mutual information between two subsystems

    I(A:B) = S(ρ_A) + S(ρ_B) - S(ρ_AB)

    Args:
        rho_ab: Joint density matrix of system AB
        dim_a: Dimension of subsystem A
        dim_b: Dimension of subsystem B
        base: Logarithm base

    Returns:
        float: Mutual information
    """
    if isinstance(rho_ab, Matrix):
        rho_data = rho_ab.data
    else:
        rho_data = np.array(rho_ab, dtype=complex)

    # Compute reduced density matrices using partial_trace
    rho_a = partial_trace(rho_data, [dim_a, dim_b], [0])
    rho_b = partial_trace(rho_data, [dim_a, dim_b], [1])

    # Compute entropies
    S_ab = von_neumann_entropy(rho_data, base)
    S_a = von_neumann_entropy(rho_a, base)
    S_b = von_neumann_entropy(rho_b, base)

    # Mutual information
    MI = S_a + S_b - S_ab

    return float(MI)

relative_entropy(rho, sigma, base='e')

Compute quantum relative entropy

S(ρ||σ) = Tr(ρ log ρ - ρ log σ)

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

First density matrix

required
sigma Union[ndarray, Matrix]

Second density matrix

required
base str

Logarithm base

'e'

Returns:

Name Type Description
float float

Relative entropy

Example

rho = np.array([[0.5, 0], [0, 0.5]]) sigma = np.array([[0.8, 0], [0, 0.2]]) print(relative_entropy(rho, sigma))

Source code in psiqit\info\entropy.py
def relative_entropy(
    rho: Union[np.ndarray, Matrix],
    sigma: Union[np.ndarray, Matrix],
    base: str = 'e'
) -> float:
    """
    Compute quantum relative entropy

    S(ρ||σ) = Tr(ρ log ρ - ρ log σ)

    Args:
        rho: First density matrix
        sigma: Second density matrix
        base: Logarithm base

    Returns:
        float: Relative entropy

    Example:
        >>> rho = np.array([[0.5, 0], [0, 0.5]])
        >>> sigma = np.array([[0.8, 0], [0, 0.2]])
        >>> print(relative_entropy(rho, sigma))
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    if isinstance(sigma, Matrix):
        sigma_data = sigma.data
    else:
        sigma_data = np.array(sigma, dtype=complex)

    # Compute eigenvalues
    eigvals_rho = np.linalg.eigvalsh(rho_data)
    eigvals_rho = eigvals_rho[eigvals_rho > 1e-12]

    eigvals_sigma = np.linalg.eigvalsh(sigma_data)
    eigvals_sigma = eigvals_sigma[eigvals_sigma > 1e-12]

    # Choose logarithm
    log_func = {'e': np.log, '2': np.log2, '10': np.log10}.get(base)
    if log_func is None:
        raise ValueError(f"Unknown base: {base}. Use 'e', '2', or '10'")

    # Compute relative entropy
    # For density matrices that commute, we can use the eigenvalues
    # For non-commuting, we need the full matrix logarithm
    # This is a simplified version

    # Check if matrices commute
    commutator = rho_data @ sigma_data - sigma_data @ rho_data
    if np.allclose(commutator, 0):
        # They commute, use eigenvalues
        # We need to align the eigenvalues (simplified)
        # This is a placeholder
        rel_ent = 0.0
        for i, lam_i in enumerate(eigvals_rho):
            for j, lam_j in enumerate(eigvals_sigma):
                if i == j:  # Simplified alignment
                    rel_ent += lam_i * (log_func(lam_i) - log_func(lam_j))
        return float(rel_ent)
    else:
        # General case: S(ρ||σ) = Tr(ρ log ρ) - Tr(ρ log σ)
        # We need the full matrix logarithm
        # This is more computationally intensive

        # Compute log of sigma
        try:
            log_sigma = np.linalg.logm(sigma_data)
            log_rho = np.linalg.logm(rho_data)

            # Compute trace
            term1 = np.trace(rho_data @ log_rho)
            term2 = np.trace(rho_data @ log_sigma)

            rel_ent = (term1 - term2).real
            return float(rel_ent)
        except:
            logger.warning("Could not compute matrix logarithm, using simplified method")
            return 0.0

purity(rho)

Compute purity of a density matrix

P(ρ) = Tr(ρ²)

For pure states, purity = 1. For maximally mixed states, purity = 1/dim.

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required

Returns:

Name Type Description
float float

Purity (0-1)

Example

rho = np.array([[1, 0], [0, 0]]) # Pure state print(purity(rho)) # 1.0 rho = np.array([[0.5, 0], [0, 0.5]]) # Maximally mixed print(purity(rho)) # 0.5

Source code in psiqit\info\entropy.py
def purity(rho: Union[np.ndarray, Matrix]) -> float:
    """
    Compute purity of a density matrix

    P(ρ) = Tr(ρ²)

    For pure states, purity = 1.
    For maximally mixed states, purity = 1/dim.

    Args:
        rho: Density matrix

    Returns:
        float: Purity (0-1)

    Example:
        >>> rho = np.array([[1, 0], [0, 0]])  # Pure state
        >>> print(purity(rho))  # 1.0
        >>> rho = np.array([[0.5, 0], [0, 0.5]])  # Maximally mixed
        >>> print(purity(rho))  # 0.5
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    # Tr(ρ²)
    rho_squared = rho_data @ rho_data
    p = np.trace(rho_squared).real

    return float(p)

linear_entropy(rho)

Compute linear entropy

S_L(ρ) = 1 - Tr(ρ²)

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required

Returns:

Name Type Description
float float

Linear entropy (0-1)

Source code in psiqit\info\entropy.py
def linear_entropy(rho: Union[np.ndarray, Matrix]) -> float:
    """
    Compute linear entropy

    S_L(ρ) = 1 - Tr(ρ²)

    Args:
        rho: Density matrix

    Returns:
        float: Linear entropy (0-1)
    """
    p = purity(rho)
    return 1 - p

min_entropy(rho)

Compute min-entropy (Rényi entropy of order ∞)

S_∞(ρ) = -log(λ_max)

where λ_max is the maximum eigenvalue.

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required

Returns:

Name Type Description
float float

Min-entropy

Source code in psiqit\info\entropy.py
def min_entropy(rho: Union[np.ndarray, Matrix]) -> float:
    """
    Compute min-entropy (Rényi entropy of order ∞)

    S_∞(ρ) = -log(λ_max)

    where λ_max is the maximum eigenvalue.

    Args:
        rho: Density matrix

    Returns:
        float: Min-entropy
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    eigvals = np.linalg.eigvalsh(rho_data)
    lambda_max = np.max(eigvals)

    if lambda_max <= 0:
        return np.inf

    return -np.log(lambda_max)

max_entropy(rho)

Compute max-entropy

S_max(ρ) = log(dim) - S_min(ρ)

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required

Returns:

Name Type Description
float float

Max-entropy

Source code in psiqit\info\entropy.py
def max_entropy(rho: Union[np.ndarray, Matrix]) -> float:
    """
    Compute max-entropy

    S_max(ρ) = log(dim) - S_min(ρ)

    Args:
        rho: Density matrix

    Returns:
        float: Max-entropy
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    dim = rho_data.shape[0]
    s_min = min_entropy(rho)

    if np.isinf(s_min):
        return np.inf

    return np.log(dim) - s_min

concurrence_pure(state, dims=None)

Compute concurrence for a pure state

For a pure state |ψ⟩, concurrence = 2 * sqrt(det(ρ_A)) where ρ_A is the reduced density matrix.

Parameters:

Name Type Description Default
state Union[Ket, ndarray]

Pure state (Ket or array)

required
dims Optional[List[int]]

Subsystem dimensions [dim_A, dim_B] (default: [2, 2])

None

Returns:

Name Type Description
float float

Concurrence (0-1)

Example

from psiqit.quantum import bell_phi_plus concurrence = concurrence_pure(bell_phi_plus()) print(concurrence) # 1.0

Source code in psiqit\info\entanglement.py
def concurrence_pure(
    state: Union[Ket, np.ndarray],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute concurrence for a pure state

    For a pure state |ψ⟩, concurrence = 2 * sqrt(det(ρ_A))
    where ρ_A is the reduced density matrix.

    Args:
        state: Pure state (Ket or array)
        dims: Subsystem dimensions [dim_A, dim_B] (default: [2, 2])

    Returns:
        float: Concurrence (0-1)

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> concurrence = concurrence_pure(bell_phi_plus())
        >>> print(concurrence)  # 1.0
    """
    if isinstance(state, Ket):
        state_data = state.data
    else:
        state_data = np.array(state, dtype=complex)

    # Default dimensions for bipartite systems
    if dims is None:
        dim = len(state_data)
        # Check if dimension is a power of 2
        n_qubits = int(np.log2(dim))
        if 2 ** n_qubits == dim:
            dim_a = 2 ** (n_qubits // 2)
            dim_b = dim // dim_a
            dims = [dim_a, dim_b]
        else:
            # Assume equal division
            dim_a = int(np.sqrt(dim))
            dim_b = dim // dim_a
            dims = [dim_a, dim_b]

    if len(dims) != 2:
        raise ValueError("Concurrence currently only supports bipartite systems")

    dim_a, dim_b = dims

    # Compute reduced density matrix
    rho = np.outer(state_data, state_data.conj())
    rho_a = np.zeros((dim_a, dim_a), dtype=complex)

    # Partial trace over subsystem B
    for i in range(dim_a):
        for j in range(dim_a):
            for k in range(dim_b):
                idx_i = i * dim_b + k
                idx_j = j * dim_b + k
                rho_a[i, j] += rho[idx_i, idx_j]

    # Concurrence = sqrt(2 * (1 - Tr(ρ_A²)))
    purity_a = np.trace(rho_a @ rho_a).real
    concurrence = np.sqrt(max(0, 2 * (1 - purity_a)))

    return float(concurrence)

concurrence_mixed(rho, dims=None)

Compute concurrence for a mixed state (Wootters formula)

For two-qubit systems, concurrence = max(0, λ₁ - λ₂ - λ₃ - λ₄) where λ_i are the square roots of eigenvalues of ρ(σ_y⊗σ_y)ρ*(σ_y⊗σ_y)

Parameters:

Name Type Description Default
rho Union[ndarray, Matrix]

Density matrix

required
dims Optional[List[int]]

Subsystem dimensions (default: [2, 2])

None

Returns:

Name Type Description
float float

Concurrence (0-1)

Example

rho = np.array([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) concurrence = concurrence_mixed(rho) print(concurrence) # 1.0

Source code in psiqit\info\entanglement.py
def concurrence_mixed(
    rho: Union[np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute concurrence for a mixed state (Wootters formula)

    For two-qubit systems, concurrence = max(0, λ₁ - λ₂ - λ₃ - λ₄)
    where λ_i are the square roots of eigenvalues of ρ(σ_y⊗σ_y)ρ*(σ_y⊗σ_y)

    Args:
        rho: Density matrix
        dims: Subsystem dimensions (default: [2, 2])

    Returns:
        float: Concurrence (0-1)

    Example:
        >>> rho = np.array([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
        >>> concurrence = concurrence_mixed(rho)
        >>> print(concurrence)  # 1.0
    """
    if isinstance(rho, Matrix):
        rho_data = rho.data
    else:
        rho_data = np.array(rho, dtype=complex)

    # Default to two-qubit system
    if dims is None:
        dims = [2, 2]

    if len(dims) != 2 or dims[0] != 2 or dims[1] != 2:
        raise ValueError("Mixed concurrence currently only supports 2-qubit systems")

    # Pauli-Y matrix
    sigma_y = np.array([[0, -1j], [1j, 0]], dtype=complex)
    sigma_y_sigma_y = np.kron(sigma_y, sigma_y)

    # Compute R = ρ (σ_y⊗σ_y) ρ* (σ_y⊗σ_y)
    rho_conj = np.conj(rho_data)
    R = rho_data @ sigma_y_sigma_y @ rho_conj @ sigma_y_sigma_y

    # Eigenvalues of R
    eigvals = np.linalg.eigvals(R)
    eigvals = np.real(eigvals)
    eigvals = eigvals[eigvals > 1e-12]

    # Sort in descending order
    eigvals = np.sort(eigvals)[::-1]
    lambda_sqrt = np.sqrt(eigvals)

    # Concurrence = max(0, λ₁ - λ₂ - λ₃ - λ₄)
    if len(lambda_sqrt) >= 4:
        concurrence = max(0, lambda_sqrt[0] - lambda_sqrt[1] - lambda_sqrt[2] - lambda_sqrt[3])
    else:
        # Not enough eigenvalues, use simplified formula
        concurrence = max(0, np.sum(lambda_sqrt) - 2 * np.max(lambda_sqrt))

    return float(min(concurrence, 1.0))

concurrence(state_or_rho, dims=None)

Compute concurrence for a state (pure or mixed)

Automatically detects if the input is pure or mixed.

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None

Returns:

Name Type Description
float float

Concurrence (0-1)

Example

from psiqit.quantum import bell_phi_plus concurrence(bell_phi_plus()) # 1.0

Source code in psiqit\info\entanglement.py
def concurrence(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute concurrence for a state (pure or mixed)

    Automatically detects if the input is pure or mixed.

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions

    Returns:
        float: Concurrence (0-1)

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> concurrence(bell_phi_plus())  # 1.0
    """
    # Check if it's a density matrix (square matrix)
    if isinstance(state_or_rho, Matrix):
        data = state_or_rho.data
    else:
        data = np.array(state_or_rho, dtype=complex)

    if len(data.shape) == 2 and data.shape[0] == data.shape[1]:
        # It's a density matrix
        # Check if it's a pure state (rank 1)
        eigvals = np.linalg.eigvalsh(data)
        if np.sum(eigvals > 1e-10) <= 1:
            # Pure state, convert to ket
            # Get the dominant eigenvector
            eigvals, eigvecs = np.linalg.eigh(data)
            idx = np.argmax(eigvals)
            state = Ket(eigvecs[:, idx])
            return concurrence_pure(state, dims)
        else:
            return concurrence_mixed(data, dims)
    else:
        # It's a state vector
        return concurrence_pure(state_or_rho, dims)

negativity(state_or_rho, dims=None)

Compute negativity of a quantum state

N(ρ) = (||ρ^{T_A}||₁ - 1) / 2

where ρ^{T_A} is the partial transpose with respect to subsystem A.

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None

Returns:

Name Type Description
float float

Negativity (0-1)

Example

from psiqit.quantum import bell_phi_plus neg = negativity(bell_phi_plus()) print(neg) # 0.5

Source code in psiqit\info\entanglement.py
def negativity(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute negativity of a quantum state

    N(ρ) = (||ρ^{T_A}||₁ - 1) / 2

    where ρ^{T_A} is the partial transpose with respect to subsystem A.

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions

    Returns:
        float: Negativity (0-1)

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> neg = negativity(bell_phi_plus())
        >>> print(neg)  # 0.5
    """
    # Convert to density matrix
    if isinstance(state_or_rho, Ket) or (isinstance(state_or_rho, np.ndarray) and len(state_or_rho.shape) == 1):
        # Pure state
        if isinstance(state_or_rho, Ket):
            state_data = state_or_rho.data
        else:
            state_data = state_or_rho
        rho = np.outer(state_data, state_data.conj())
    else:
        # Density matrix
        if isinstance(state_or_rho, Matrix):
            rho = state_or_rho.data
        else:
            rho = np.array(state_or_rho, dtype=complex)

    # Default dimensions for bipartite systems
    if dims is None:
        dim = rho.shape[0]
        # Check if dimension is a power of 2
        n_qubits = int(np.log2(dim))
        if 2 ** n_qubits == dim:
            dim_a = 2 ** (n_qubits // 2)
            dim_b = dim // dim_a
            dims = [dim_a, dim_b]
        else:
            # Assume equal division
            dim_a = int(np.sqrt(dim))
            dim_b = dim // dim_a
            dims = [dim_a, dim_b]

    if len(dims) != 2:
        raise ValueError("Negativity currently only supports bipartite systems")

    dim_a, dim_b = dims

    # Partial transpose with respect to subsystem A
    rho_pt = np.zeros_like(rho)

    # Reshape to (dim_a, dim_b, dim_a, dim_b)
    rho_reshaped = rho.reshape(dim_a, dim_b, dim_a, dim_b)

    # Transpose subsystem A: (i, j, k, l) -> (k, j, i, l)
    rho_pt_reshaped = np.einsum('ijkl->kjil', rho_reshaped)

    # Reshape back
    rho_pt = rho_pt_reshaped.reshape(dim_a * dim_b, dim_a * dim_b)

    # Compute trace norm: ||ρ^{T_A}||₁ = sum of singular values
    singular_values = np.linalg.svd(rho_pt, compute_uv=False)
    trace_norm = np.sum(singular_values)

    # Negativity = (||ρ^{T_A}||₁ - 1) / 2
    neg = max(0, (trace_norm - 1) / 2)

    return float(neg)

logarithmic_negativity(state_or_rho, dims=None)

Compute logarithmic negativity

E_N(ρ) = log₂(||ρ^{T_A}||₁)

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None

Returns:

Name Type Description
float float

Logarithmic negativity

Example

from psiqit.quantum import bell_phi_plus log_neg = logarithmic_negativity(bell_phi_plus()) print(log_neg) # 1.0

Source code in psiqit\info\entanglement.py
def logarithmic_negativity(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute logarithmic negativity

    E_N(ρ) = log₂(||ρ^{T_A}||₁)

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions

    Returns:
        float: Logarithmic negativity

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> log_neg = logarithmic_negativity(bell_phi_plus())
        >>> print(log_neg)  # 1.0
    """
    # Compute negativity
    neg = negativity(state_or_rho, dims)

    # Log negativity = log₂(2*neg + 1)
    log_neg = np.log2(2 * neg + 1)

    return float(log_neg)

entanglement_entropy(state_or_rho, dims, base='e')

Compute entanglement entropy (von Neumann entropy of reduced state)

S_E(ρ) = S(ρ_A) = -Tr(ρ_A log ρ_A)

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims List[int]

Subsystem dimensions [dim_A, dim_B]

required
base str

Logarithm base

'e'

Returns:

Name Type Description
float float

Entanglement entropy

Example

from psiqit.quantum import bell_phi_plus S_E = entanglement_entropy(bell_phi_plus(), [2, 2]) print(S_E) # 0.693147...

Source code in psiqit\info\entanglement.py
def entanglement_entropy(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: List[int],
    base: str = 'e'
) -> float:
    """
    Compute entanglement entropy (von Neumann entropy of reduced state)

    S_E(ρ) = S(ρ_A) = -Tr(ρ_A log ρ_A)

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions [dim_A, dim_B]
        base: Logarithm base

    Returns:
        float: Entanglement entropy

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> S_E = entanglement_entropy(bell_phi_plus(), [2, 2])
        >>> print(S_E)  # 0.693147...
    """
    # Convert to density matrix
    if isinstance(state_or_rho, Ket) or (isinstance(state_or_rho, np.ndarray) and len(state_or_rho.shape) == 1):
        # Pure state
        if isinstance(state_or_rho, Ket):
            state_data = state_or_rho.data
        else:
            state_data = state_or_rho
        rho = np.outer(state_data, state_data.conj())
    else:
        # Density matrix
        if isinstance(state_or_rho, Matrix):
            rho = state_or_rho.data
        else:
            rho = np.array(state_or_rho, dtype=complex)

    if len(dims) != 2:
        raise ValueError("Entanglement entropy currently only supports bipartite systems")

    dim_a, dim_b = dims

    # Compute reduced density matrix
    rho_a = np.zeros((dim_a, dim_a), dtype=complex)

    for i in range(dim_a):
        for j in range(dim_a):
            for k in range(dim_b):
                idx_i = i * dim_b + k
                idx_j = j * dim_b + k
                rho_a[i, j] += rho[idx_i, idx_j]

    # Compute von Neumann entropy
    from .entropy import von_neumann_entropy
    return von_neumann_entropy(rho_a, base)

schmidt_decomposition(state, dims)

Compute Schmidt decomposition of a bipartite pure state

|ψ⟩ = Σ_i λ_i |i⟩_A ⊗ |i⟩_B

Parameters:

Name Type Description Default
state Union[Ket, ndarray]

Pure state

required
dims List[int]

Subsystem dimensions [dim_A, dim_B]

required

Returns:

Name Type Description
Dict Dict[str, Any]

Schmidt coefficients, Schmidt vectors, and rank

Example

from psiqit.quantum import bell_phi_plus result = schmidt_decomposition(bell_phi_plus(), [2, 2]) print(result['coefficients']) # [0.707, 0.707]

Source code in psiqit\info\entanglement.py
def schmidt_decomposition(
    state: Union[Ket, np.ndarray],
    dims: List[int]
) -> Dict[str, Any]:
    """
    Compute Schmidt decomposition of a bipartite pure state

    |ψ⟩ = Σ_i λ_i |i⟩_A ⊗ |i⟩_B

    Args:
        state: Pure state
        dims: Subsystem dimensions [dim_A, dim_B]

    Returns:
        Dict: Schmidt coefficients, Schmidt vectors, and rank

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> result = schmidt_decomposition(bell_phi_plus(), [2, 2])
        >>> print(result['coefficients'])  # [0.707, 0.707]
    """
    if isinstance(state, Ket):
        state_data = state.data
    else:
        state_data = np.array(state, dtype=complex)

    if len(dims) != 2:
        raise ValueError("Schmidt decomposition currently only supports bipartite systems")

    dim_a, dim_b = dims

    # Reshape state into a matrix
    # |ψ⟩ = Σ_{i,j} A_{i,j} |i⟩_A ⊗ |j⟩_B
    A = state_data.reshape(dim_a, dim_b)

    # Compute Schmidt decomposition: A = U Σ V†
    U, S, Vh = np.linalg.svd(A, full_matrices=False)

    # Schmidt coefficients (normalized)
    coeffs = S / np.sqrt(np.sum(S ** 2))

    # Schmidt vectors
    schmidt_a = [Ket(U[:, i]) for i in range(len(coeffs))]
    schmidt_b = [Ket(Vh[i, :].conj()) for i in range(len(coeffs))]

    logger.debug(f"Schmidt decomposition: rank={len(coeffs)}")

    return {
        'coefficients': [float(c) for c in coeffs],
        'vectors_a': schmidt_a,
        'vectors_b': schmidt_b,
        'rank': len(coeffs),
        'schmidt_rank': len(coeffs)
    }

schmidt_rank(state, dims, tol=1e-10)

Compute Schmidt rank of a bipartite pure state

Parameters:

Name Type Description Default
state Union[Ket, ndarray]

Pure state

required
dims List[int]

Subsystem dimensions

required
tol float

Tolerance for zero coefficients

1e-10

Returns:

Name Type Description
int int

Schmidt rank

Example

from psiqit.quantum import bell_phi_plus rank = schmidt_rank(bell_phi_plus(), [2, 2]) print(rank) # 2

Source code in psiqit\info\entanglement.py
def schmidt_rank(
    state: Union[Ket, np.ndarray],
    dims: List[int],
    tol: float = 1e-10
) -> int:
    """
    Compute Schmidt rank of a bipartite pure state

    Args:
        state: Pure state
        dims: Subsystem dimensions
        tol: Tolerance for zero coefficients

    Returns:
        int: Schmidt rank

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> rank = schmidt_rank(bell_phi_plus(), [2, 2])
        >>> print(rank)  # 2
    """
    result = schmidt_decomposition(state, dims)
    coeffs = result['coefficients']

    # Count coefficients above tolerance
    rank = sum(1 for c in coeffs if c > tol)

    return rank

is_entangled(state_or_rho, dims=None, tol=1e-10)

Detect if a quantum state is entangled

Uses multiple criteria: 1. For pure states: Schmidt rank > 1 2. For mixed states: negativity > 0 (for bipartite)

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None
tol float

Tolerance for numerical checks

1e-10

Returns:

Name Type Description
bool bool

True if entangled, False if separable

Example

from psiqit.quantum import bell_phi_plus, zero is_entangled(bell_phi_plus()) # True is_entangled(zero()) # False

Source code in psiqit\info\entanglement.py
def is_entangled(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None,
    tol: float = 1e-10
) -> bool:
    """
    Detect if a quantum state is entangled

    Uses multiple criteria:
    1. For pure states: Schmidt rank > 1
    2. For mixed states: negativity > 0 (for bipartite)

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions
        tol: Tolerance for numerical checks

    Returns:
        bool: True if entangled, False if separable

    Example:
        >>> from psiqit.quantum import bell_phi_plus, zero
        >>> is_entangled(bell_phi_plus())  # True
        >>> is_entangled(zero())  # False
    """
    # Check if it's a density matrix (square matrix)
    if isinstance(state_or_rho, Matrix):
        data = state_or_rho.data
    else:
        data = np.array(state_or_rho, dtype=complex)

    if len(data.shape) == 2 and data.shape[0] == data.shape[1]:
        # It's a density matrix
        # Use negativity criterion for bipartite systems

        # Default dimensions
        if dims is None:
            dim = data.shape[0]
            n_qubits = int(np.log2(dim))
            if 2 ** n_qubits == dim:
                dim_a = 2 ** (n_qubits // 2)
                dim_b = dim // dim_a
                dims = [dim_a, dim_b]
            else:
                # If not bipartite, try to determine
                # For simplicity, we'll assume it's a 2-qubit system if dim=4
                if dim == 4:
                    dims = [2, 2]
                else:
                    # Cannot determine, return False
                    logger.warning("Cannot determine entanglement for this density matrix")
                    return False

        # Check if it's a pure state (rank 1)
        eigvals = np.linalg.eigvalsh(data)
        if np.sum(eigvals > tol) <= 1:
            # Pure state: get the ket and check Schmidt rank
            eigvals, eigvecs = np.linalg.eigh(data)
            idx = np.argmax(eigvals)
            state = Ket(eigvecs[:, idx])
            return schmidt_rank(state, dims, tol) > 1
        else:
            # Mixed state: use negativity
            neg = negativity(data, dims)
            return neg > tol
    else:
        # It's a state vector
        # Default dimensions for bipartite systems
        if dims is None:
            dim = len(data)
            n_qubits = int(np.log2(dim))
            if 2 ** n_qubits == dim:
                dim_a = 2 ** (n_qubits // 2)
                dim_b = dim // dim_a
                dims = [dim_a, dim_b]
            else:
                # For arbitrary dimensions, try to split evenly
                import math
                dim_a = int(math.isqrt(dim))
                if dim_a * dim_a == dim:
                    dims = [dim_a, dim_a]
                else:
                    # Cannot determine
                    logger.warning("Cannot determine subsystem dimensions for this state")
                    return False

        # Check Schmidt rank
        return schmidt_rank(data, dims, tol) > 1

entanglement_of_formation(state_or_rho, dims=None)

Compute entanglement of formation for two-qubit states

E_F(ρ) = h((1 + √(1 - C²))/2) where h(x) = -x log₂(x) - (1-x) log₂(1-x)

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None

Returns:

Name Type Description
float float

Entanglement of formation (0-1)

Example

from psiqit.quantum import bell_phi_plus EOF = entanglement_of_formation(bell_phi_plus()) print(EOF) # 1.0

Source code in psiqit\info\entanglement.py
def entanglement_of_formation(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute entanglement of formation for two-qubit states

    E_F(ρ) = h((1 + √(1 - C²))/2)
    where h(x) = -x log₂(x) - (1-x) log₂(1-x)

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions

    Returns:
        float: Entanglement of formation (0-1)

    Example:
        >>> from psiqit.quantum import bell_phi_plus
        >>> EOF = entanglement_of_formation(bell_phi_plus())
        >>> print(EOF)  # 1.0
    """
    # Compute concurrence
    C = concurrence(state_or_rho, dims)

    # Compute binary entropy
    def h(x):
        if x <= 0 or x >= 1:
            return 0.0
        return -x * np.log2(x) - (1 - x) * np.log2(1 - x)

    # Entanglement of formation
    x = (1 + np.sqrt(1 - C**2)) / 2
    EOF = h(x)

    return float(EOF)

distillable_entanglement(state_or_rho, dims=None)

Compute distillable entanglement (upper bound using log negativity)

E_D(ρ) ≤ log₂(||ρ^{T_A}||₁)

Parameters:

Name Type Description Default
state_or_rho Union[Ket, ndarray, Matrix]

State vector or density matrix

required
dims Optional[List[int]]

Subsystem dimensions

None

Returns:

Name Type Description
float float

Distillable entanglement (upper bound)

Source code in psiqit\info\entanglement.py
def distillable_entanglement(
    state_or_rho: Union[Ket, np.ndarray, Matrix],
    dims: Optional[List[int]] = None
) -> float:
    """
    Compute distillable entanglement (upper bound using log negativity)

    E_D(ρ) ≤ log₂(||ρ^{T_A}||₁)

    Args:
        state_or_rho: State vector or density matrix
        dims: Subsystem dimensions

    Returns:
        float: Distillable entanglement (upper bound)
    """
    return logarithmic_negativity(state_or_rho, dims)

info()

Get information about the information theory module

Returns:

Name Type Description
dict dict

Module information

Source code in psiqit\info\__init__.py
def info() -> dict:
    """
    Get information about the information theory module

    Returns:
        dict: Module information
    """
    return {
        'module': 'psiqit.info',
        'version': __version__,
        'submodules': ['entropy', 'entanglement'],
        'exports': len(__all__),
    }

test()

Run basic tests for the information theory module

Returns:

Name Type Description
dict dict

Test results

Source code in psiqit\info\__init__.py
def test() -> dict:
    """
    Run basic tests for the information theory module

    Returns:
        dict: Test results
    """
    results = {}

    # Test entropy
    try:
        from .entropy import shannon_entropy, von_neumann_entropy, purity
        probs = [0.5, 0.5]
        H = shannon_entropy(probs)
        results['shannon_entropy'] = abs(H - 0.693147) < 1e-6

        rho = np.array([[0.5, 0], [0, 0.5]])
        S = von_neumann_entropy(rho)
        results['von_neumann_entropy'] = abs(S - 0.693147) < 1e-6

        p = purity(rho)
        results['purity'] = abs(p - 0.5) < 1e-6
    except Exception as e:
        results['entropy'] = str(e)

    # Test entanglement
    try:
        from .entanglement import concurrence, negativity, is_entangled
        from ..quantum.state import bell_phi_plus, zero

        C = concurrence(bell_phi_plus())
        results['concurrence'] = abs(C - 1.0) < 1e-6

        N = negativity(bell_phi_plus())
        results['negativity'] = abs(N - 0.5) < 1e-6

        is_ent = is_entangled(bell_phi_plus())
        results['is_entangled_bell'] = is_ent

        is_ent = is_entangled(zero())
        results['is_entangled_zero'] = not is_ent
    except Exception as e:
        results['entanglement'] = str(e)

    return results