Пример #1
0
def permutation_operator(
    dim: Union[List[int], int],
    perm: List[int],
    inv_perm: bool = False,
    is_sparse: bool = False,
) -> np.ndarray:
    """
    Produce a unitary operator that permutes subsystems.

    Generates a unitary operator that permutes the order of subsystems
    according to the permutation vector `perm`, where the ith subsystem has
    dimension `dim[i]`.

    If `inv_perm` = True, it implements the inverse permutation of `perm`. The
    permutation operator return is full is `is_sparse` is False and sparse if
    `is_sparse` is True.

    :param dim: The dimensions of the subsystems to be permuted.
    :param perm: A permutation vector.
    :param inv_perm: Boolean dictating if `perm` is inverse or not.
    :param is_sparse: Boolean indicating if return is sparse or not.
    :return: Permutation operator of dimension `dim`.
    """
    # Allow the user to enter a single number for `dim`.
    if isinstance(dim, int):
        dim = dim * np.ones(max(perm))
    if isinstance(dim, list):
        dim = np.array(dim)

    # Swap the rows of the identity matrix appropriately.
    return permute_systems(iden(int(np.prod(dim)), is_sparse), perm, dim, True,
                           inv_perm)
Пример #2
0
    def test_2(self):
        """Test permute systems for dim = [2,3,1]."""
        test_input_mat = np.array(
            [
                [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],
            ]
        )

        expected_res = np.array(
            [
                [1, 5, 2, 6, 3, 7, 4, 8],
                [33, 37, 34, 38, 35, 39, 36, 40],
                [9, 13, 10, 14, 11, 15, 12, 16],
                [41, 45, 42, 46, 43, 47, 44, 48],
                [17, 21, 18, 22, 19, 23, 20, 24],
                [49, 53, 50, 54, 51, 55, 52, 56],
                [25, 29, 26, 30, 27, 31, 28, 32],
                [57, 61, 58, 62, 59, 63, 60, 64],
            ]
        )

        res = permute_systems(test_input_mat, [2, 3, 1])

        bool_mat = np.isclose(res, expected_res)
        self.assertEqual(np.all(bool_mat), True)
Пример #3
0
def permutation_operator(
    dim: Union[List[int], int],
    perm: List[int],
    inv_perm: bool = False,
    is_sparse: bool = False,
) -> np.ndarray:
    r"""
    Produce a unitary operator that permutes subsystems.

    Generates a unitary operator that permutes the order of subsystems
    according to the permutation vector `perm`, where the ith subsystem has
    dimension `dim[i]`.

    If `inv_perm` = True, it implements the inverse permutation of `perm`. The
    permutation operator return is full is `is_sparse` is False and sparse if
    `is_sparse` is True.

    Examples
    ==========

    The permutation operator obtained with dimension :math:`d = 2` is equivalent
    to the standard swap operator on two qubits

    .. math::
        \begin{pmatrix}
            1 & 0 & 0 & 0 \\
            0 & 0 & 1 & 0 \\
            0 & 1 & 0 & 0 \\
            0 & 0 & 0 & 1
        \end{pmatrix}

    Using `toqito`, this can be achieved in the following manner.

    >>> from toqito.perms.permutation_operator import permutation_operator
    >>> permutation_operator(2, [2, 1])
    array([[1., 0., 0., 0.],
           [0., 0., 1., 0.],
           [0., 1., 0., 0.],
           [0., 0., 0., 1.]])

    :param dim: The dimensions of the subsystems to be permuted.
    :param perm: A permutation vector.
    :param inv_perm: Boolean dictating if `perm` is inverse or not.
    :param is_sparse: Boolean indicating if return is sparse or not.
    :return: Permutation operator of dimension `dim`.
    """
    # Allow the user to enter a single number for `dim`.
    if isinstance(dim, int):
        dim = dim * np.ones(max(perm))
    if isinstance(dim, list):
        dim = np.array(dim)

    # Swap the rows of the identity matrix appropriately.
    return permute_systems(iden(int(np.prod(dim)), is_sparse), perm, dim, True,
                           inv_perm)
