utils.py 13.2 KB
Newer Older
Q
Quleaf 已提交
1
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
Q
Quleaf 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import reduce

Q
Quleaf 已提交
17
import numpy as np
Q
Quleaf 已提交
18
from numpy import absolute, log
Q
Quleaf 已提交
19 20
from numpy import diag, dot, identity
from numpy import kron as np_kron
Q
Quleaf 已提交
21 22 23
from numpy import trace as np_trace
from numpy import matmul as np_matmul
from numpy import random as np_random
Q
Quleaf 已提交
24 25 26 27 28
from numpy import linalg, sqrt
from numpy import sum as np_sum
from numpy import transpose as np_transpose
from numpy import zeros as np_zeros

Q
Quleaf 已提交
29 30 31 32
from paddle import add, to_tensor
from paddle import kron as pp_kron
from paddle import matmul
from paddle import transpose as pp_transpose
Q
Quleaf 已提交
33

Q
Quleaf 已提交
34 35
from paddle import concat, cos, ones, reshape, sin
from paddle import zeros as pp_zeros
Q
Quleaf 已提交
36

Q
Quleaf 已提交
37 38
from scipy.linalg import logm, sqrtm

Q
Quleaf 已提交
39 40
import paddle

Q
Quleaf 已提交
41 42
__all__ = [
    "partial_trace",
Q
Quleaf 已提交
43 44 45 46 47
    "state_fidelity",
    "gate_fidelity",
    "purity",
    "von_neumann_entropy",
    "relative_entropy",
Q
Quleaf 已提交
48
    "NKron",
Q
Quleaf 已提交
49
    "dagger",
Q
Quleaf 已提交
50
    "random_pauli_str_generator",
Q
Quleaf 已提交
51 52 53 54 55 56
    "pauli_str_to_matrix",
    "partial_transpose_2",
    "partial_transpose",
    "negativity",
    "logarithmic_negativity",
    "is_ppt"
Q
Quleaf 已提交
57 58 59
]


Q
Quleaf 已提交
60 61 62 63
def partial_trace(rho_AB, dim1, dim2, A_or_B):
    r"""计算量子态的偏迹。

    Args:
Q
Quleaf 已提交
64
        rho_AB (Tensor): 输入的量子态
Q
Quleaf 已提交
65 66
        dim1 (int): 系统A的维数
        dim2 (int): 系统B的维数
Q
Quleaf 已提交
67
        A_or_B (int): 1或者2,1表示计算系统A上的偏迹,2表示计算系统B上的偏迹
Q
Quleaf 已提交
68 69

    Returns:
Q
Quleaf 已提交
70
        Tensor: 输入的量子态的偏迹
Q
Quleaf 已提交
71

Q
Quleaf 已提交
72
    """
Q
Quleaf 已提交
73 74 75 76
    if A_or_B == 2:
        dim1, dim2 = dim2, dim1

    idty_np = identity(dim2).astype("complex128")
Q
Quleaf 已提交
77
    idty_B = to_tensor(idty_np)
Q
Quleaf 已提交
78 79

    zero_np = np_zeros([dim2, dim2], "complex128")
Q
Quleaf 已提交
80
    res = to_tensor(zero_np)
Q
Quleaf 已提交
81 82 83 84 85

    for dim_j in range(dim1):
        row_top = pp_zeros([1, dim_j], dtype="float64")
        row_mid = ones([1, 1], dtype="float64")
        row_bot = pp_zeros([1, dim1 - dim_j - 1], dtype="float64")
Q
Quleaf 已提交
86 87
        bra_j = concat([row_top, row_mid, row_bot], axis=1)
        bra_j = paddle.cast(bra_j, 'complex128')
Q
Quleaf 已提交
88

Q
Quleaf 已提交
89 90
        if A_or_B == 1:
            row_tmp = pp_kron(bra_j, idty_B)
