utils.py 33.3 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# 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.

Q
Quleaf 已提交
15 16
r"""
This module contains various common classes and functions used for computation.
Q
Quleaf 已提交
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
"""

from numpy import array, exp, pi, linalg
from numpy import sqrt as np_sqrt
from numpy import random as np_random
from paddle import Tensor, to_tensor, t, cos, eye, sin
from paddle import kron as pp_kron
from paddle import matmul, conj, real
from paddle import reshape, transpose
from paddle import sqrt as pp_sqrt
from paddle import multiply
from paddle_quantum.mbqc.qobject import State
import matplotlib.pyplot as plt

__all__ = ["plus_state",
           "minus_state",
           "zero_state",
           "one_state",
           "h_gate",
           "s_gate",
           "t_gate",
           "cz_gate",
           "cnot_gate",
           "swap_gate",
           "pauli_gate",
           "rotation_gate",
           "to_projector",
           "basis",
           "kron",
           "permute_to_front",
           "permute_systems",
           "compare_by_density",
           "compare_by_vector",
           "random_state_vector",
           "div_str_to_float",
           "int_to_div_str",
           "print_progress",
           "plot_results",
           "write_running_data",
           "read_running_data"
           ]


def plus_state():
Q
Quleaf 已提交
61
    r"""Define plus state.
Q
Quleaf 已提交
62

Q
Quleaf 已提交
63
    The matrix form is:
Q
Quleaf 已提交
64 65 66 67 68 69

    .. math::

        \frac{1}{\sqrt{2}}  \begin{bmatrix}  1 \\ 1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
70
        Tensor: The ``Tensor`` form of plus state.
Q
Quleaf 已提交
71

Q
Quleaf 已提交
72
    Code example:
Q
Quleaf 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    .. code-block:: python

        from paddle_quantum.mbqc.utils import plus_state
        print("State vector of plus state: \n", plus_state().numpy())

    ::

        State vector of plus state:
         [[0.70710678]
         [0.70710678]]
    """
    return to_tensor([[1 / np_sqrt(2)], [1 / np_sqrt(2)]], dtype='float64')


def minus_state():
Q
Quleaf 已提交
89
    r"""Define minus state.
Q
Quleaf 已提交
90

Q
Quleaf 已提交
91
    The matrix form is:
Q
Quleaf 已提交
92 93 94 95 96 97

    .. math::

        \frac{1}{\sqrt{2}}  \begin{bmatrix}  1 \\ -1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
98
        Tensor: The ``Tensor`` form of minus state.
Q
Quleaf 已提交
99

Q
Quleaf 已提交
100
    Code example:
Q
Quleaf 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

    .. code-block:: python

        from paddle_quantum.mbqc.utils import minus_state
        print("State vector of minus state: \n", minus_state().numpy())

    ::

        State vector of minus state:
         [[ 0.70710678]
         [-0.70710678]]
    """
    return to_tensor([[1 / np_sqrt(2)], [-1 / np_sqrt(2)]], dtype='float64')


def zero_state():
Q
Quleaf 已提交
117
    r"""Define zero state.
Q
Quleaf 已提交
118

Q
Quleaf 已提交
119
    The matrix form is:
Q
Quleaf 已提交
120 121 122 123 124 125

    .. math::

        \begin{bmatrix}  1 \\ 0 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
126
        Tensor: The ``Tensor`` form of zero state.
Q
Quleaf 已提交
127

Q
Quleaf 已提交
128
    Code example:
Q
Quleaf 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    .. code-block:: python

        from paddle_quantum.mbqc.utils import zero_state
        print("State vector of zero state: \n", zero_state().numpy())

    ::

        State vector of zero state:
         [[1.]
         [0.]]
    """
    return to_tensor([[1], [0]], dtype='float64')


def one_state():
Q
Quleaf 已提交
145
    r"""Define one state.
Q
Quleaf 已提交
146

Q
Quleaf 已提交
147
    The matrix form is:
Q
Quleaf 已提交
148 149 150 151 152 153

    .. math::

        \begin{bmatrix}  0 \\ 1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
154
        Tensor: The ``Tensor`` form of one state.
Q
Quleaf 已提交
155

Q
Quleaf 已提交
156
    Code example:
Q
Quleaf 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

    .. code-block:: python

        from paddle_quantum.mbqc.utils import one_state
        print("State vector of one state: \n", one_state().numpy())

    ::

        State vector of one state:
         [[0.]
         [1.]]
    """
    return to_tensor([[0], [1]], dtype='float64')


def h_gate():
Q
Quleaf 已提交
173
    r"""Define ``Hadamard`` gate.
Q
Quleaf 已提交
174

Q
Quleaf 已提交
175
    The matrix form is:
Q
Quleaf 已提交
176 177 178 179 180 181

    .. math::

        \frac{1}{\sqrt{2}} \begin{bmatrix}  1 & 1 \\ 1 & -1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
182
        Tensor: The ``Tensor`` form of ``Hadamard`` gate.
Q
Quleaf 已提交
183

Q
Quleaf 已提交
184
    Code example:
Q
Quleaf 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

    .. code-block:: python

        from paddle_quantum.mbqc.utils import h_gate
        print("Matrix of Hadamard gate: \n", h_gate().numpy())

    ::

        Matrix of Hadamard gate:
         [[ 0.70710678  0.70710678]
         [ 0.70710678 -0.70710678]]
    """
    return to_tensor((1 / np_sqrt(2)) * array([[1, 1], [1, -1]]), dtype='float64')


