def test_permute_systems_invalid_perm_vector():
    """Invalid input for permute systems."""
    with np.testing.assert_raises(ValueError):
        test_input_mat = np.array(
            [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
        )
        permute_systems(test_input_mat, [0, 1])
def permute_systems_test_2_3_1():
    """Test permute systems for perm = [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)
    np.testing.assert_equal(np.all(bool_mat), True)
Exemple #3
0
def _operator_is_product(rho: np.ndarray,
                         dim: Union[int, List[int]] = None) -> [int, bool]:
    """
    Determine if a given matrix is a product operator.

    Given an input `rho` provided as a matrix, determine if it is a product state.
    :param rho: The matrix to check.
    :param dim: The dimension of the matrix
    :return: :code:`True` if :code:`rho` is product and :code:`False` otherwise.
    """
    if dim is None:
        dim_x = rho.shape
        sqrt_dim = np.round(np.sqrt(dim_x))

        dim = np.array([[sqrt_dim[0], sqrt_dim[0]], [sqrt_dim[1],
                                                     sqrt_dim[1]]])

    if isinstance(dim, list):
        dim = np.array(dim)

    num_sys = len(dim)

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

    op_1 = rho.reshape(int(np.prod(np.prod(dim))), 1)
    perm = swap(np.array(list(range(2 * num_sys))), [1, 2], [2, num_sys]) + 1
    perm_dim = np.concatenate((dim[1, :].astype(int), dim[0, :].astype(int)))
    op_3 = permute_systems(op_1, perm, perm_dim).reshape(-1, 1)

    return is_product(op_3, np.prod(dim, axis=0).astype(int))
def test_permute_systems_vec():
    """Permute system for perm = [2,1] and vector [1, 2, 3, 4]."""
    test_input_mat = np.array([1, 2, 3, 4])
    expected_res = np.array([1, 3, 2, 4])

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

    bool_mat = np.isclose(res, expected_res)
    np.testing.assert_equal(np.all(bool_mat), True)
def test_permute_systems_m2_m2_np_array():
    """Permute system for perm = np.array([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, np.array([2, 1]))

    bool_mat = np.isclose(res, expected_res)
    np.testing.assert_equal(np.all(bool_mat), True)
Exemple #6
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 :code:`perm`, where the :math:`i^{th}` subsystem has dimension :code:`dim[i]`.

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

    Examples
    ==========

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

    .. math::
        P_{2, [2, 1]} =
        \begin{pmatrix}
            1 & 0 & 0 & 0 \\
            0 & 0 & 1 & 0 \\
            0 & 1 & 0 & 0 \\
            0 & 0 & 0 & 1
        \end{pmatrix}

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

    >>> from toqito.perms import permutation_operator
    >>> permutation_operator(2, [2, 1])
    [[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 :code:`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)
def partial_transpose(
    rho: Union[np.ndarray, Variable],
    sys: Union[List[int], np.ndarray, int] = 2,
    dim: Union[List[int], np.ndarray] = None,
) -> Union[np.ndarray, Expression]:
    r"""Compute the partial transpose of a matrix [WikPtrans]_.

    The *partial transpose* is defined as

    .. math::
        \left( \text{T} \otimes \mathbb{I}_{\mathcal{Y}} \right)
        \left(X\right)

    where :math:`X \in \text{L}(\mathcal{X})` is a linear operator over the
    complex Euclidean space :math:`\mathcal{X}` and where :math:`\text{T}` is
    the transpose mapping :math:`\text{T} \in \text{T}(\mathcal{X})` defined as

    .. math::
        \text{T}(X) = X^{\text{T}}

    for all :math:`X \in \text{L}(\mathcal{X})`.

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

    In the case where :code:`sys` amd :code:`dim` are specified, this function
    gives the partial transpose of the matrix :code:`rho` where the dimensions
    of the (possibly more than 2) subsystems are given by the vector :code:`dim`
    and the subsystems to take the partial transpose are given by the scalar or
    vector :code:`sys`. If :code:`rho` is non-square, different row and column
    dimensions can be specified by putting the row dimensions in the first row
    of :code:`dim` and the column dimensions in the second row of :code:`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 :code:`toqito`, the partial transpose function performs the
    transposition on the second subsystem as follows.

    >>> from toqito.channels 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 :code:`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 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
    ==========
    .. [WikPtrans] Wikipedia: Partial transpose
        https://en.wikipedia.org/w/index.php?title=Partial_transpose

    :param rho: A matrix.
    :param sys: Scalar or vector specifying the size of the subsystems.
    :param dim: Dimension of the subsystems. If :code:`None`, all dimensions
                are assumed to be equal.
    :returns: The partial transpose of matrix :code:`rho`.
    """
    # If the input matrix is a CVX variable for an SDP, we convert it to a
    # numpy array, perform the partial transpose, and convert it back to a CVX
    # variable.
    if isinstance(rho, Variable):
        rho_np = expr_as_np_array(rho)
        transposed_rho = partial_transpose(rho_np, sys, dim)
        transposed_rho = np_array_as_expr(transposed_rho)
        return transposed_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(sub_sys_vec_r[0]) * int(sub_prod_c),
            int(sub_sys_vec_c[0]) * int(sub_prod_r),
        ],
        order="F",
    )

    # If z_tmp is a just a 1-D matrix, extract just the row.
    if z_tmp.shape[0] == 1:
        z_tmp = z_tmp[0]

    # Return the subsystems back to their original positions.
    dim[[0, 1], sys - 1] = dim[[1, 0], sys - 1]

    return permute_systems(z_tmp, perm, dim, False, True)
Exemple #8
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 :code:`phi_map` should be provided as a Choi matrix.

    Examples
    ==========

    >>> from toqito.channel_ops import partial_map
    >>> from toqito.channels 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.channel_ops import partial_map
    >>> from toqito.channels 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 :code:`None`, all dimensions
                are assumed to be equal.
    :return: The partial map :code:`phi_map` applied to matrix :code:`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."
    )
Exemple #9
0
def partial_trace(
    input_mat: Union[np.ndarray, Variable],
    sys: Union[int, List[int]] = 2,
    dim: Union[int, List[int]] = None,
) -> Union[np.ndarray, Expression]:
    r"""
    Compute the partial trace of a matrix [WikPtrace]_.

    The *partial trace* is defined as

    .. math::
        \left( \text{Tr} \otimes \mathbb{I}_{\mathcal{Y}} \right)
        \left(X \otimes Y \right) = \text{Tr}(X)Y

    where :math:`X \in \text{L}(\mathcal{X})` and :math:`Y \in \text{L}(\mathcal{Y})` are linear
    operators over complex Euclidean spaces :math:`\mathcal{X}` and :math:`\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 :code:`dim` and the subsystems to take the trace on are
    given by the scalar or vector :code:`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 :code:`toqito` takes the trace of the second
    subsystem.

    >>> from toqito.channels 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)
    [[ 7, 11],
     [23, 27]]

    By specifying the :code:`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 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)
    [[12, 14],
     [20, 22]]

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

    >>> from toqito.channels 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 import partial_trace
    >>> import numpy as np
    >>> partial_trace(test_input_mat, [1, 3], [2, 2, 2, 2])
    [[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 :code:`None`, all dimensions are assumed to be
                equal.
    :return: The partial trace of matrix :code:`input_mat`.
    """
    # If the input matrix is a CVX variable for an SDP, we convert it to a numpy array,
    # perform the partial trace, and convert it back to a CVX variable.
    if isinstance(input_mat, 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

    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)

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

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

    res = permute_systems(rho, perm, dim, False, True)
    expected_res = np.array([
        [1, 2, 65, 66, 9, 10, 73, 74, 33, 34, 97, 98, 41, 42, 105, 106],
        [17, 18, 81, 82, 25, 26, 89, 90, 49, 50, 113, 114, 57, 58, 121, 122],
        [5, 6, 69, 70, 13, 14, 77, 78, 37, 38, 101, 102, 45, 46, 109, 110],
        [21, 22, 85, 86, 29, 30, 93, 94, 53, 54, 117, 118, 61, 62, 125, 126],
        [
            129, 130, 193, 194, 137, 138, 201, 202, 161, 162, 225, 226, 169,
            170, 233, 234
        ],
        [
            145, 146, 209, 210, 153, 154, 217, 218, 177, 178, 241, 242, 185,
            186, 249, 250
        ],
        [
            133, 134, 197, 198, 141, 142, 205, 206, 165, 166, 229, 230, 173,
            174, 237, 238
        ],
        [
            149, 150, 213, 214, 157, 158, 221, 222, 181, 182, 245, 246, 189,
            190, 253, 254
        ],
        [3, 4, 67, 68, 11, 12, 75, 76, 35, 36, 99, 100, 43, 44, 107, 108],
        [19, 20, 83, 84, 27, 28, 91, 92, 51, 52, 115, 116, 59, 60, 123, 124],
        [7, 8, 71, 72, 15, 16, 79, 80, 39, 40, 103, 104, 47, 48, 111, 112],
        [23, 24, 87, 88, 31, 32, 95, 96, 55, 56, 119, 120, 63, 64, 127, 128],
        [
            131, 132, 195, 196, 139, 140, 203, 204, 163, 164, 227, 228, 171,
            172, 235, 236
        ],
        [
            147, 148, 211, 212, 155, 156, 219, 220, 179, 180, 243, 244, 187,
            188, 251, 252
        ],
        [
            135, 136, 199, 200, 143, 144, 207, 208, 167, 168, 231, 232, 175,
            176, 239, 240
        ],
        [
            151, 152, 215, 216, 159, 160, 223, 224, 183, 184, 247, 248, 191,
            192, 255, 256
        ],
    ])
    bool_mat = np.isclose(res, expected_res)
    np.testing.assert_equal(np.all(bool_mat), True)
Exemple #11
0
def test_permute_systems_invalid_dim_mismatch_perm():
    """Invalid length of permutation must be equal to the length of dimension."""
    with np.testing.assert_raises(ValueError):
        test_input_mat = np.array([1, 2, 3, 4])
        permute_systems(test_input_mat, [2, 1, 3, 4])
Exemple #12
0
def test_permute_systems_invalid_empty_input():
    """Invalid input for input matrix for permute systems."""
    with np.testing.assert_raises(ValueError):
        test_input_mat = np.array([[]])
        permute_systems(test_input_mat, [2, 1])
Exemple #13
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 :code:`rho`, where the dimensions of the
    (possibly more than 2) subsystems are given by :code:`dim` and the indices of the two subsystems
    to be swapped are specified in the 1-by-2 vector :code:`sys`.

    If :code:`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 :code:`dim` and the column
    dimensions in the second row of :code:`dim`.

    If :code:`row_only` is set to :code:`True`, then only the rows of :code:`rho` are swapped, but
    not the columns -- this is equivalent to multiplying :code:`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 :code:`swap` function provided by :code:`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 :code:`toqito`.

    >>> from toqito.perms 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 :code:`sys` and :code:`dim` arguments, it is possible to specify
    the system and dimension on which to apply the swap operator. For instance for
    :code:`sys = [1 ,2]` and :code:`dim = 2` we have that

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

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

    >>> from toqito.perms 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 :code:`swap` function on vectors in addition to matrices.

    >>> from toqito.perms 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: :code:`[sqrt(len(X), sqrt(len(X)))]`
    :param row_only: Default: :code:`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 = np.array(range(1, num_sys + 1))
    sys = np.array(sys) - 1

    perm[sys] = perm[sys[::-1]]

    return permute_systems(rho, perm, dim, row_only)
Exemple #14
0
def brauer(dim: int, p_val: int) -> np.ndarray:
    r"""
    Produce all Brauer states [WikBrauer]_.

    Produce a matrix whose columns are all of the (unnormalized) "Brauer" states: states that are
    the :code:`p_val`-fold tensor product of the standard maximally-entangled pure state on
    :code:`dim` local dimensions. There are many such states, since there are many different ways to
    group the :code:`2 * p_val` parties into :code:`p_val` pairs (with each pair corresponding to
    one maximally-entangled state).

    The exact number of such states is:

    ```python
    np.factorial(2 * p_val) / (np.factorial(p_val) * 2**p_val)
    ```

    which is the number of columns of the returned matrix.

    This function has been adapted from QETLAB.

    Examples
    ==========

    Generate a matrix whose columns are all Brauer states on 4 qubits.

    >>> from toqito.states import brauer
    >>> brauer(2, 2)
    [[1. 1. 1.]
     [0. 0. 0.]
     [0. 0. 0.]
     [1. 0. 0.]
     [0. 0. 0.]
     [0. 1. 0.]
     [0. 0. 1.]
     [0. 0. 0.]
     [0. 0. 0.]
     [0. 0. 1.]
     [0. 1. 0.]
     [0. 0. 0.]
     [1. 0. 0.]
     [0. 0. 0.]
     [0. 0. 0.]
     [1. 1. 1.]]

    References
    ==========
    .. [WikBrauer] Wikipedia: Brauer algebra
        https://en.wikipedia.org/wiki/Brauer_algebra

    :param dim: Dimension of each local subsystem
    :param p_val: Half of the number of parties (i.e., the state that this function computes will
                  live in :math:`(\mathbb{C}^D)^{\otimes 2 P})`
    :return: Matrix whose columns are all of the unnormalized Brauer states.
    """
    # The Brauer states are computed from perfect matchings of the complete graph. So compute all
    # perfect matchings first.
    phi = tensor(max_entangled(dim, False, False), p_val)
    matchings = perfect_matchings(2 * p_val)
    num_matchings = matchings.shape[0]
    state = np.zeros((dim**(2 * p_val), num_matchings))

    # Turn these perfect matchings into the corresponding states.
    for i in range(num_matchings):
        state[:,
              i] = permute_systems(phi, matchings[i, :],
                                   dim * np.ones((1, 2 * p_val), dtype=int)[0])
    return state