Q
Quleaf 已提交
91 92
            row_tmp_conj = paddle.conj(row_tmp)
            res = add(res, matmul(matmul(row_tmp, rho_AB), pp_transpose(row_tmp_conj, perm=[1, 0]), ), )
Q
Quleaf 已提交
93 94 95

        if A_or_B == 2:
            row_tmp = pp_kron(idty_B, bra_j)
Q
Quleaf 已提交
96 97
            row_tmp_conj = paddle.conj(row_tmp)
            res = add(res, matmul(matmul(row_tmp, rho_AB), pp_transpose(row_tmp_conj, perm=[1, 0]), ), )
Q
Quleaf 已提交
98 99 100 101 102 103

    return res


def state_fidelity(rho, sigma):
    r"""计算两个量子态的保真度。
Q
Quleaf 已提交
104

Q
Quleaf 已提交
105 106
    .. math::
        F(\rho, \sigma) = \text{tr}(\sqrt{\sqrt{\rho}\sigma\sqrt{\rho}})
Q
Quleaf 已提交
107

Q
Quleaf 已提交
108 109 110
    Args:
        rho (numpy.ndarray): 量子态的密度矩阵形式
        sigma (numpy.ndarray): 量子态的密度矩阵形式
Q
Quleaf 已提交
111

Q
Quleaf 已提交
112 113
    Returns:
        float: 输入的量子态之间的保真度
Q
Quleaf 已提交
114
    """
Q
Quleaf 已提交
115
    assert rho.shape == sigma.shape, 'The shape of two quantum states are different'
Q
Quleaf 已提交
116
    fidelity = np.trace(sqrtm(sqrtm(rho) @ sigma @ sqrtm(rho))).real
Q
Quleaf 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130

    return fidelity


def gate_fidelity(U, V):
    r"""计算两个量子门的保真度。

    .. math::

        F(U, V) = |\text{tr}(UV^\dagger)|/2^n

    :math:`U` 是一个 :math:`2^n\times 2^n` 的 Unitary 矩阵。

    Args:
Q
Quleaf 已提交
131 132
        U (numpy.ndarray): 量子门 :math:`U` 的酉矩阵形式
        V (numpy.ndarray): 量子门 :math:`V` 的酉矩阵形式
Q
Quleaf 已提交
133 134 135

    Returns:
        float: 输入的量子门之间的保真度
Q
Quleaf 已提交
136
    """
Q
Quleaf 已提交
137 138 139 140 141
    assert U.shape == V.shape, 'The shape of two unitary matrices are different'
    dim = U.shape[0]
    fidelity = absolute(np_trace(np_matmul(U, V.conj().T)))/dim
    
    return fidelity
Q
Quleaf 已提交
142 143


Q
Quleaf 已提交
144 145
def purity(rho):
    r"""计算量子态的纯度。
Q
Quleaf 已提交
146

Q
Quleaf 已提交
147 148 149 150 151 152 153 154 155
    .. math::

        P = \text{tr}(\rho^2)

    Args:
        rho (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态的纯度
Q
Quleaf 已提交
156
    """
Q
Quleaf 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    gamma = np_trace(np_matmul(rho, rho))
    
    return gamma.real
    

def von_neumann_entropy(rho):
    r"""计算量子态的冯诺依曼熵。

    .. math::

        S = -\text{tr}(\rho \log(\rho))

    Args:
        rho(numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态的冯诺依曼熵
Q
Quleaf 已提交
174
    """
Q
Quleaf 已提交
175 176 177 178
    rho_eigenvalue, _ = linalg.eig(rho)
    entropy = -np_sum(rho_eigenvalue*log(rho_eigenvalue))
    
    return entropy.real
Q
Quleaf 已提交
179 180


