Skip to content

partial_trace

Generates the partial trace of a matrix.

partial_trace

partial_trace(
    input_mat: ndarray | Expression | Variable,
    sys: int | list[int] | tuple | None = None,
    dim: int | list[int] | tuple | ndarray | None = None,
) -> ndarray | Expression

Compute the partial trace of a matrix 1.

The partial trace is defined as

\[ \left( \text{Tr} \otimes \mathbb{I}_{\mathcal{Y}} \right) \left(X \otimes Y \right) = \text{Tr}(X)Y \]

where \(X \in \text{L}(\mathcal{X})\) and \(Y \in \text{L}(\mathcal{Y})\) are linear operators over complex Euclidean spaces \(\mathcal{X}\) and \(\mathcal{Y}\).

Gives the partial trace of the matrix X, where the dimensions of the (possibly more than 2) subsystems are given by the vector dim and the subsystems to take the trace on are given by the scalar or vector sys.

Parameters:

  • input_mat (ndarray | Expression | Variable) –

    A square matrix.

  • sys (int | list[int] | tuple | None, default: None ) –

    Scalar or vector specifying the size of the subsystems.

  • dim (int | list[int] | tuple | ndarray | None, default: None ) –

    Dimension of the subsystems. If None, all dimensions are assumed to be equal. Accepted types are int, list, tuple, or numpy.ndarray.

Returns:

  • ndarray | Expression

    The partial trace of matrix input_mat.

Raises:

  • ValueError

    If input_mat is not a 2D square matrix.

  • ValueError

    If dim is not an int, list, tuple, or numpy.ndarray of ints.

  • ValueError

    If dim is a scalar that does not evenly divide the matrix dimension.

  • ValueError

    If the product of dim does not match the matrix dimension.

  • ValueError

    If any index in sys is negative or out of bounds.

  • ValueError

    If sys is not an int, list, tuple, or numpy.ndarray of ints.

Examples:

Consider the following matrix