def s_gate():
Q
Quleaf 已提交
201
    r"""Define ``S`` gate.
Q
Quleaf 已提交
202

Q
Quleaf 已提交
203
    The matrix form is:
Q
Quleaf 已提交
204 205 206 207 208 209 210 211

    .. math::

        \begin{bmatrix}  1 & 0 \\ 0 & i \end{bmatrix}

    Returns:
        Tensor: ``S`` 门矩阵对应的 ``Tensor`` 形式

Q
Quleaf 已提交
212
    Code example:
Q
Quleaf 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

    .. code-block:: python

        from paddle_quantum.mbqc.utils import s_gate
        print("Matrix of S gate:\n", s_gate().numpy())

    ::

        Matrix of S gate:
         [[1.+0.j 0.+0.j]
         [0.+0.j 0.+1.j]]
    """
    return to_tensor([[1, 0], [0, 1j]], dtype='complex128')


def t_gate():
Q
Quleaf 已提交
229
    r"""Define ``T`` gate.
Q
Quleaf 已提交
230

Q
Quleaf 已提交
231
    The matrix form is:
Q
Quleaf 已提交
232 233 234 235 236 237

    .. math::

        \begin{bmatrix}  1 & 0 \\ 0 & e^{i \pi / 4} \end{bmatrix}

    Returns:
Q
Quleaf 已提交
238
        Tensor: The ``Tensor`` form of ``T`` gate.
Q
Quleaf 已提交
239

Q
Quleaf 已提交
240
    Code example:
Q
Quleaf 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

    .. code-block:: python

        from paddle_quantum.mbqc.utils import t_gate
        print("Matrix of T gate: \n", t_gate().numpy())

    ::

        Matrix of T gate:
         [[1.        +0.j         0.        +0.j        ]
         [0.        +0.j         0.70710678+0.70710678j]]
    """
    return to_tensor([[1, 0], [0, exp(1j * pi / 4)]], dtype='complex128')


def cz_gate():
Q
Quleaf 已提交
257
    r"""Define ``Controlled-Z`` gate.
Q
Quleaf 已提交
258

Q
Quleaf 已提交
259
    The matrix form is:
Q
Quleaf 已提交
260 261 262 263 264 265

    .. math::

        \begin{bmatrix}  1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
266
        Tensor: The ``Tensor`` form of ``Controlled-Z`` gate.
Q
Quleaf 已提交
267

Q
Quleaf 已提交
268
    Code example:
Q
Quleaf 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

    .. code-block:: python

        from paddle_quantum.mbqc.utils import cz_gate
        print("Matrix of CZ gate: \n", cz_gate().numpy())

    ::

        Matrix of CZ gate:
         [[ 1.  0.  0.  0.]
         [ 0.  1.  0.  0.]
         [ 0.  0.  1.  0.]
         [ 0.  0.  0. -1.]]
    """
    return to_tensor([[1, 0, 0, 0],
                      [0, 1, 0, 0],
                      [0, 0, 1, 0],
                      [0, 0, 0, -1]], dtype='float64')


def cnot_gate():
Q
Quleaf 已提交
290
    r"""Define ``Controlled-NOT (CNOT)`` gate.
Q
Quleaf 已提交
291

Q
Quleaf 已提交
292
    The matrix form is:
Q
Quleaf 已提交
293 294 295 296 297 298

    .. math::

        \begin{bmatrix}  1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
299
        Tensor: The ``Tensor`` form of ``Controlled-NOT (CNOT)`` gate.
Q
Quleaf 已提交
300

Q
Quleaf 已提交
301
    Code example:
Q
Quleaf 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    .. code-block:: python

        from paddle_quantum.mbqc.utils import cnot_gate
        print("Matrix of CNOT gate: \n", cnot_gate().numpy())

    ::

        Matrix of CNOT gate:
         [[1. 0. 0. 0.]
         [0. 1. 0. 0.]
         [0. 0. 0. 1.]
         [0. 0. 1. 0.]]
    """
    return to_tensor([[1, 0, 0, 0],
                      [0, 1, 0, 0],
                      [0, 0, 0, 1],
                      [0, 0, 1, 0]], dtype='float64')


def swap_gate():
Q
Quleaf 已提交
323
    r"""Define ``SWAP`` gate.
Q
Quleaf 已提交
324

Q
Quleaf 已提交
325
    The matrix form is:
Q
Quleaf 已提交
326 327 328 329 330 331

    .. math::

        \begin{bmatrix}  1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

    Returns:
Q
Quleaf 已提交
332
        Tensor: The ``Tensor`` form of ``SWAP`` gate.
Q
Quleaf 已提交
333

Q
Quleaf 已提交
334
    Code example:
Q
Quleaf 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

    .. code-block:: python

        from paddle_quantum.mbqc.utils import swap_gate
        print("Matrix of Swap gate: \n", swap_gate().numpy())

    ::

        Matrix of Swap gate:
         [[1. 0. 0. 0.]
         [0. 0. 1. 0.]
         [0. 1. 0. 0.]
         [0. 0. 0. 1.]]
    """
    return to_tensor([[1, 0, 0, 0],
                      [0, 0, 1, 0],
                      [0, 1, 0, 0],
                      [0, 0, 0, 1]], dtype='float64')