Q
Quleaf 已提交
181 182
def relative_entropy(rho, sig):
    r"""计算两个量子态的相对熵。
Q
Quleaf 已提交
183

Q
Quleaf 已提交
184
    .. math::
Q
Quleaf 已提交
185

Q
Quleaf 已提交
186 187 188 189 190 191 192 193
        S(\rho \| \sigma)=\text{tr} \rho(\log \rho-\log \sigma)

    Args:
        rho (numpy.ndarray): 量子态的密度矩阵形式
        sig (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态之间的相对熵
Q
Quleaf 已提交
194
    """
Q
Quleaf 已提交
195
    assert rho.shape == sig.shape, 'The shape of two quantum states are different'
Q
Quleaf 已提交
196
    res = np.trace(rho @ logm(rho) - rho @ logm(sig))
Q
Quleaf 已提交
197 198 199 200 201 202 203 204 205 206 207 208
    return res.real


def NKron(matrix_A, matrix_B, *args):
    r"""计算两个及以上的矩阵的Kronecker积。

    Args:
        matrix_A (numpy.ndarray): 一个矩阵
        matrix_B (numpy.ndarray): 一个矩阵
        *args (numpy.ndarray): 其余矩阵

    Returns:
Q
Quleaf 已提交
209
        Tensor: 输入矩阵的Kronecker积
Q
Quleaf 已提交
210 211 212 213 214 215 216 217 218 219

    .. code-block:: python
    
        from paddle_quantum.state import density_op_random
        from paddle_quantum.utils import NKron
        A = density_op_random(2)
        B = density_op_random(2)
        C = density_op_random(2)
        result = NKron(A, B, C)

Q
Quleaf 已提交
220
    ``result`` 应为 :math:`A \otimes B \otimes C`
Q
Quleaf 已提交
221
    """
Q
Quleaf 已提交
222
    return reduce(lambda result, index: np_kron(result, index), args, np_kron(matrix_A, matrix_B), )
Q
Quleaf 已提交
223 224


Q
Quleaf 已提交
225
def dagger(matrix):
Q
Quleaf 已提交
226
    r"""计算矩阵的埃尔米特转置,即Hermitian transpose。
Q
Quleaf 已提交
227

Q
Quleaf 已提交
228
    Args:
Q
Quleaf 已提交
229
        matrix (Tensor): 需要埃尔米特转置的矩阵
Q
Quleaf 已提交
230

Q
Quleaf 已提交
231
    Returns:
Q
Quleaf 已提交
232
        Tensor: 输入矩阵的埃尔米特转置
Q
Quleaf 已提交
233

Q
Quleaf 已提交
234
    代码示例:
Q
Quleaf 已提交
235

Q
Quleaf 已提交
236 237
    .. code-block:: python
    
Q
Quleaf 已提交
238
        from paddle_quantum.utils import dagger
Q
Quleaf 已提交
239
        import numpy as np
Q
Quleaf 已提交
240 241
        rho = paddle.to_tensor(np.array([[1+1j, 2+2j], [3+3j, 4+4j]]))
        print(dagger(rho).numpy())
Q
Quleaf 已提交
242

Q
Quleaf 已提交
243
    ::
Q
Quleaf 已提交
244

Q
Quleaf 已提交
245 246
        [[1.-1.j 3.-3.j]
        [2.-2.j 4.-4.j]]
Q
Quleaf 已提交
247
    """
Q
Quleaf 已提交
248 249
    matrix_conj = paddle.conj(matrix)
    matrix_dagger = pp_transpose(matrix_conj, perm=[1, 0])
Q
Quleaf 已提交
250 251

    return matrix_dagger
Q
Quleaf 已提交
252 253