Пример #4
0
    def test_m2_m2(self):
        """Permute system for dim = [2,1]."""
        test_input_mat = np.array(
            [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
        )

        expected_res = np.array(
            [[1, 3, 2, 4], [9, 11, 10, 12], [5, 7, 6, 8], [13, 15, 14, 16]]
        )

        res = permute_systems(test_input_mat, [2, 1])

        bool_mat = np.isclose(res, expected_res)
        self.assertEqual(np.all(bool_mat), True)
Пример #5
0
def swap(
    rho: np.ndarray,
    sys: List[int] = None,
    dim: Union[List[int], List[List[int]], int, np.ndarray] = None,
    row_only: bool = False,
) -> np.ndarray:
    """
    Swap two subsystems within a state or operator.

    Swaps the two subsystems of the vector or matrix `rho`, where the
    dimensions of the (possibly more than 2) subsystems are given by `dim` and
    the indices of the two subsystems to be swapped are specified in the 1-by-2
    vector `sys`.

    If `rho` is non-square and not a vector, different row and column
    dimensions can be specified by putting the row dimensions in the first row
    of `dim` and the column dimensions in the second row of `dim`.

    If `row_only` is set to `True`, then only the rows of `rho` are swapped,
    but not the columns -- this is equivalent to multiplying `rho` on the left
    by the corresponding swap operator, but not on the right.

    :param rho: A vector or matrix to have its subsystems swapped.
    :param sys: Default: [1, 2]
    :param dim: Default: [sqrt(len(X), sqrt(len(X)))]
    :param row_only: Default: False
    :return: The swapped matrix.
    """
    eps = np.finfo(float).eps
    if len(rho.shape) == 1:
        rho_dims = (1, rho.shape[0])
    else:
        rho_dims = rho.shape

    round_dim = np.round(np.sqrt(rho_dims))

    if sys is None:
        sys = [1, 2]

    if isinstance(dim, list):
        dim = np.array(dim)
    if dim is None:
        dim = np.array([[round_dim[0], round_dim[0]], [round_dim[1], round_dim[1]]])

    if isinstance(dim, int):
        dim = np.array([[dim, rho_dims[0] / dim], [dim, rho_dims[1] / dim]])
        if (
            np.abs(dim[0, 1] - np.round(dim[0, 1]))
            + np.abs(dim[1, 1] - np.round(dim[1, 1]))
            >= 2 * np.prod(rho_dims) * eps
        ):
            val_error = """
                InvalidDim: The value of `dim` must evenly divide the number of
                rows and columns of `rho`; please provide the `dim` array
                containing the dimensions of the subsystems.
            """
            raise ValueError(val_error)

        dim[0, 1] = np.round(dim[0, 1])
        dim[1, 1] = np.round(dim[1, 1])
        num_sys = 2
    else:
        num_sys = len(dim)

    # Verify that the input sys makes sense.
    if any(sys) < 1 or any(sys) > num_sys:
        val_error = """
            InvalidSys: The subsystems in `sys` must be between 1 and 
            `len(dim).` inclusive.
        """
        raise ValueError(val_error)
    if len(sys) != 2:
        val_error = """
            InvalidSys: `sys` must be a vector with exactly two elements.
        """
        raise ValueError(val_error)

    # Swap the indicated subsystems.
    perm = list(range(1, num_sys + 1))
    perm = perm[::-1]
    return permute_systems(rho, perm, dim, row_only)
Пример #6
0
def partial_trace(
    input_mat: np.ndarray,
    sys: Union[int, List[int]] = 2,
    dim: Union[int, List[int]] = None,
):
    """
    Compute the partial trace of a matrix.

    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`.

    References:
        [1] Wikipedia: Partial trace
        https://en.wikipedia.org/wiki/Partial_trace

    :param input_mat: A square matrix.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If `None`, all dimensions
                are assumed to be equal.
    :return: The partial trace of matrix `input_mat`.
    """
    if dim is None:
        dim = np.array([np.round(np.sqrt(len(input_mat)))])
    if isinstance(dim, int):
        dim = np.array([dim])
    if isinstance(dim, list):
        dim = np.array(dim)

    if sys is None:
        sys = 2

    num_sys = len(dim)

    # Allow the user to enter a single number for dim.
    if num_sys == 1:
        dim = np.array([dim[0], len(input_mat) / dim[0]])
        if (np.abs(dim[1] - np.round(dim[1])) >=
                2 * len(input_mat) * np.finfo(float).eps):
            raise ValueError(
                "Invalid: If `dim` is a scalar, `dim` must evenly "
                "divide `len(input_mat)`.")
        dim[1] = np.round(dim[1])
        num_sys = 2

    prod_dim = np.prod(dim)
    if isinstance(sys, list):
        prod_dim_sys = np.prod(dim[sys])
    elif isinstance(sys, int):
        prod_dim_sys = np.prod(dim[sys - 1])
    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_vec = prod_dim * np.ones(int(sub_prod)) / sub_prod

    if isinstance(sys, int):
        sys = [sys]
    set_diff = list(set(list(range(1, num_sys + 1))) - set(sys))

    perm = set_diff
    perm.extend(sys)

    a_mat = permute_systems(input_mat, perm, dim)

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

    pt_mat = permuted_reshaped_mat[:, :,
                                   list(
                                       range(0, int(sub_sys_vec[0]**2
                                                    ), int(sub_sys_vec[0] +
                                                           1)))]
    pt_mat = np.sum(pt_mat, axis=2)

    return pt_mat
Пример #7
0
def partial_trace(
    input_mat: np.ndarray,
    sys: Union[int, List[int]] = 2,
    dim: Union[int, List[int]] = None,
):
    r"""
    Compute the partial trace of a matrix [WikPtrace]_.

    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`.

    Examples
    ==========

    Consider the following matrix

    .. math::
        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 :math:`X` yields the
    following matrix

    .. math::
        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.

    >>> from toqito.channels.channels.partial_trace import partial_trace
    >>> import numpy as np
    >>> test_input_mat = np.array(
    >>>     [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    >>> )
    >>> partial_trace(test_input_mat)
    array([[ 7, 11],
           [23, 27]])

    By specifying the `sys = 1` 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

    .. math::
        X_{pt, 1} = \begin{pmatrix}
                        12 & 14 \\
                        20 & 22
                    \end{pmatrix}

    >>> from toqito.channels.channels.partial_trace import partial_trace
    >>> import numpy as np
    >>> test_input_mat = np.array(
    >>>     [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    >>> )
    >>> partial_trace(test_input_mat, 1)
    array([[12, 14],
           [20, 22]])

    We can also specify both dimension and system size as `list` arguments.
    Consider the following :math:`16`-by-:math:`16` matrix.

    >>> from toqito.channels.channels.partial_trace import partial_trace
    >>> import numpy as np
    >>> test_input_mat = np.arange(1, 257).reshape(16, 16)
    >>> 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.

    >>> from toqito.channels.channels.partial_trace import partial_trace
    >>> import numpy as np
    >>> partial_trace(test_input_mat, [1, 3], [2, 2, 2, 2])
    array([[344, 348, 360, 364],
           [408, 412, 424, 428],
           [600, 604, 616, 620],
           [664, 668, 680, 684]])

    References
    ==========
    .. [WikPtrace] Wikipedia: Partial trace
        https://en.wikipedia.org/wiki/Partial_trace

    :param input_mat: A square matrix.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If `None`, all dimensions
                are assumed to be equal.
    :return: The partial trace of matrix `input_mat`.
    """
    if dim is None:
        dim = np.array([np.round(np.sqrt(len(input_mat)))])
    if isinstance(dim, int):
        dim = np.array([dim])
    if isinstance(dim, list):
        dim = np.array(dim)

    if sys is None:
        sys = 2

    num_sys = len(dim)

    # Allow the user to enter a single number for dim.
    if num_sys == 1:
        dim = np.array([dim[0], len(input_mat) / dim[0]])
        if (np.abs(dim[1] - np.round(dim[1])) >=
                2 * len(input_mat) * np.finfo(float).eps):
            raise ValueError(
                "Invalid: If `dim` is a scalar, `dim` must evenly "
                "divide `len(input_mat)`.")
        dim[1] = np.round(dim[1])
        num_sys = 2

    prod_dim = np.prod(dim)
    if isinstance(sys, list):
        prod_dim_sys = np.prod(dim[sys])
    elif isinstance(sys, int):
        prod_dim_sys = np.prod(dim[sys - 1])
    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_vec = prod_dim * np.ones(int(sub_prod)) / sub_prod

    if isinstance(sys, int):
        sys = [sys]
    set_diff = list(set(list(range(1, num_sys + 1))) - set(sys))

    perm = set_diff
    perm.extend(sys)

    a_mat = permute_systems(input_mat, perm, dim)

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

    pt_mat = permuted_reshaped_mat[:, :,
                                   list(
                                       range(0, int(sub_sys_vec[0]**2
                                                    ), int(sub_sys_vec[0] +
                                                           1)))]
    pt_mat = np.sum(pt_mat, axis=2)

    return pt_mat
Пример #8
0
def partial_transpose(
    rho: np.ndarray,
    sys: Union[List[int], np.ndarray, int] = 2,
    dim: Union[List[int], np.ndarray] = None,
) -> np.ndarray:
    """Compute the partial transpose of a matrix.

    By default, the returned matrix is the partial transpose of the matrix
    `rho`, where it is assumed that the number of rows and columns of `rho` are
    both perfect squares and both subsystems have equal dimension. The
    transpose is applied to the second subsystem.

    In the case where `sys` amd `dim` are specified, this function gives the
    partial transpose of the matrix `rho` where the dimensions of the (possibly
    more than 2) subsystems are given by the vector `dim` and the subsystems to
    take the partial transpose are given by the scalar or vector `sys`. If
    `rho` is non-square, different row and column dimensions can be specified
    by putting the row dimensions in the first row of `dim` and the column
    dimensions in the second row of `dim`.

    References:
        [1] Wikipedia: Partial transpose
        https://en.wikipedia.org/w/index.php?title=Partial_transpose&redirect=no

    :param rho: A matrix.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If `None`, all dimensions
                are assumed to be equal.
    :returns: The partial transpose of matrix `rho`.
    """
    sqrt_rho_dims = np.round(np.sqrt(list(rho.shape)))

    if dim is None:
        dim = np.array([[sqrt_rho_dims[0], sqrt_rho_dims[0]],
                        [sqrt_rho_dims[1], sqrt_rho_dims[1]]])
    if isinstance(dim, float):
        dim = np.array([dim])
    if isinstance(dim, list):
        dim = np.array(dim)
    if isinstance(sys, list):
        sys = np.array(sys)
    if isinstance(sys, int):
        sys = np.array([sys])

    num_sys = len(dim)
    # Allow the user to enter a single number for dim.
    if num_sys == 1:
        dim = np.array([dim, list(rho.shape)[0] / dim])
        if (np.abs(dim[1] - np.round(dim[1]))[0] >=
                2 * list(rho.shape)[0] * np.finfo(float).eps):
            raise ValueError("InvalidDim: If `dim` is a scalar, `rho` must be "
                             "square and `dim` must evenly divide `len(rho)`; "
                             "please provide the `dim` array containing the "
                             "dimensions of the subsystems.")
        dim[1] = np.round(dim[1])
        num_sys = 2

    # Allow the user to enter a vector for dim if X is square.
    if min(dim.shape) == 1 or len(dim.shape) == 1:
        # Force dim to be a row vector.
        dim = dim.T.flatten()
        dim = np.array([dim, dim])

    prod_dim_r = int(np.prod(dim[0, :]))
    prod_dim_c = int(np.prod(dim[1, :]))

    sub_prod_r = np.prod(dim[0, sys - 1])
    sub_prod_c = np.prod(dim[1, sys - 1])

    sub_sys_vec_r = prod_dim_r * np.ones(int(sub_prod_r)) / sub_prod_r
    sub_sys_vec_c = prod_dim_c * np.ones(int(sub_prod_c)) / sub_prod_c

    set_diff = list(set(list(range(1, num_sys + 1))) - set(sys))
    perm = sys.tolist()[:]
    perm.extend(set_diff)

    # Permute the subsystems so that we just have to do the partial transpose
    # on the first (potentially larger) subsystem.
    rho_permuted = permute_systems(rho, perm, dim)

    x_tmp = np.reshape(
        rho_permuted,
        [
            int(sub_sys_vec_r[0]),
            int(sub_prod_r),
            int(sub_sys_vec_c[0]),
            int(sub_prod_c),
        ],
        order="F",
    )
    y_tmp = np.transpose(x_tmp, [0, 3, 2, 1])
    z_tmp = np.reshape(y_tmp, [int(prod_dim_r), int(prod_dim_c)], order="F")

    # # Return the subsystems back to their original positions.
    # if len(sys) > 1:
    #     dim[:, sys-1] = dim[[1, 0], sys-1]

    dim = dim[:, np.array(perm) - 1]

    return permute_systems(z_tmp, perm, dim, False, True)
Пример #9
0
def partial_transpose(
    rho: np.ndarray,
    sys: Union[List[int], np.ndarray, int] = 2,
    dim: Union[List[int], np.ndarray] = None,
) -> np.ndarray:
    r"""Compute the partial transpose of a matrix [WIKPTRN]_.

    By default, the returned matrix is the partial transpose of the matrix
    `rho`, where it is assumed that the number of rows and columns of `rho` are
    both perfect squares and both subsystems have equal dimension. The
    transpose is applied to the second subsystem.

    In the case where `sys` amd `dim` are specified, this function gives the
    partial transpose of the matrix `rho` where the dimensions of the (possibly
    more than 2) subsystems are given by the vector `dim` and the subsystems to
    take the partial transpose are given by the scalar or vector `sys`. If
    `rho` is non-square, different row and column dimensions can be specified
    by putting the row dimensions in the first row of `dim` and the column
    dimensions in the second row of `dim`.

    Examples
    ==========

    Consider the following matrix

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

    Performing the partial transpose on the matrix :math:`X` over the second
    subsystem yields the following matrix

    .. math::
        X_{pt, 2} = \begin{pmatrix}
                    1 & 5 & 3 & 7 \\
                    2 & 6 & 4 & 8 \\
                    9 & 13 & 11 & 15 \\
                    10 & 14 & 12 & 16
                 \end{pmatrix}.

    By default, in `toqito`, the partial transpose function performs the
    transposition on the second subsystem as follows.

    >>> from toqito.maps.partial_transpose import partial_transpose
    >>> import numpy as np
    >>> test_input_mat = np.arange(1, 17).reshape(4, 4)
    >>> partial_transpose(test_input_mat)
    [[ 1  5  3  7]
     [ 2  6  4  8]
     [ 9 13 11 15]
     [10 14 12 16]]

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

    .. math::
        X_{pt, 1} = \begin{pmatrix}
                        1 & 2 & 9 & 10 \\
                        5 & 6 & 13 & 14 \\
                        3 & 4 & 11 & 12 \\
                        7 & 8 & 15 & 16
                    \end{pmatrix}

    >>> from toqito.channels.channels.partial_transpose import partial_transpose
    >>> import numpy as np
    >>> test_input_mat = np.array(
    >>>     [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    >>> )
    >>> partial_transpose(test_input_mat, 1)
    [[ 1  2  9 10]
     [ 5  6 13 14]
     [ 3  4 11 12]
     [ 7  8 15 16]]

    References
    ==========
    .. [WIKPTRN] Wikipedia: Partial transpose
        https://en.wikipedia.org/w/index.php?title=Partial_transpose&redirect=no

    :param rho: A matrix.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If `None`, all dimensions
                are assumed to be equal.
    :returns: The partial transpose of matrix `rho`.
    """
    sqrt_rho_dims = np.round(np.sqrt(list(rho.shape)))

    if dim is None:
        dim = np.array([[sqrt_rho_dims[0], sqrt_rho_dims[0]],
                        [sqrt_rho_dims[1], sqrt_rho_dims[1]]])
    if isinstance(dim, float):
        dim = np.array([dim])
    if isinstance(dim, list):
        dim = np.array(dim)
    if isinstance(sys, list):
        sys = np.array(sys)
    if isinstance(sys, int):
        sys = np.array([sys])

    num_sys = len(dim)
    # Allow the user to enter a single number for dim.
    if num_sys == 1:
        dim = np.array([dim, list(rho.shape)[0] / dim])
        if (np.abs(dim[1] - np.round(dim[1]))[0] >=
                2 * list(rho.shape)[0] * np.finfo(float).eps):
            raise ValueError("InvalidDim: If `dim` is a scalar, `rho` must be "
                             "square and `dim` must evenly divide `len(rho)`; "
                             "please provide the `dim` array containing the "
                             "dimensions of the subsystems.")
        dim[1] = np.round(dim[1])
        num_sys = 2

    # Allow the user to enter a vector for dim if X is square.
    if min(dim.shape) == 1 or len(dim.shape) == 1:
        # Force dim to be a row vector.
        dim = dim.T.flatten()
        dim = np.array([dim, dim])

    prod_dim_r = int(np.prod(dim[0, :]))
    prod_dim_c = int(np.prod(dim[1, :]))

    sub_prod_r = np.prod(dim[0, sys - 1])
    sub_prod_c = np.prod(dim[1, sys - 1])

    sub_sys_vec_r = prod_dim_r * np.ones(int(sub_prod_r)) / sub_prod_r
    sub_sys_vec_c = prod_dim_c * np.ones(int(sub_prod_c)) / sub_prod_c

    set_diff = list(set(list(range(1, num_sys + 1))) - set(sys))
    perm = sys.tolist()[:]
    perm.extend(set_diff)

    # Permute the subsystems so that we just have to do the partial transpose
    # on the first (potentially larger) subsystem.
    rho_permuted = permute_systems(rho, perm, dim)

    x_tmp = np.reshape(
        rho_permuted,
        [
            int(sub_sys_vec_r[0]),
            int(sub_prod_r),
            int(sub_sys_vec_c[0]),
            int(sub_prod_c),
        ],
        order="F",
    )
    y_tmp = np.transpose(x_tmp, [0, 3, 2, 1])
    z_tmp = np.reshape(y_tmp, [int(prod_dim_r), int(prod_dim_c)], order="F")

    # # Return the subsystems back to their original positions.
    # if len(sys) > 1:
    #     dim[:, sys-1] = dim[[1, 0], sys-1]

    dim = dim[:, np.array(perm) - 1]

    return permute_systems(z_tmp, perm, dim, False, True)
Пример #10
0
def partial_map(
    rho: np.ndarray,
    phi_map: Union[np.ndarray, List[List[np.ndarray]]],
    sys: int = 2,
    dim: Union[List[int], np.ndarray] = None,
) -> np.ndarray:
    r"""Apply map to a subsystem of an operator [WatPMap18]_.

    Applies the operator

    .. math::
        \left(\mathbb{I} \otimes \Phi \right) \left(\rho \right).

    In other words, it is the result of applying the channel :math:`\Phi` to the
    second subsystem of :math:`\rho`, which is assumed to act on two
    subsystems of equal dimension.

    The input `phi_map` should be provided as a Choi matrix.

    Examples
    ==========

    >>> from toqito.channels.channels.partial_map import partial_map
    >>> from toqito.channels.channels.depolarizing import depolarizing
    >>> rho = np.array([[0.3101, -0.0220-0.0219*1j, -0.0671-0.0030*1j, -0.0170-0.0694*1j],
    >>>                 [-0.0220+0.0219*1j, 0.1008, -0.0775+0.0492*1j, -0.0613+0.0529*1j],
    >>>                 [-0.0671+0.0030*1j, -0.0775-0.0492*1j, 0.1361, 0.0602 + 0.0062*1j],
    >>>                 [-0.0170+0.0694*1j, -0.0613-0.0529*1j, 0.0602-0.0062*1j, 0.4530]])
    >>> phi_x = partial_map(rho, depolarizing(2))
    [[ 0.20545+0.j       0.     +0.j      -0.0642 +0.02495j  0.     +0.j     ]
     [ 0.     +0.j       0.20545+0.j       0.     +0.j      -0.0642 +0.02495j]
     [-0.0642 -0.02495j  0.     +0.j       0.29455+0.j       0.     +0.j     ]
     [ 0.     +0.j      -0.0642 -0.02495j  0.     +0.j       0.29455+0.j     ]]

    >>> from toqito.channels.channels.partial_map import partial_map
    >>> from toqito.channels.channels.depolarizing import depolarizing
    >>> rho = np.array([[0.3101, -0.0220-0.0219*1j, -0.0671-0.0030*1j, -0.0170-0.0694*1j],
    >>>                 [-0.0220+0.0219*1j, 0.1008, -0.0775+0.0492*1j, -0.0613+0.0529*1j],
    >>>                 [-0.0671+0.0030*1j, -0.0775-0.0492*1j, 0.1361, 0.0602 + 0.0062*1j],
    >>>                 [-0.0170+0.0694*1j, -0.0613-0.0529*1j, 0.0602-0.0062*1j, 0.4530]])
    >>> phi_x = partial_map(rho, depolarizing(2), 1)
    [[0.2231+0.j      0.0191-0.00785j 0.    +0.j      0.    +0.j     ]
     [0.0191+0.00785j 0.2769+0.j      0.    +0.j      0.    +0.j     ]
     [0.    +0.j      0.    +0.j      0.2231+0.j      0.0191-0.00785j]
     [0.    +0.j      0.    +0.j      0.0191+0.00785j 0.2769+0.j     ]]

    References
    ==========
    .. [WatPMap18] Watrous, John.
        The theory of quantum information.
        Cambridge University Press, 2018.

    :param rho: A matrix.
    :param phi_map: The map to partially apply.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If `None`, all dimensions
                are assumed to be equal.
    :return: The partial map `phi_map` applied to matrix `rho`.
    """
    if dim is None:
        dim = np.round(np.sqrt(list(rho.shape))).conj().T * np.ones(2)
    if isinstance(dim, list):
        dim = np.array(dim)

    # Force dim to be a row vector.
    if dim.ndim == 1:
        dim = dim.T.flatten()
        dim = np.array([dim, dim])

    prod_dim_r1 = int(np.prod(dim[0, :sys - 1]))
    prod_dim_c1 = int(np.prod(dim[1, :sys - 1]))
    prod_dim_r2 = int(np.prod(dim[0, sys:]))
    prod_dim_c2 = int(np.prod(dim[1, sys:]))

    # Note: In the case where the Kraus operators refer to a CP map, this
    # approach of appending to the list may not work.
    if isinstance(phi_map, list):
        # The `phi_map` variable is provided as a list of Kraus operators.
        phi = []
        for i, _ in enumerate(phi_map):
            phi.append(
                np.kron(
                    np.kron(np.identity(prod_dim_r1), phi_map[i]),
                    np.identity(prod_dim_r2),
                ))
        phi_x = apply_map(rho, phi)
        return phi_x

    # The `phi_map` variable is provided as a Choi matrix.
    if isinstance(phi_map, np.ndarray):
        dim_phi = phi_map.shape

        dim = np.array([
            [
                prod_dim_r2,
                prod_dim_r2,
                int(dim[0, sys - 1]),
                int(dim_phi[0] / dim[0, sys - 1]),
                prod_dim_r1,
                prod_dim_r1,
            ],
            [
                prod_dim_c2,
                prod_dim_c2,
                int(dim[1, sys - 1]),
                int(dim_phi[1] / dim[1, sys - 1]),
                prod_dim_c1,
                prod_dim_c1,
            ],
        ])
        psi_r1 = max_entangled(prod_dim_r2, False, False)
        psi_c1 = max_entangled(prod_dim_c2, False, False)
        psi_r2 = max_entangled(prod_dim_r1, False, False)
        psi_c2 = max_entangled(prod_dim_c1, False, False)

        phi_map = permute_systems(
            np.kron(np.kron(psi_r1 * psi_c1.conj().T, phi_map),
                    psi_r2 * psi_c2.conj().T),
            [1, 3, 5, 2, 4, 6],
            dim,
        )

        phi_x = apply_map(rho, phi_map)

        return phi_x

    raise ValueError("The `phi_map` variable is assumed to be provided as "
                     "either a Choi matrix or a list of Kraus operators.")
Пример #11
0
def swap(
    rho: np.ndarray,
    sys: List[int] = None,
    dim: Union[List[int], List[List[int]], int, np.ndarray] = None,
    row_only: bool = False,
) -> np.ndarray:
    r"""
    Swap two subsystems within a state or operator.

    Swaps the two subsystems of the vector or matrix `rho`, where the
    dimensions of the (possibly more than 2) subsystems are given by `dim` and
    the indices of the two subsystems to be swapped are specified in the 1-by-2
    vector `sys`.

    If `rho` is non-square and not a vector, different row and column
    dimensions can be specified by putting the row dimensions in the first row
    of `dim` and the column dimensions in the second row of `dim`.

    If `row_only` is set to `True`, then only the rows of `rho` are swapped,
    but not the columns -- this is equivalent to multiplying `rho` on the left
    by the corresponding swap operator, but not on the right.

    Examples
    ==========

    Consider the following matrix

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

    If we apply the `swap` function provided by `toqito` on :math:`X`, we should
    obtain the following matrix

    .. math::
        \text{Swap}(X) =
        \begin{pmatrix}
            1 & 9 & 5 & 13 \\
            3 & 11 & 7 & 15 \\
            2 & 10 & 6 & 14 \\
            4 & 12 & 8 & 16
        \end{pmatrix}

    This can be observed by the following example in `toqito`.

    >>> from toqito.perms.swap import swap
    >>> import numpy as np
    >>> test_mat = np.array(
    >>>     [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]
    >>> )
    >>> swap(test_mat)
    [[ 1  9  5 13]
     [ 3 11  7 15]
     [ 2 10  6 14]
     [ 4 12  8 16]]

    It is also possible to use the `sys` and `dim` arguments, it is possible to
    specify the system and dimension on which to apply the swap operator. For
    instance for `sys = [1 ,2]` and `dim = 2` we have that

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

    Using `toqito` we can see this gives the proper result.

    >>> from toqito.perms.swap import swap
    >>> import numpy as np
    >>> test_mat = np.array(
    >>>     [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]
    >>> )
    >>> swap(test_mat, [1, 2], 2)
    [[ 1  9  5 13]
     [ 3 11  7 15]
     [ 2 10  6 14]
     [ 4 12  8 16]]

    It is also possible to perform the `swap` function on vectors in addition to
    matrices.

    >>> from toqito.perms.swap import swap
    >>> import numpy as np
    >>> test_vec = np.array([1, 2, 3, 4])
    >>> swap(test_vec)
    [1 3 2 4]

    :param rho: A vector or matrix to have its subsystems swapped.
    :param sys: Default: [1, 2]
    :param dim: Default: [sqrt(len(X), sqrt(len(X)))]
    :param row_only: Default: False
    :return: The swapped matrix.
    """
    eps = np.finfo(float).eps
    if len(rho.shape) == 1:
        rho_dims = (1, rho.shape[0])
    else:
        rho_dims = rho.shape

    round_dim = np.round(np.sqrt(rho_dims))

    if sys is None:
        sys = [1, 2]

    if isinstance(dim, list):
        dim = np.array(dim)
    if dim is None:
        dim = np.array([[round_dim[0], round_dim[0]],
                        [round_dim[1], round_dim[1]]])

    if isinstance(dim, int):
        dim = np.array([[dim, rho_dims[0] / dim], [dim, rho_dims[1] / dim]])
        if (np.abs(dim[0, 1] - np.round(dim[0, 1])) +
                np.abs(dim[1, 1] - np.round(dim[1, 1])) >=
                2 * np.prod(rho_dims) * eps):
            val_error = """
                InvalidDim: The value of `dim` must evenly divide the number of
                rows and columns of `rho`; please provide the `dim` array
                containing the dimensions of the subsystems.
            """
            raise ValueError(val_error)

        dim[0, 1] = np.round(dim[0, 1])
        dim[1, 1] = np.round(dim[1, 1])
        num_sys = 2
    else:
        num_sys = len(dim)

    # Verify that the input sys makes sense.
    if any(sys) < 1 or any(sys) > num_sys:
        val_error = """
            InvalidSys: The subsystems in `sys` must be between 1 and 
            `len(dim).` inclusive.
        """
        raise ValueError(val_error)
    if len(sys) != 2:
        val_error = """
            InvalidSys: `sys` must be a vector with exactly two elements.
        """
        raise ValueError(val_error)

    # Swap the indicated subsystems.
    perm = list(range(1, num_sys + 1))
    perm = perm[::-1]
    return permute_systems(rho, perm, dim, row_only)