def pauli_gate(gate):
Q
Quleaf 已提交
356
    r"""Define ``Pauli`` gate.
Q
Quleaf 已提交
357

Q
Quleaf 已提交
358
    The matrix form of Identity gate ``I`` is:
Q
Quleaf 已提交
359 360 361 362 363

    .. math::

        \begin{bmatrix}  1 & 0 \\ 0 & 1 \end{bmatrix}

Q
Quleaf 已提交
364
    The matrix form of Pauli gate ``X`` is:
Q
Quleaf 已提交
365 366 367 368 369

    .. math::

        \begin{bmatrix}  0 & 1 \\ 1 & 0 \end{bmatrix}

Q
Quleaf 已提交
370
    The matrix form of Pauli gate ``Y`` is:
Q
Quleaf 已提交
371 372 373 374 375

    .. math::

        \begin{bmatrix}  0 & - i \\ i & 0 \end{bmatrix}

Q
Quleaf 已提交
376
    The matrix form of Pauli gate ``Z`` is:
Q
Quleaf 已提交
377 378 379 380 381 382

    .. math::

        \begin{bmatrix}  1 & 0 \\ 0 & - 1 \end{bmatrix}

    Args:
Q
Quleaf 已提交
383
        gate (str): Index of Pauli gate. “I”, “X”, “Y”, or “Z” denotes the corresponding gate.
Q
Quleaf 已提交
384 385

    Returns:
Q
Quleaf 已提交
386
        Tensor: The matrix form of the Pauli gate.
Q
Quleaf 已提交
387

Q
Quleaf 已提交
388
    Code example:
Q
Quleaf 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

    .. code-block:: python

        from paddle_quantum.mbqc.utils import pauli_gate
        I = pauli_gate('I')
        X = pauli_gate('X')
        Y = pauli_gate('Y')
        Z = pauli_gate('Z')
        print("Matrix of Identity gate: \n", I.numpy())
        print("Matrix of Pauli X gate: \n", X.numpy())
        print("Matrix of Pauli Y gate: \n", Y.numpy())
        print("Matrix of Pauli Z gate: \n", Z.numpy())

    ::

        Matrix of Identity gate:
         [[1. 0.]
         [0. 1.]]
        Matrix of Pauli X gate:
         [[0. 1.]
         [1. 0.]]
        Matrix of Pauli Y gate:
         [[ 0.+0.j -0.-1.j]
         [ 0.+1.j  0.+0.j]]
        Matrix of Pauli Z gate:
         [[ 1.  0.]
         [ 0. -1.]]
    """
    if gate == 'I':  # Identity gate
        return to_tensor(eye(2, 2), dtype='float64')
    elif gate == 'X':  # Pauli X gate
        return to_tensor([[0, 1], [1, 0]], dtype='float64')
    elif gate == 'Y':  # Pauli Y gate
        return to_tensor([[0, -1j], [1j, 0]], dtype='complex128')
    elif gate == 'Z':  # Pauli Z gate
        return to_tensor([[1, 0], [0, -1]], dtype='float64')
    else:
        print("The Pauli gate must be 'I', 'X', 'Y' or 'Z'.")
        raise KeyError("invalid Pauli gate index: %s" % gate + ".")


def rotation_gate(axis, theta):
Q
Quleaf 已提交
431
    r"""Define Rotation gate.
Q
Quleaf 已提交
432 433 434 435 436 437 438 439 440 441

    .. math::

        R_{x}(\theta) = \cos(\theta / 2) I - i\sin(\theta / 2) X

        R_{y}(\theta) = \cos(\theta / 2) I - i\sin(\theta / 2) Y

        R_{z}(\theta) = \cos(\theta / 2) I - i\sin(\theta / 2) Z

    Args:
Q
Quleaf 已提交
442 443
        axis (str): Rotation axis. 'x', 'y' or 'z' denotes the corresponding axis.
        theta (Tensor): Rotation angle.
Q
Quleaf 已提交
444 445

    Returns:
Q
Quleaf 已提交
446
        Tensor: The matrix form of Rotation gate.
Q
Quleaf 已提交
447

Q
Quleaf 已提交
448
    Code example:
Q
Quleaf 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

    .. code-block:: python

        from numpy import pi
        from paddle import to_tensor
        from paddle_quantum.mbqc.utils import rotation_gate

        theta = to_tensor([pi / 6], dtype='float64')
        Rx = rotation_gate('x', theta)
        Ry = rotation_gate('y', theta)
        Rz = rotation_gate('z', theta)
        print("Matrix of Rotation X gate with angle pi/6: \n", Rx.numpy())
        print("Matrix of Rotation Y gate with angle pi/6: \n", Ry.numpy())
        print("Matrix of Rotation Z gate with angle pi/6: \n", Rz.numpy())

    ::

        Matrix of Rotation X gate with angle pi/6:
         [[0.96592583+0.j         0.        -0.25881905j]
         [0.        -0.25881905j 0.96592583+0.j        ]]
        Matrix of Rotation Y gate with angle pi/6:
         [[ 0.96592583+0.j -0.25881905+0.j]
         [ 0.25881905+0.j  0.96592583+0.j]]
        Matrix of Rotation Z gate with angle pi/6:
         [[0.96592583-0.25881905j 0.        +0.j        ]
         [0.        +0.j         0.96592583+0.25881905j]]
    """
    # Check if the input theta is a Tensor and has 'float64' datatype
    float64_tensor = to_tensor([], dtype='float64')
    assert isinstance(theta, Tensor) and theta.dtype == float64_tensor.dtype, \
        "The rotation angle should be a Tensor and of type 'float64'."

    # Calculate half of the input theta
    half_theta = multiply(theta, to_tensor([0.5], dtype='float64'))

    if axis == 'x':  # Define the rotation - x gate matrix
        return multiply(pauli_gate('I'), cos(half_theta)) + \
               multiply(pauli_gate('X'), multiply(sin(half_theta), to_tensor([-1j], dtype='complex128')))
    elif axis == 'y':  # Define the rotation - y gate matrix
        return multiply(pauli_gate('I'), cos(half_theta)) + \
               multiply(pauli_gate('Y'), multiply(sin(half_theta), to_tensor([-1j], dtype='complex128')))
    elif axis == 'z':  # Define the rotation - z gate matrix
        return multiply(pauli_gate('I'), cos(half_theta)) + \
               multiply(pauli_gate('Z'), multiply(sin(half_theta), to_tensor([-1j], dtype='complex128')))
    else:
        raise KeyError("invalid rotation gate index: %s, the rotation axis must be 'x', 'y' or 'z'." % axis)