Q
Quleaf 已提交
254 255
def random_pauli_str_generator(n, terms=3):
    r"""随机生成一个可观测量(observable)的列表( ``list`` )形式。
Q
Quleaf 已提交
256

Q
Quleaf 已提交
257 258 259
    一个可观测量 :math:`O=0.3X\otimes I\otimes I+0.5Y\otimes I\otimes Z` 的
    列表形式为 ``[[0.3, 'x0'], [0.5, 'y0,z2']]`` 。这样一个可观测量是由
    调用 ``random_pauli_str_generator(3, terms=2)`` 生成的。
Q
Quleaf 已提交
260

Q
Quleaf 已提交
261 262 263 264 265 266
    Args:
        n (int): 量子比特数量
        terms (int, optional): 可观测量的项数

    Returns:
        list: 随机生成的可观测量的列表形式
Q
Quleaf 已提交
267
    """
Q
Quleaf 已提交
268 269
    pauli_str = []
    for sublen in np_random.randint(1, high=n+1, size=terms):
Q
Quleaf 已提交
270 271
        # Tips: -1 <= coeff < 1
        coeff = np_random.rand()*2-1
Q
Quleaf 已提交
272 273 274
        ops = np_random.choice(['x', 'y', 'z'], size=sublen)
        pos = np_random.choice(range(n), size=sublen, replace=False)
        op_list = [ops[i]+str(pos[i]) for i in range(sublen)]
Q
Quleaf 已提交
275
        pauli_str.append([coeff, ','.join(op_list)])
Q
Quleaf 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    return pauli_str


def pauli_str_to_matrix(pauli_str, n):
    r"""将输入的可观测量(observable)的列表( ``list`` )形式转换为其矩阵形式。

    如输入的 ``pauli_str`` 为 ``[[0.7, 'z0,x1'], [0.2, 'z1']]`` 且 ``n=3`` ,
    则此函数返回可观测量 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I` 的
    矩阵形式。

    Args:
        pauli_str (list): 一个可观测量的列表形式
        n (int): 量子比特数量

    Returns:
        numpy.ndarray: 输入列表对应的可观测量的矩阵形式
Q
Quleaf 已提交
292
    """
Q
Quleaf 已提交
293 294
    pauli_dict = {'i': np.eye(2) + 0j, 'x': np.array([[0, 1], [1, 0]]) + 0j,
                  'y': np.array([[0, -1j], [1j, 0]]), 'z': np.array([[1, 0], [0, -1]]) + 0j}
Q
Quleaf 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

    # Parse pauli_str; 'x0,z1,y4' to 'xziiy'
    new_pauli_str = []
    for coeff, op_str in pauli_str:
        init = list('i'*n)
        op_list = op_str.split(',')
        for op in op_list:
            pos = int(op[1:])
            assert pos < n, 'n is too small'
            init[pos] = op[0]
        new_pauli_str.append([coeff, ''.join(init)])

    # Convert new_pauli_str to matrix; 'xziiy' to NKron(x, z, i, i, y)
    matrices = []
    for coeff, op_str in new_pauli_str:
        sub_matrices = []
        for op in op_str:
            sub_matrices.append(pauli_dict[op])
        if len(op_str) == 1:
            matrices.append(coeff * sub_matrices[0])
        else:
            matrices.append(coeff * NKron(sub_matrices[0], sub_matrices[1], *sub_matrices[2:]))

    return sum(matrices)
Q
Quleaf 已提交
319

Q
Quleaf 已提交
320

Q
Quleaf 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
def partial_transpose_2(density_op, sub_system=None):
    r"""计算输入量子态的 partial transpose :math:`\rho^{T_A}`

    Args:
        density_op (numpy.ndarray): 量子态的密度矩阵形式
        sub_system (int): 1或2,表示关于哪个子系统进行 partial transpose,默认为第二个

    Returns:
        float: 输入的量子态的 partial transpose

    代码示例:

    .. code-block:: python

        from paddle_quantum.utils import partial_transpose_2
        rho_test = np.arange(1,17).reshape(4,4)
        partial_transpose_2(rho_test, sub_system=1)

    ::

       [[ 1,  2,  9, 10],
        [ 5,  6, 13, 14],
        [ 3,  4, 11, 12],
        [ 7,  8, 15, 16]]
    """
    sys_idx = 2 if sub_system is None else 1

    # Copy the density matrix and not corrupt the original one