\[ X = \begin{pmatrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \end{pmatrix}. \]

Taking the partial trace over the second subsystem of \(X\) yields the following matrix

\[ X_{pt, 2} = \begin{pmatrix} 7 & 11 \\ 23 & 27 \end{pmatrix}. \]

By default, the partial trace function in |toqito⟩ takes the trace of the second subsystem.

import numpy as np
from toqito.matrix_ops import partial_trace

test_input_mat = np.arange(1, 17).reshape(4, 4)

print(partial_trace(test_input_mat))
[[ 7 11]
 [23 27]]

By specifying the sys = [0] argument, we can perform the partial trace over the first subsystem (instead of the default second subsystem as done above). Performing the partial trace over the first subsystem yields the following matrix

[ X_{pt, 1} = \begin{pmatrix} 12 & 14 \ 20 & 22 \end{pmatrix} ]

import numpy as np
from toqito.matrix_ops import partial_trace

test_input_mat = np.arange(1, 17).reshape(4, 4)

print(partial_trace(test_input_mat, [0]))
[[12 14]
 [20 22]]

We can also specify both dimension and system size as list arguments. Consider the following \(16\)-by-\(16\) matrix.

import numpy as np
from toqito.matrix_ops import partial_trace

test_input_mat = np.arange(1, 257).reshape(16, 16)
print(test_input_mat)
[[  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16]
 [ 17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32]
 [ 33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48]
 [ 49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64]
 [ 65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80]
 [ 81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96]
 [ 97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112]
 [113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128]
 [129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144]
 [145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160]
 [161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176]
 [177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192]
 [193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208]
 [209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224]
 [225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240]
 [241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256]]

We can take the partial trace on the first and third subsystems and assume that the size of each of the 4 systems is of dimension 2.

import numpy as np
from toqito.matrix_ops import partial_trace
test_input_mat = np.arange(1, 257).reshape(16, 16)

print(partial_trace(test_input_mat, [0, 2], [2, 2, 2, 2]))
[[344 348 360 364]
 [408 412 424 428]
 [600 604 616 620]
 [664 668 680 684]]

References

1 Wikipedia. Partial Trace. link.

Source code in toqito/matrix_ops/partial_trace.py
def partial_trace(
    input_mat: np.ndarray | Expression | Variable,
    sys: int | list[int] | tuple | None = None,
    dim: int | list[int] | tuple | np.ndarray | None = None,
) -> np.ndarray | Expression:
    r"""Compute the partial trace of a matrix [@wikipediapartialtrace].

    The *partial trace* is defined as

    \[
        \left( \text{Tr} \otimes \mathbb{I}_{\mathcal{Y}} \right)
        \left(X \otimes Y \right) = \text{Tr}(X)Y
    \]

    where \(X \in \text{L}(\mathcal{X})\) and \(Y \in \text{L}(\mathcal{Y})\) are linear
    operators over complex Euclidean spaces \(\mathcal{X}\) and \(\mathcal{Y}\).

    Gives the partial trace of the matrix X, where the dimensions of the (possibly more than 2)
    subsystems are given by the vector `dim` and the subsystems to take the trace on are
    given by the scalar or vector `sys`.

    Args:
        input_mat: A square matrix.
        sys: Scalar or vector specifying the size of the subsystems.
        dim: Dimension of the subsystems. If `None`, all dimensions are assumed to be equal.
            Accepted types are `int`, `list`, `tuple`, or `numpy.ndarray`.

    Returns:
        The partial trace of matrix `input_mat`.

    Raises:
        ValueError: If `input_mat` is not a 2D square matrix.
        ValueError: If `dim` is not an `int`, `list`, `tuple`, or `numpy.ndarray` of ints.
        ValueError: If `dim` is a scalar that does not evenly divide the matrix dimension.
        ValueError: If the product of `dim` does not match the matrix dimension.
        ValueError: If any index in `sys` is negative or out of bounds.
        ValueError: If `sys` is not an `int`, `list`, `tuple`, or `numpy.ndarray` of ints.

    Examples:
        Consider the following matrix

        \[
            X = \begin{pmatrix}
                    1 & 2 & 3 & 4 \\
                    5 & 6 & 7 & 8 \\
                    9 & 10 & 11 & 12 \\
                    13 & 14 & 15 & 16
                \end{pmatrix}.
        \]

        Taking the partial trace over the second subsystem of \(X\) yields the following matrix

        \[
            X_{pt, 2} = \begin{pmatrix}
                        7 & 11 \\
                        23 & 27
                     \end{pmatrix}.
        \]

        By default, the partial trace function in `|toqito⟩` takes the trace of the second
        subsystem.
        ```python exec="1" source="above" result="text"
        import numpy as np
        from toqito.matrix_ops import partial_trace

        test_input_mat = np.arange(1, 17).reshape(4, 4)

        print(partial_trace(test_input_mat))
        ```

        By specifying the `sys = [0]` argument, we can perform the partial trace over the first
        subsystem (instead of the default second subsystem as done above). Performing the partial
        trace over the first subsystem yields the following matrix

        \[
            X_{pt, 1} = \begin{pmatrix}
                            12 & 14 \\
                            20 & 22
                        \end{pmatrix}
        \]
        ```python exec="1" source="above" result="text"
        import numpy as np
        from toqito.matrix_ops import partial_trace

        test_input_mat = np.arange(1, 17).reshape(4, 4)

        print(partial_trace(test_input_mat, [0]))
        ```

        We can also specify both dimension and system size as `list` arguments. Consider the
        following \(16\)-by-\(16\) matrix.
        ```python exec="1" source="above" result="text"
        import numpy as np
        from toqito.matrix_ops import partial_trace

        test_input_mat = np.arange(1, 257).reshape(16, 16)
        print(test_input_mat)
        ```

        We can take the partial trace on the first and third subsystems and assume that the size of
        each of the 4 systems is of dimension 2.
        ```python exec="1" source="above" result="text"
        import numpy as np
        from toqito.matrix_ops import partial_trace
        test_input_mat = np.arange(1, 257).reshape(16, 16)

        print(partial_trace(test_input_mat, [0, 2], [2, 2, 2, 2]))
        ```

    """
    if not isinstance(sys, int):
        if sys is None:
            sys = [1]
    # If the input matrix is a CVXPY expression for an SDP, we convert it to a
    # NumPy object array, perform the partial trace recursively, and convert it
    # back to a CVXPY expression.
    if isinstance(input_mat, (Expression, Variable)):
        rho_np = expr_as_np_array(input_mat)
        traced_rho = partial_trace(rho_np, sys, dim)
        traced_rho = np_array_as_expr(traced_rho)
        return traced_rho

    # Ensure input_mat is square.
    if input_mat.ndim != 2 or input_mat.shape[0] != input_mat.shape[1]:
        raise ValueError("input_mat must be a 2D square matrix.")
    n = input_mat.shape[0]

    if dim is None:
        d = int(round(np.sqrt(n)))
        if d * d != n:
            raise ValueError("Cannot infer subsystem dimensions directly. Please provide `dim`.")
        dim = np.array([d, d])
    elif isinstance(dim, int):
        if n % dim != 0:
            raise ValueError("Invalid: If `dim` is a scalar, it must evenly divide matrix dimension.")
        dim = np.array([dim, n // dim])
    elif isinstance(dim, (list, tuple, np.ndarray)):
        dim = np.asarray(dim)
        if dim.ndim != 1:
            raise ValueError("Invalid: `dim` must be a 1D array-like of ints.")
        if len(dim) == 1:
            d = dim[0]
            if n % d != 0:
                raise ValueError("Invalid: If `dim` is a scalar, it must evenly divide matrix dimension.")
            dim = np.array([d, n // d])
    else:
        raise ValueError("Invalid: `dim` must be int or array-like of ints.")

    num_sys = len(dim)
    prod_dim = np.prod(dim)
    # Ensure product of dim matches matrix dimension.
    if prod_dim != n:
        raise ValueError("Product of `dim` must match the dimension of input_mat.")

    # Validate sys indices and compute subsystem product.
    if isinstance(sys, int):
        if sys < 0 or sys >= num_sys:
            raise ValueError("Subsystem indices in `sys` are out of bounds.")
        prod_dim_sys = dim[sys]
        sys = np.array([sys])

    elif isinstance(sys, (list, tuple, np.ndarray)):
        if any(s < 0 or s >= num_sys for s in sys):
            raise ValueError("Subsystem indices in `sys` are out of bounds.")
        prod_dim_sys = int(np.prod([dim[i] for i in sys]))
        sys = np.array(sys)

    else:
        raise ValueError("Invalid: The variable `sys` must either be of type int or of a list of ints.")

    sub_prod = prod_dim // prod_dim_sys
    sub_sys_size = prod_dim_sys

    remaining_sys = np.setdiff1d(np.arange(num_sys), sys, assume_unique=True)
    perm = np.concatenate([remaining_sys, sys]).astype(np.int32)

    a_mat = permute_systems(input_mat, perm, dim)

    ret_mat = np.reshape(
        a_mat,
        [sub_sys_size, sub_prod, sub_sys_size, sub_prod],
        order="F",
    )
    permuted_mat = ret_mat.transpose((1, 3, 0, 2))

    permuted_reshaped_mat = np.reshape(
        permuted_mat,
        [sub_prod, sub_prod, sub_sys_size**2],
        order="F",
    )

    diag_idx = np.arange(sub_sys_size) * (sub_sys_size + 1)
    pt_mat = permuted_reshaped_mat[:, :, diag_idx]
    pt_mat = np.sum(pt_mat, axis=2)

    return pt_mat