def to_projector(vector):
Q
Quleaf 已提交
498
    r"""Transform a vector into its density matrix (or measurement projector).
Q
Quleaf 已提交
499 500 501 502 503 504

    .. math::

        |\psi\rangle \to |\psi\rangle\langle\psi|

    Args:
Q
Quleaf 已提交
505
        vector (Tensor): Vector of a quantum state or a measurement basis
Q
Quleaf 已提交
506 507

    Returns:
Q
Quleaf 已提交
508
        Tensor: Density matrix (or measurement projector)
Q
Quleaf 已提交
509

Q
Quleaf 已提交
510
    Code example:
Q
Quleaf 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

    .. code-block:: python

        from paddle_quantum.mbqc.utils import zero_state, plus_state
        from paddle_quantum.mbqc.utils import to_projector

        zero_proj = to_projector(zero_state())
        plus_proj = to_projector(plus_state())
        print("The projector of zero state: \n", zero_proj.numpy())
        print("The projector of plus state: \n", plus_proj.numpy())

    ::

        The projector of zero state:
         [[1. 0.]
         [0. 0.]]
        The projector of plus state:
         [[0.5 0.5]
         [0.5 0.5]]
    """
    assert isinstance(vector, Tensor) and vector.shape[0] >= 1 and vector.shape[1] == 1, \
        "'vector' must be a Tensor of shape (x, 1) with x >= 1."
    return matmul(vector, t(conj(vector)))


def basis(label, theta=to_tensor([0], dtype='float64')):
Q
Quleaf 已提交
537
    r"""Measurement basis.
Q
Quleaf 已提交
538 539

    Note:
Q
Quleaf 已提交
540
        Commonly used measurements are measurements in the XY and YZ planes, and Pauli X, Y, Z measurements.
Q
Quleaf 已提交
541 542

    .. math::
Q
Quleaf 已提交
543 544 545 546 547 548 549
        \begin{align*}
        & M^{XY}(\theta) = \{R_{z}(\theta)|+\rangle, R_{z}(\theta)|-\rangle\}\\
        & M^{YZ}(\theta) = \{R_{x}(\theta)|0\rangle, R_{x}(\theta)|1\rangle\}\\
        & X = M^{XY}(0)\\
        & Y = M^{YZ}(\pi / 2) = M^{XY}(-\pi / 2)\\
        & Z = M_{YZ}(0)
        \end{align*}
Q
Quleaf 已提交
550 551

    Args:
Q
Quleaf 已提交
552 553 554 555
        label (str): the labels of the measurement basis, "XY" denotes XY plane, "YZ" denotes YZ plane, 
            "X" denotes X measurement, "Y" denotes Y measurement, "Z" denotes Z measurement.
        theta (Tensor, optional): measurement angle, the parameter is needed when the measurement is in
            XY plane or YZ plane.
Q
Quleaf 已提交
556 557

    Returns:
Q
Quleaf 已提交
558
        list: the list composed of measurement basis, the elements are of type ``Tensor``.
Q
Quleaf 已提交
559

Q
Quleaf 已提交
560
    Code example:
Q
Quleaf 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

    .. code-block:: python

        from numpy import pi
        from paddle import to_tensor
        from paddle_quantum.mbqc.utils import basis
        theta = to_tensor(pi / 6, dtype='float64')
        YZ_plane_basis = basis('YZ', theta)
        XY_plane_basis = basis('XY', theta)
        X_basis = basis('X')
        Y_basis = basis('Y')
        Z_basis = basis('Z')
        print("Measurement basis in YZ plane: \n", YZ_plane_basis)
        print("Measurement basis in XY plane: \n", XY_plane_basis)
        print("Measurement basis of X: \n", X_basis)
        print("Measurement basis of Y: \n", Y_basis)
        print("Measurement basis of Z: \n", Z_basis)

    ::

        Measurement basis in YZ plane:
         [Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[(0.9659258262890683+0j)],
                [-0.25881904510252074j  ]]),
          Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[-0.25881904510252074j  ],
                [(0.9659258262890683+0j)]])]
        Measurement basis in XY plane:
         [Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[(0.6830127018922193-0.1830127018922193j)],
                [(0.6830127018922193+0.1830127018922193j)]]),
          Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[ (0.6830127018922193-0.1830127018922193j)],
                [(-0.6830127018922193-0.1830127018922193j)]])]
        Measurement basis of X:
         [Tensor(shape=[2, 1], dtype=float64, place=CPUPlace, stop_gradient=True,
               [[0.70710678],
                [0.70710678]]),
          Tensor(shape=[2, 1], dtype=float64, place=CPUPlace, stop_gradient=True,
               [[ 0.70710678],
                [-0.70710678]])]
        Measurement basis of Y:
         [Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[(0.5-0.5j)],
                [(0.5+0.5j)]]),
          Tensor(shape=[2, 1], dtype=complex128, place=CPUPlace, stop_gradient=True,
               [[ (0.5-0.5j)],
                [(-0.5-0.5j)]])]
        Measurement basis of Z:
         [Tensor(shape=[2, 1], dtype=float64, place=CPUPlace, stop_gradient=True,
               [[1.],
                [0.]]),
          Tensor(shape=[2, 1], dtype=float64, place=CPUPlace, stop_gradient=True,
               [[0.],
                [1.]])]
    """
    # Check the label and input angle
    assert label in ['XY', 'YZ', 'X', 'Y', 'Z'], "the basis label must be 'XY', 'YZ', 'X', 'Y' or 'Z'."
    float64_tensor = to_tensor([], dtype='float64')
    assert isinstance(theta, Tensor) and theta.dtype == float64_tensor.dtype, \
        "The input angle should be a tensor and of type 'float64'."

    if label == 'YZ':  # Define the YZ plane measurement basis
        return [matmul(rotation_gate('x', theta), zero_state()),
                matmul(rotation_gate('x', theta), one_state())]
    elif label == 'XY':  # Define the XY plane measurement basis
        return [matmul(rotation_gate('z', theta), plus_state()),
                matmul(rotation_gate('z', theta), minus_state())]
    elif label == 'X':  # Define the X-measurement basis
        return [plus_state(), minus_state()]
    elif label == 'Y':  # Define the Y-measurement basis
        return [matmul(rotation_gate('z', to_tensor([pi / 2], dtype='float64')), plus_state()),
                matmul(rotation_gate('z', to_tensor([pi / 2], dtype='float64')), minus_state())]
    elif label == 'Z':  # Define the Z-measurement basis
        return [zero_state(), one_state()]