Q
Quleaf 已提交
349
    transposed_density_op = np.copy(density_op)
Q
Quleaf 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    if sys_idx == 2:
        for j in [0, 2]:
            for i in [0, 2]:
                transposed_density_op[i:i+2, j:j+2] = density_op[i:i+2, j:j+2].transpose()
    else:
        transposed_density_op[2:4, 0:2] = density_op[0:2, 2:4]
        transposed_density_op[0:2, 2:4] = density_op[2:4, 0:2]

    return transposed_density_op


def partial_transpose(density_op, n):
    r"""计算输入量子态的 partial transpose :math:`\rho^{T_A}`。

    Args:
        density_op (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态的 partial transpose
    """

    # Copy the density matrix and not corrupt the original one
Q
Quleaf 已提交
372
    transposed_density_op = np.copy(density_op)
Q
Quleaf 已提交
373 374 375 376 377 378
    for j in range(0, 2**n, 2):
        for i in range(0, 2**n, 2):
            transposed_density_op[i:i+2, j:j+2] = density_op[i:i+2, j:j+2].transpose()

    return transposed_density_op

Q
Quleaf 已提交
379

Q
Quleaf 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
def negativity(density_op):
    r"""计算输入量子态的 Negativity :math:`N = ||\frac{\rho^{T_A}-1}{2}||`。

    Args:
        density_op (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态的 Negativity

    代码示例:

    .. code-block:: python

        from paddle_quantum.utils import negativity
        from paddle_quantum.state import bell_state
        rho = bell_state(2)
        print("Negativity of the Bell state is:", negativity(rho))

    ::

        Negativity of the Bell state is: 0.5
    """
    # Implement the partial transpose
    density_op_T = partial_transpose_2(density_op)

    # Calculate through the equivalent expression N = sum(abs(\lambda_i)) when \lambda_i<0
    n = 0
Q
Quleaf 已提交
407
    eigen_val, _ = np.linalg.eig(density_op_T)
Q
Quleaf 已提交
408 409
    for val in eigen_val:
        if val < 0:
Q
Quleaf 已提交
410
            n = n + np.abs(val)
Q
Quleaf 已提交
411 412
    return n

Q
Quleaf 已提交
413

Q
Quleaf 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
def logarithmic_negativity(density_op):
    r"""计算输入量子态的 Logarithmic Negativity :math:`E_N = ||\rho^{T_A}||`。

    Args:
        density_op (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        float: 输入的量子态的 Logarithmic Negativity

    代码示例:

    .. code-block:: python

        from paddle_quantum.utils import logarithmic_negativity
        from paddle_quantum.state import bell_state
        rho = bell_state(2)
        print("Logarithmic negativity of the Bell state is:", logarithmic_negativity(rho))

    ::

        Logarithmic negativity of the Bell state is: 1.0
    """
    # Calculate the negativity
    n = negativity(density_op)

    # Calculate through the equivalent expression
Q
Quleaf 已提交
440
    log2_n = np.log2(2*n + 1)
Q
Quleaf 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    return log2_n


def is_ppt(density_op):
    r"""计算输入量子态是否满足 PPT 条件。

    Args:
        density_op (numpy.ndarray): 量子态的密度矩阵形式

    Returns:
        bool: 输入的量子态是否满足 PPT 条件

    代码示例:

    .. code-block:: python

        from paddle_quantum.utils import is_ppt
        from paddle_quantum.state import bell_state
        rho = bell_state(2)
        print("Whether the Bell state satisfies PPT condition:", is_ppt(rho))

    ::

        Whether the Bell state satisfies PPT condition: False
    """
    # By default the PPT condition is satisfied
    ppt = True

    # Detect negative eigenvalues from the partial transposed density_op
    if negativity(density_op) > 0:
        ppt = False
    return ppt