def kron(tensor_list):
Q
Quleaf 已提交
639
    r"""Take the tensor product of all the elements in the list.
Q
Quleaf 已提交
640 641 642 643 644 645

    .. math::

        [A, B, C, \cdots] \to A \otimes B \otimes C \otimes \cdots

    Args:
Q
Quleaf 已提交
646
        tensor_list (list): a list contains the element to taking tensor product.
Q
Quleaf 已提交
647 648

    Returns:
Q
Quleaf 已提交
649 650
        Tensor: the results of the tensor product are of type ``Tensor``. If there is only
        one ``Tensor`` in the list, return the ``Tensor``.
Q
Quleaf 已提交
651

Q
Quleaf 已提交
652
    Code example 1:
Q
Quleaf 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

    .. code-block:: python

        from paddle import to_tensor
        from paddle_quantum.mbqc.utils import pauli_gate, kron
        tensor0 = pauli_gate('I')
        tensor1 = to_tensor([[1, 1], [1, 1]], dtype='float64')
        tensor2 = to_tensor([[1, 2], [3, 4]], dtype='float64')
        tensor_list = [tensor0, tensor1, tensor2]
        tensor_all = kron(tensor_list)
        print("The tensor product result: \n", tensor_all.numpy())

    ::

        The tensor product result:
        [[1. 2. 1. 2. 0. 0. 0. 0.]
         [3. 4. 3. 4. 0. 0. 0. 0.]
         [1. 2. 1. 2. 0. 0. 0. 0.]
         [3. 4. 3. 4. 0. 0. 0. 0.]
         [0. 0. 0. 0. 1. 2. 1. 2.]
         [0. 0. 0. 0. 3. 4. 3. 4.]
         [0. 0. 0. 0. 1. 2. 1. 2.]
         [0. 0. 0. 0. 3. 4. 3. 4.]]

Q
Quleaf 已提交
677
    Code example 2:
Q
Quleaf 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

    .. code-block:: python

        from paddle_quantum.mbqc.utils import pauli_gate, kron
        tensor0 = pauli_gate('I')
        tensor_list = [tensor0]
        tensor_all = kron(tensor_list)
        print("The tensor product result: \n", tensor_all.numpy())

    ::

        The tensor product result:
        [[1. 0.]
        [0. 1.]]
    """
    assert isinstance(tensor_list, list), "'tensor_list' must be a `list`."
    assert all(isinstance(tensor, Tensor) for tensor in tensor_list), "each element in the list must be a `Tensor`."
    kron_all = tensor_list[0]
    if len(tensor_list) > 1:  # Kron together
        for i in range(1, len(tensor_list)):
            tensor = tensor_list[i]
            kron_all = pp_kron(kron_all, tensor)
    return kron_all


def permute_to_front(state, which_system):
Q
Quleaf 已提交
704
    r"""Move a subsystem of a system to the first.
Q
Quleaf 已提交
705

Q
Quleaf 已提交
706
    Assume that a quantum state :math:`\psi\rangle` can be decomposed to tensor product form: 
Q
Quleaf 已提交
707 708 709 710 711 712

    .. math::

        |\psi\rangle = |\psi_1\rangle \otimes |\psi_2\rangle \otimes |\psi_3\rangle \otimes \cdots


Q
Quleaf 已提交
713
    the labels of each :math:`|\psi_i\rangle` is :math:`i` , so the total labels of the current system are: 
Q
Quleaf 已提交
714 715 716 717 718

    .. math::

        \text{label} = \{1, 2, 3, \cdots \}

Q
Quleaf 已提交
719
    Assume that the label of the subsystem to be moved is: i
Q
Quleaf 已提交
720

Q
Quleaf 已提交
721
    The output new quantum state is: 
Q
Quleaf 已提交
722 723 724 725 726 727

    .. math::

        |\psi_i\rangle \otimes |\psi_1\rangle \otimes \cdots |\psi_{i-1}\rangle \otimes |\psi_{i+1}\rangle \otimes \cdots

    Args:
Q
Quleaf 已提交
728 729
        state (State): the quantum state to be processed
        which_system (str): the labels of the subsystem to be moved.
Q
Quleaf 已提交
730 731

    Returns:
Q
Quleaf 已提交
732
        State: the final state after the move operation.
Q
Quleaf 已提交
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    """
    assert which_system in state.system, 'the system to permute must be in the state systems.'
    system_idx = state.system.index(which_system)
    if system_idx == 0:  # system in the front
        return state
    elif system_idx == state.size - 1:  # system in the end
        new_shape = [2 ** (state.size - 1), 2]
        new_axis = [1, 0]
        new_system = [which_system] + state.system[: system_idx]
    else:  # system in the middle
        new_shape = [2 ** system_idx, 2, 2 ** (state.size - system_idx - 1)]
        new_axis = [1, 0, 2]
        new_system = [which_system] + state.system[: system_idx] + state.system[system_idx + 1:]
    new_vector = reshape(transpose(reshape(state.vector, new_shape), new_axis), [state.length, 1])

    return State(new_vector, new_system)


def permute_systems(state, new_system):
Q
Quleaf 已提交
752
    r""" Permute the quantum system to given order
Q
Quleaf 已提交
753

Q
Quleaf 已提交
754
    Assume that a quantum state :math:`\psi\rangle` can be decomposed to tensor product form: 
Q
Quleaf 已提交
755 756 757 758 759

    .. math::

        |\psi\rangle = |\psi_1\rangle \otimes |\psi_2\rangle \otimes |\psi_3\rangle \otimes \cdots

Q
Quleaf 已提交
760
    the labels of each :math:`|\psi_i\rangle` is :math:`i` , so the total labels of the current system are: 
Q
Quleaf 已提交
761 762 763 764 765

    .. math::

        \text{label} = \{1, 2, 3, \cdots \}

Q
Quleaf 已提交
766
    the order of labels of the given new system is: 
Q
Quleaf 已提交
767 768 769 770 771

    .. math::

        \{i_1, i_2, i_3, \cdots \}

Q
Quleaf 已提交
772
    The output new quantum state is: 
Q
Quleaf 已提交
773 774 775 776 777 778

    .. math::

        |\psi_{i_1}\rangle \otimes |\psi_{i_2}\rangle \otimes |\psi_{i_3}\rangle \otimes \cdots

    Args:
Q
Quleaf 已提交
779 780
        state (State): the quantum state to be processed
        new_system (list): target order of the system
Q
Quleaf 已提交
781 782

    Returns:
Q
Quleaf 已提交
783
        State: the quantum state after permutation.
Q
Quleaf 已提交
784 785 786 787 788 789 790
    """
    for label in reversed(new_system):
        state = permute_to_front(state, label)
    return state


def compare_by_density(state1, state2):
Q
Quleaf 已提交
791
    r"""Compare whether two quantum states are the same by their density operators.
Q
Quleaf 已提交
792 793

    Args:
Q
Quleaf 已提交
794 795
        state1 (State): the first quantum state
        state2 (State): the second quantum state
Q
Quleaf 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    """
    assert state1.size == state2.size, "two state vectors compared are not of the same length."

    # Permute the system order
    new_state1 = permute_systems(state1, state2.system)
    # Transform the vector to density
    density1 = to_projector(new_state1.vector)
    density2 = to_projector(state2.vector)

    error = linalg.norm(density1.numpy() - density2.numpy())

    print("Norm difference of the given states is: \r\n", error)
    eps = 1e-12  # Error criterion
    if error < eps:
        print("They are exactly the same states.")
    elif 1e-10 > error >= eps:
        print("They are probably the same states.")
    else:
        print("They are not the same states.")


def compare_by_vector(state1, state2):
Q
Quleaf 已提交
818
    r"""Compare whether two quantum states are the same by their column vector form.
Q
Quleaf 已提交
819 820

    Args:
Q
Quleaf 已提交
821 822
        state1 (State): the first quantum state
        state2 (State): the second quantum state
Q
Quleaf 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    """
    assert state1.size == state2.size, "two state vectors compared are not of the same length."
    # Check if they are normalized quantum states
    eps = 1e-12  # Error criterion
    if state1.norm >= 1 + eps or state1.norm <= 1 - eps:
        raise ValueError("the first state is not normalized.")
    elif state2.norm >= 1 + eps or state2.norm <= 1 - eps:
        raise ValueError("the second state is not normalized.")
    else:
        new_state1 = permute_systems(state1, state2.system)
        vector1_list = list(new_state1.vector.numpy())
        idx = vector1_list.index(max(vector1_list, key=abs))
        if - eps <= state2.vector[idx].numpy() <= eps:
            print("They are not the same states.")
        else:
            # Calculate the phase and erase it
            phase = new_state1.vector[idx] / state2.vector[idx]
            vector1_phase = new_state1.vector / phase
            error = linalg.norm(vector1_phase - state2.vector)

            print("Norm difference of the given states is: \r\n", error)
            if error < eps:
                print("They are exactly the same states.")
            elif 1e-10 > error >= eps:
                print("They are probably the same states.")
            else:
                print("They are not the same states.")


def random_state_vector(n, is_real=False):
Q
Quleaf 已提交
853
    r"""Generate a state vector randomly.
Q
Quleaf 已提交
854 855

    Args:
Q
Quleaf 已提交
856 857 858
        n (int): the number of qubits of the random state.
        is_real (int, optional): ``True`` denotes a state vector with real values, ``False`` denotes a quantum
        state with complex values, default to ``False``
Q
Quleaf 已提交
859 860

    Returns:
Q
Quleaf 已提交
861
        Tensor: the column vector of the random quantum state.
Q
Quleaf 已提交
862

Q
Quleaf 已提交
863
    Code example:
Q
Quleaf 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

    .. code-block:: python

        from paddle_quantum.mbqc.utils import random_state_vector
        random_vec = random_state_vector(2)
        print(random_vec.numpy())
        random_vec = random_state_vector(1, is_real=True)
        print(random_vec.numpy())

    ::

        [[-0.06831946+0.04548425j]
         [ 0.60460088-0.16733175j]
         [ 0.39185213-0.24831266j]
         [ 0.45911355-0.41680807j]]
        [[0.77421121]
         [0.63292732]]
    """
    assert isinstance(n, int) and n >= 1, "the number of qubit must be a int larger than one."
    assert isinstance(is_real, bool), "'is_real' must be a bool."

    if is_real:
        psi = to_tensor(np_random.randn(2 ** n, 1), dtype='float64')
        inner_prod = matmul(t(conj(psi)), psi)
    else:
        psi = to_tensor(np_random.randn(2 ** n, 1) + 1j * np_random.randn(2 ** n, 1), dtype='complex128')
        inner_prod = real(matmul(t(conj(psi)), psi))

    psi = psi / pp_sqrt(inner_prod)  # Normalize the vector
    return psi


def div_str_to_float(div_str):
Q
Quleaf 已提交
897
    r"""Converts the division string to the corresponding floating point number.
Q
Quleaf 已提交
898

Q
Quleaf 已提交
899
    For example, the string '3/2' to the float number 1.5.
Q
Quleaf 已提交
900 901

    Args:
Q
Quleaf 已提交
902
        div_str (str): division string
Q
Quleaf 已提交
903 904

    Returns:
Q
Quleaf 已提交
905
        float: the float number
Q
Quleaf 已提交
906

Q
Quleaf 已提交
907
    Code example:
Q
Quleaf 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924

    ..  code-block:: python

        from paddle_quantum.mbqc.utils import div_str_to_float
        division_str = "1/2"
        division_float = div_str_to_float(division_str)
        print("The corresponding float value is: ", division_float)

    ::

        The corresponding float value is:  0.5
    """
    div_str = div_str.split("/")
    return float(div_str[0]) / float(div_str[1])


def int_to_div_str(idx1, idx2=1):
Q
Quleaf 已提交
925
    r"""Transform two integers to a division string.
Q
Quleaf 已提交
926 927

    Args:
Q
Quleaf 已提交
928 929
        idx1 (int): the first integer
        idx2 (int): the second integer
Q
Quleaf 已提交
930 931

    Returns:
Q
Quleaf 已提交
932
        str: the division string
Q
Quleaf 已提交
933

Q
Quleaf 已提交
934
    Code example:
Q
Quleaf 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

    ..  code-block:: python

        from paddle_quantum.mbqc.utils import int_to_div_str
        one = 1
        two = 2
        division_string = int_to_div_str(one, two)
        print("The corresponding division string is: ", division_string)

    ::

        The corresponding division string is:  1/2
    """
    assert isinstance(idx1, int) and isinstance(idx2, int), "two input parameters must be int."
    return str(idx1) + "/" + str(idx2)


def print_progress(current_progress, progress_name, track=True):
Q
Quleaf 已提交
953
    r"""Plot the progress bar.
Q
Quleaf 已提交
954 955

    Args:
Q
Quleaf 已提交
956 957 958
        current_progress (float / int): the percentage of the current progress.
        progress_name (str): the name of the current progress.
        track (bool): the boolean switch of whether plot.
Q
Quleaf 已提交
959

Q
Quleaf 已提交
960
    Code example:
Q
Quleaf 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973

    ..  code-block:: python

        from paddle_quantum.mbqc.utils import print_progress
        print_progress(14/100, "Current Progress")

    ::

       Current Progress              |■■■■■■■                                           |   14.00%
    """
    assert 0 <= current_progress <= 1, "'current_progress' must be between 0 and 1"
    assert isinstance(track, bool), "'track' must be a bool."
    if track:
Q
Quleaf 已提交
974 975 976 977 978 979
        print(
            "\r"
            f"{progress_name.ljust(30)}"
            f"|{'■' * int(50 * current_progress):{50}s}| "
            f"\033[94m {'{:6.2f}'.format(100 * current_progress)}% \033[0m ", flush=True, end=""
        )
Q
Quleaf 已提交
980 981 982 983 984
        if current_progress == 1:
            print(" (Done)")


def plot_results(dict_lst, bar_label, title, xlabel, ylabel, xticklabels=None):
Q
Quleaf 已提交
985 986
    r"""Plot the histogram based on the key-value pair of the dict.
        The key is the abscissa, and the corresponding value is the ordinate
Q
Quleaf 已提交
987 988

    Note:
Q
Quleaf 已提交
989
        The function is mainly used for plotting the sampling statistics or histogram.
Q
Quleaf 已提交
990 991

    Args:
Q
Quleaf 已提交
992 993 994 995 996 997
        dict_lst (list): a list contains the data to be plotted
        bar_label (list): the name of different bars in the histogram
        title (str): the title of the figure
        xlabel (str): the label of the x axis.
        ylabel (str): the label of the y axis.
        xticklabels (list, optional): the label of each ticks of the x-axis.
Q
Quleaf 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    """
    assert isinstance(dict_lst, list), "please input a list with dictionaries."
    assert isinstance(bar_label, list), "please input a list with bar_labels."
    assert len(dict_lst) == len(bar_label), \
        "please check your input as the number of dictionaries and bar labels are not equal."
    bars_num = len(dict_lst)
    bar_width = 1 / (bars_num + 1)
    plt.ion()
    plt.figure()
    for i in range(bars_num):
        plot_dict = dict_lst[i]
        # Obtain the y label and xticks in order
        keys = list(plot_dict.keys())
        values = list(plot_dict.values())
        xlen = len(keys)
        xticks = [((i) / (bars_num + 1)) + j for j in range(xlen)]
        # Plot bars
        plt.bar(xticks, values, width=bar_width, align='edge', label=bar_label[i])
        plt.yticks()
    if xticklabels is None:
        plt.xticks(list(range(xlen)), keys, rotation=90)
    else:
        assert len(xticklabels) == xlen, "the 'xticklabels' should have the same length with 'x' length."
        plt.xticks(list(range(xlen)), xticklabels, rotation=90)
    plt.legend()
    plt.title(title, fontproperties='SimHei', fontsize='x-large')
    plt.xlabel(xlabel, fontproperties='SimHei')
    plt.ylabel(ylabel, fontproperties='SimHei')
    plt.ioff()
    plt.show()


def write_running_data(textfile, eg, width, mbqc_time, reference_time):
Q
Quleaf 已提交
1031
    r"""Write the running times of the quantum circuit.
Q
Quleaf 已提交
1032

Q
Quleaf 已提交
1033 1034
    In many cases of circuit models, we need to compare the simulation time of our MBQC model with other methods
    such as qiskit or ``UAnsatz`` circuit model in paddle_quantum. So we define this function.
Q
Quleaf 已提交
1035 1036

    Hint:
Q
Quleaf 已提交
1037
        this function is used with the ``read_running_data`` function.
Q
Quleaf 已提交
1038 1039

    Warning:
Q
Quleaf 已提交
1040 1041
        Before using this function, we need to open a textfile. After using this function,
        we need to close the textfile.
Q
Quleaf 已提交
1042 1043

    Args:
Q
Quleaf 已提交
1044 1045 1046 1047 1048 1049
        textfile (TextIOWrapper): the file to be written in.
        eg (str): the name of the current case
        width (float): the width of the circuit(number of qubits)
        mbqc_time (float): `the simulation time of the ``MBQC`` model.
        reference_time (float):  the simulation time of the circuit
        based model in qiskit or ``UAnsatz`` in paddle_quantum.
Q
Quleaf 已提交
1050 1051 1052 1053 1054 1055 1056 1057
    """
    textfile.write("The current example is: " + eg + "\n")
    textfile.write("The qubit number is: " + str(width) + "\n")
    textfile.write("MBQC running time is: " + str(mbqc_time) + " s\n")
    textfile.write("Circuit model running time is: " + str(reference_time) + " s\n\n")


def read_running_data(file_name):
Q
Quleaf 已提交
1058
    r"""Read the running time of the quantum circuit.
Q
Quleaf 已提交
1059

Q
Quleaf 已提交
1060 1061 1062 1063
    In many cases of circuit models, we need to compare the simulation time of our MBQC model with other methods
    such as qiskit or ``UAnsatz`` circuit model in paddle_quantum. So we define this function and save the running
    time to a list. There are two dicts in the list, the first dict contains the running time of qiskit or ``UAnsatz``,
    the second contains the simulation time of our MBQC model.
Q
Quleaf 已提交
1064 1065

    Hint:
Q
Quleaf 已提交
1066
        This function is used with the ``write_running_data`` function.
Q
Quleaf 已提交
1067 1068

    Args:
Q
Quleaf 已提交
1069
        file_name (str): the name of the file to be read.
Q
Quleaf 已提交
1070 1071

    Returns:
Q
Quleaf 已提交
1072
        list: The list of running time.
Q
Quleaf 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    """
    bit_num_lst = []
    mbqc_list = []
    reference_list = []
    remainder = {2: bit_num_lst, 3: mbqc_list, 4: reference_list}
    # Read data
    with open(file_name, 'r') as file:
        counter = 0
        for line in file:
            counter += 1
            if counter % 5 in remainder.keys():
                remainder[counter % 5].append(float(line.strip("\n").split(":")[1].split(" ")[1]))

    # Transform the lists to dictionaries
    mbqc_dict = {i: mbqc_list[i] for i in range(len(bit_num_lst))}
    refer_dict = {i: reference_list[i] for i in range(len(bit_num_lst))}
    dict_lst = [mbqc_dict, refer_dict]
    return dict_lst