circuit.py 69.9 KB
Newer Older
Q
Quleaf 已提交
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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 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 407 408 409 410 411 412 413 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 440 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 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 498 499 500 501 502 503 504 505 506 507 508 509 510 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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 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 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 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 853 854 855 856 857 858 859 860 861 862 863 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 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 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 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
# !/usr/bin/env python3
# Copyright (c) 2022 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.

r"""
The source file of the Circuit class.
"""

import paddle
from .container import Sequential
from ..gate import Gate, H, S, T, X, Y, Z, P, RX, RY, RZ, U3
from ..gate import CNOT, CX, CY, CZ, SWAP
from ..gate import CP, CRX, CRY, CRZ, CU, RXX, RYY, RZZ
from ..gate import MS, CSWAP, Toffoli
from ..gate import UniversalTwoQubits, UniversalThreeQubits
from ..gate import Oracle, ControlOracle
from ..gate import SuperpositionLayer, WeakSuperpositionLayer, LinearEntangledLayer
from ..gate import RealBlockLayer, RealEntangledLayer, ComplexBlockLayer, ComplexEntangledLayer
from ..gate import QAOALayer
from ..gate import AmplitudeEncoding
from ..channel import BitFlip, PhaseFlip, BitPhaseFlip, AmplitudeDamping, GeneralizedAmplitudeDamping, PhaseDamping
from ..channel import Depolarizing, PauliChannel, ResetChannel, ThermalRelaxation, KrausRepr
from ..state import zero_state
from typing import Union, Iterable, Optional, Dict, List, Tuple
from paddle_quantum import State, get_backend, get_dtype, Backend
from math import pi
import numpy as np


class Circuit(Sequential):
    r"""Quantum circuit.

    Args:
        num_qubits: Number of qubits. Defaults to None.
    """

    def __init__(self, num_qubits: Optional[int] = None):
        super().__init__()
        self.__num_qubits = num_qubits

        # whether the circuit is a dynamic quantum circuit
        self.__isdynamic = True if num_qubits is None else False

        # alias for ccx
        self.toffoli = self.ccx

    @property
    def num_qubits(self) -> int:
        r"""Number of qubits.
        """
        return self.__num_qubits

    @property
    def isdynamic(self) -> bool:
        r"""Whether the circuit is dynamic
        """
        return self.__dynamic

    @num_qubits.setter
    def num_qubits(self, value: int) -> None:
        assert isinstance(value, int)
        self.__num_qubits = value

    @property
    def param(self) -> paddle.Tensor:
        r"""Flattened parameters in the circuit.
        """
        return paddle.concat([paddle.flatten(param) for param in self.parameters()])

    @property
    def grad(self) -> np.ndarray:
        r"""Gradients with respect to the flattened parameters.
        """
        grad_list = []
        for param in self.parameters():
            assert param.grad is not None, 'the gradient is None, run the backward first before calling this property,' + \
                ' otherwise check where the gradient chain is broken'
            grad_list.append(paddle.flatten(param.grad))
        return paddle.concat(grad_list).numpy()

    def update_param(self, theta: Union[paddle.Tensor, np.ndarray, float], idx:  Optional[int] = None) -> None:
        r"""Replace parameters of all/one layer(s) by ``theta``.

        Args:
            theta: New parameters
            idx: Index of replacement. Defaults to None, refering to all layers.
        """
        if not isinstance(theta, paddle.Tensor):
            theta = paddle.to_tensor(theta, dtype='float32')
        theta = paddle.flatten(theta)

        if idx is None:
            assert self.param.shape == theta.shape, "the shapen of input paramters is not correct"
            for layer in self.sublayers():
                for name, _ in layer.named_parameters():
                    param = getattr(layer, name)
                    num_param = int(paddle.numel(param))

                    param = paddle.create_parameter(
                        shape=param.shape,
                        dtype=param.dtype,
                        default_initializer=paddle.nn.initializer.Assign(
                            theta[:num_param].reshape(param.shape)),
                    )

                    setattr(layer, 'theta', param)
                    if num_param == theta.shape[0]:
                        return
                    theta = theta[num_param:]
        elif isinstance(idx, int):
            assert idx < len(self.sublayers(
            )), "the index is out of range, expect below " + str(len(self.sublayers()))
            layer = self.sublayers()[idx]
            assert theta.shape == paddle.concat([paddle.flatten(param) for param in layer.parameters()]).shape, \
                "the shape of input paramters is not correct,"

            for name, _ in layer.named_parameters():
                param = getattr(layer, name)
                num_param = int(paddle.numel(param))

                param = paddle.create_parameter(
                    shape=param.shape,
                    dtype=param.dtype,
                    default_initializer=paddle.nn.initializer.Assign(
                        theta[:num_param].reshape(param.shape)),
                )

                setattr(layer, 'theta', param)
                if num_param == theta.shape[0]:
                    return
                theta = theta[num_param:]
        else:
            raise ValueError("idx must be an integer or None")

    def randomize_param(self, low: float = 0, high:  Optional[float] = 2 * pi) -> None:
        r"""Randomize parameters of the circuit in a range from low to high.

        Args:
            low: Lower bound.
            high: Upper bound.
        """
        for layer in self.sublayers():
            for name, _ in layer.named_parameters():
                param = getattr(layer, name)

                param = paddle.create_parameter(
                    shape=param.shape,
                    dtype=param.dtype,
                    default_initializer=paddle.nn.initializer.Uniform(
                        low=low, high=high),
                )
                setattr(layer, 'theta', param)

    def __num_qubits_update(self, qubits_idx: Union[Iterable[int], int, str]) -> None:
        r"""Update ``self.num_qubits`` according to ``qubits_idx``, or report error.

        Args:
            qubits_idx: Input qubit indices of a quantum gate.
        """
        num_qubits = self.__num_qubits
        if isinstance(qubits_idx, str):
            assert num_qubits is not None, "The qubit idx cannot be full when the number of qubits is unknown"
            return

        if isinstance(qubits_idx, Iterable):
            max_idx = np.max(qubits_idx)
        else:
            max_idx = qubits_idx

        if num_qubits is None:
            self.__num_qubits = max_idx + 1
            return

        assert max_idx + 1 <= num_qubits or self.__isdynamic, \
            "The circuit is not a dynamic quantum circuit. Invalid input qubit idx: " + \
            str(max_idx) + " num_qubit: " + str(self.__num_qubits)
        self.__num_qubits = int(max(max_idx + 1, num_qubits))

    def h(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit Hadamard gates.

        The matrix form of such a gate is:

        .. math::

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

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            H(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def s(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit S gates.

        The matrix form of such a gate is:

        .. math::

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

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            S(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def t(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit T gates.

        The matrix form of such a gate is:

        .. math::

            T = \begin{bmatrix}
                    1&0\\
                    0&e^\frac{i\pi}{4}
                \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            T(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def x(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit X gates.

        The matrix form of such a gate is:

        .. math::
            X = \begin{bmatrix}
                    0 & 1 \\
                    1 & 0
                \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            X(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def y(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit Y gates.

        The matrix form of such a gate is:

        .. math::

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

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            Y(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def z(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1
    ) -> None:
        r"""Add single-qubit Z gates.

        The matrix form of such a gate is:

        .. math::

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

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            Z(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def p(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add single-qubit P gates.

        The matrix form of such a gate is:

        .. math::

            P(\theta) = \begin{bmatrix}
                1 & 0 \\
                0 & e^{i\theta}
            \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(P(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def rx(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add single-qubit rotation gates about the x-axis.

        The matrix form of such a gate is:

        .. math::

            R_X(\theta) = \begin{bmatrix}
                \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\
                -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2}
            \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RX(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def ry(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add single-qubit rotation gates about the y-axis.

        The matrix form of such a gate is:

        .. math::

            R_Y(\theta) = \begin{bmatrix}
                \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\
                \sin\frac{\theta}{2} & \cos\frac{\theta}{2}
            \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RY(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def rz(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: Optional[int] = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add single-qubit rotation gates about the z-axis.

        The matrix form of such a gate is:

        .. math::

            R_Z(\theta) = \begin{bmatrix}
                e^{-i\frac{\theta}{2}} & 0 \\
                0 & e^{i\frac{\theta}{2}}
            \end{bmatrix}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RZ(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def u3(
            self, qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, Iterable[float]] = None, param_sharing: bool = False
    ) -> None:
        r"""Add single-qubit rotation gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                U_3(\theta, \phi, \lambda) =
                    \begin{bmatrix}
                        \cos\frac\theta2&-e^{i\lambda}\sin\frac\theta2\\
                        e^{i\phi}\sin\frac\theta2&e^{i(\phi+\lambda)}\cos\frac\theta2
                    \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(U3(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def cnot(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add CNOT gates.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CNOT} &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes X\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 1 \\
                    0 & 0 & 1 & 0
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            CNOT(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def cx(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Same as cnot.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            CX(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def cy(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add controlled Y gates.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CY} &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes Y\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & -1j \\
                    0 & 0 & 1j & 0
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            CY(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def cz(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add controlled Z gates.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CZ} &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes Z\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 0 & 0 & -1
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            CZ(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def swap(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add SWAP gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{SWAP} =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 1
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            SWAP(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def cp(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add controlled P gates.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CP}(\theta) =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 0 & 0 & e^{i\theta}
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(CP(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def crx(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add controlled rotation gates about the x-axis.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CR_X} &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes R_X\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\
                    0 & 0 & -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2}
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(CRX(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def cry(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add controlled rotation gates about the y-axis.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CR_Y} &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes R_Y\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\
                    0 & 0 & \sin\frac{\theta}{2} & \cos\frac{\theta}{2}
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(CRY(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def crz(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add controlled rotation gates about the z-axis.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CR_Z} &= |0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes R_Z\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & e^{-i\frac{\theta}{2}} & 0 \\
                    0 & 0 & 0 & e^{i\frac{\theta}{2}}
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(CRZ(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def cu(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add controlled single-qubit rotation gates.

        For a 2-qubit quantum circuit, when `qubits_idx` is `[0, 1]`, the matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CU}
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & \cos\frac\theta2 &-e^{i\lambda}\sin\frac\theta2 \\
                    0 & 0 & e^{i\phi}\sin\frac\theta2&e^{i(\phi+\lambda)}\cos\frac\theta2
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(CU(qubits_idx, self.num_qubits if num_qubits is None else num_qubits,
                    depth, param, param_sharing))

    def rxx(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add RXX gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{R_{XX}}(\theta) =
                    \begin{bmatrix}
                        \cos\frac{\theta}{2} & 0 & 0 & -i\sin\frac{\theta}{2} \\
                        0 & \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} & 0 \\
                        0 & -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2} & 0 \\
                        -i\sin\frac{\theta}{2} & 0 & 0 & \cos\frac{\theta}{2}
                    \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RXX(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def ryy(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add RYY gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{R_{YY}}(\theta) =
                    \begin{bmatrix}
                        \cos\frac{\theta}{2} & 0 & 0 & i\sin\frac{\theta}{2} \\
                        0 & \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} & 0 \\
                        0 & -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2} & 0 \\
                        i\sin\frac{\theta}{2} & 0 & 0 & cos\frac{\theta}{2}
                    \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RYY(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def rzz(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add RZZ gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{R_{ZZ}}(\theta) =
                    \begin{bmatrix}
                        e^{-i\frac{\theta}{2}} & 0 & 0 & 0 \\
                        0 & e^{i\frac{\theta}{2}} & 0 & 0 \\
                        0 & 0 & e^{i\frac{\theta}{2}} & 0 \\
                        0 & 0 & 0 & e^{-i\frac{\theta}{2}}
                    \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RZZ(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def ms(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add Mølmer-Sørensen (MS) gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{MS} = \mathit{R_{XX}}(-\frac{\pi}{2}) = \frac{1}{\sqrt{2}}
                    \begin{bmatrix}
                        1 & 0 & 0 & i \\
                        0 & 1 & i & 0 \\
                        0 & i & 1 & 0 \\
                        i & 0 & 0 & 1
                    \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            MS(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def cswap(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add CSWAP (Fredkin) gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                \mathit{CSWAP} =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
                    0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
                    0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
                    0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
                    0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
                    0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 0 & 0 & 0 & 0 & 1
                \end{bmatrix}
            \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(
            CSWAP(qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def ccx(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add CCX gates.

        The matrix form of such a gate is:

        .. math::

            \begin{align}
                    \mathit{CCX} = \begin{bmatrix}
                        1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
                        0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
                        0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
                        0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
                        0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
                        0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
                        0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
                        0 & 0 & 0 & 0 & 0 & 0 & 1 & 0
                    \end{bmatrix}
                \end{align}

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(Toffoli(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def universal_two_qubits(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add universal two-qubit gates. One of such a gate requires 15 parameters.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(UniversalTwoQubits(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def universal_three_qubits(
            self, qubits_idx: Union[Iterable[int], str] = 'cycle', num_qubits: int = None, depth: int = 1,
            param: Union[paddle.Tensor, float] = None, param_sharing: bool = False
    ) -> None:
        r"""Add universal three-qubit gates. One of such a gate requires 81 parameters.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'cycle'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
            param: Parameters of the gates. Defaults to None.
            param_sharing: Whether gates in the same layer share a parameter. Defaults to False.

        Raises:
            ValueError: The ``param`` must be paddle.Tensor or float.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(UniversalThreeQubits(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth, param, param_sharing))

    def oracle(
            self, oracle: paddle.tensor, qubits_idx: Union[Iterable[Iterable[int]], Iterable[int], int],
            num_qubits: int = None, depth: int = 1
    ) -> None:
        """Add an oracle gate.

        Args:
            oracle: Unitary oracle to be implemented.
            qubits_idx: Indices of the qubits on which the gates are applied.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(Oracle(oracle, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits, depth))

    def control_oracle(
            self, oracle: paddle.Tensor,
            # num_control_qubits: int, controlled_value: 'str',
            qubits_idx: Union[Iterable[Iterable[int]], Iterable[int]],
            num_qubits: int = None, depth: int = 1
    ) -> None:
        """Add a controlled oracle gate.

        Args:
            oracle: Unitary oracle to be implemented.
            qubits_idx: Indices of the qubits on which the gates are applied.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(ControlOracle(oracle, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits, depth))

    def superposition_layer(
            self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add layers of Hadamard gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(SuperpositionLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def weak_superposition_layer(
            self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add layers of Ry gates with a rotation angle :math:`\pi/4`.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(WeakSuperpositionLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def linear_entangled_layer(
        self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add linear entangled layers consisting of Ry gates, Rz gates, and CNOT gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(LinearEntangledLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def real_entangled_layer(
        self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add strongly entangled layers consisting of Ry gates and CNOT gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RealEntangledLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def complex_entangled_layer(
        self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add strongly entangled layers consisting of single-qubit rotation gates and CNOT gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(ComplexEntangledLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def real_block_layer(
        self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add weakly entangled layers consisting of Ry gates and CNOT gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(RealBlockLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def complex_block_layer(
        self, qubits_idx: Iterable[int] = 'full', num_qubits: int = None, depth: int = 1
    ) -> None:
        r"""Add weakly entangled layers consisting of single-qubit rotation gates and CNOT gates.

        Args:
            qubits_idx: Indices of the qubits on which the gates are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
            depth: Number of layers. Defaults to 1.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(ComplexBlockLayer(
            qubits_idx, self.num_qubits if num_qubits is None else num_qubits, depth))

    def bit_flip(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add bit flip channels.

        Args:
            prob: Probability of a bit flip.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(BitFlip(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def phase_flip(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add phase flip channels.

        Args:
            prob: Probability of a phase flip.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(PhaseFlip(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def bit_phase_flip(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add bit phase flip channels.

        Args:
            prob: Probability of a bit phase flip.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(BitPhaseFlip(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def amplitude_damping(
        self, gamma: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add amplitude damping channels.

        Args:
            gamma: Damping probability.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(AmplitudeDamping(gamma, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def generalized_amplitude_damping(
        self, gamma: Union[paddle.Tensor, float], prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add generalized amplitude damping channels.

        Args:
            gamma: Damping probability.
            prob: Excitation probability.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(GeneralizedAmplitudeDamping(gamma, prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def phase_damping(
        self, gamma: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add phase damping channels.

        Args:
            gamma: Parameter of the phase damping channel.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(PhaseDamping(gamma, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def depolarizing(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add depolarizing channels.

        Args:
            prob: Parameter of the depolarizing channel.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(Depolarizing(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def pauli_channel(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add Pauli channels.

        Args:
            prob: Probabilities corresponding to the Pauli X, Y, and Z operators.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(PauliChannel(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def reset_channel(
        self, prob: Union[paddle.Tensor, float], qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add reset channels.

        Args:
            prob: Probabilities of resetting to :math:`|0\rangle` and to :math:`|1\rangle`.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(ResetChannel(prob, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def thermal_relaxation(
        self, const_t: Union[paddle.Tensor, Iterable[float]], exec_time: Union[paddle.Tensor, float],
        qubits_idx: Union[Iterable[int], int, str] = 'full', num_qubits: int = None
    ) -> None:
        r"""Add thermal relaxation channels.

        Args:
            const_t: :math:`T_1` and :math:`T_2` relaxation time in microseconds.
            exec_time: Quantum gate execution time in the process of relaxation in nanoseconds.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(ThermalRelaxation(const_t, exec_time, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def kraus_repr(
            self, kraus_oper: Iterable[paddle.Tensor],
            qubits_idx: Union[Iterable[Iterable[int]], Iterable[int], int],
            num_qubits: int = None
    ) -> None:
        r"""Add custom channels in the Kraus representation.

        Args:
            kraus_oper: Kraus operators of this channel.
            qubits_idx: Indices of the qubits on which the channels are applied. Defaults to 'full'.
            num_qubits: Total number of qubits. Defaults to None.
        """
        self.__num_qubits_update(qubits_idx)
        self.append(KrausRepr(kraus_oper, qubits_idx,
                    self.num_qubits if num_qubits is None else num_qubits))

    def qaoa_layer(self, edges: Iterable, nodes: Iterable, depth:  Optional[int] = 1) -> None:
        # TODO: see qaoa layer in layer.py
        self.__num_qubits_update(edges)
        self.__num_qubits_update(nodes)
        self.append(QAOALayer(edges, nodes, depth))

    def unitary_matrix(self, num_qubits:  Optional[int] = None) -> paddle.Tensor:
        r"""Get the unitary matrix form of the circuit.

        Args:
            num_qubits: Total number of qubits. Defaults to None.

        Returns:
            Unitary matrix form of the circuit.
        """
        if num_qubits is None:
            num_qubits = self.__num_qubits
        else:
            assert num_qubits >= self.__num_qubits

        backend = get_backend()
        self.to(backend=Backend.UnitaryMatrix)
        unitary = State(paddle.eye(
            2 ** num_qubits).cast(get_dtype()), backend=Backend.UnitaryMatrix)
        for layer in self._sub_layers.values():
            unitary = layer(unitary)
        self.to(backend=backend)
        return unitary.data

    @property
    def gate_history(self) -> List[Dict[str, Union[str, List[int], paddle.Tensor]]]:
        r""" list of gates information of circuit

        Returns:
            history of quantum gates of circuit

        """
        def get_gate_name(gate: Gate) -> str:
            r""" return the corresponding string of gate

            Returns:
                gate name

            """
            if isinstance(gate, H):
                return 'h'
            if isinstance(gate, S):
                return 's'
            if isinstance(gate, T):
                return 't'
            if isinstance(gate, X):
                return 'x'
            if isinstance(gate, Y):
                return 'y'
            if isinstance(gate, Z):
                return 'z'
            if isinstance(gate, U3):
                return 'u'
            if isinstance(gate, P):
                return 'p'
            if isinstance(gate, RX):
                return 'rx'
            if isinstance(gate, RY):
                return 'ry'
            if isinstance(gate, RZ):
                return 'rz'
            if isinstance(gate, CNOT):
                return 'cnot'
            if isinstance(gate, SWAP):
                return 'swap'
            if isinstance(gate, CX):
                return 'cnot'
            if isinstance(gate, CY):
                return 'cy'
            if isinstance(gate, CZ):
                return 'cz'
            if isinstance(gate, RXX):
                return 'rxx'
            if isinstance(gate, RYY):
                return 'ryy'
            if isinstance(gate, RZZ):
                return 'rzz'
            if isinstance(gate, CP):
                return 'cp'
            if isinstance(gate, CRX):
                return 'crx'
            if isinstance(gate, CRY):
                return 'cry'
            if isinstance(gate, CRZ):
                return 'crz'
            if isinstance(gate, CU):
                return 'cu'
            if isinstance(gate, MS):
                return 'ms'
            if isinstance(gate, CSWAP):
                return 'cswap'
            if isinstance(gate, Toffoli):
                return 'ccx'
            raise ValueError("The gate is not a simple quantum gate.")

        not_implemented_gate = [
            AmplitudeEncoding,
            Oracle,
            ControlOracle,
            UniversalTwoQubits,
            UniversalThreeQubits,
            RealBlockLayer,
            ComplexBlockLayer,
        ]
        single_qubit_gate = {'h', 's', 't', 'x',
                             'y', 'z', 'p', 'rx', 'ry', 'rz', 'u'}
        gate_history = []
        qubit_max_idx = 0
        for gate in self.sublayers():
            if any((isinstance(gate, gate_class) for gate_class in not_implemented_gate)):
                raise NotImplementedError(
                    f"Not support to print the {type(gate)}.")
            if isinstance(gate, SuperpositionLayer):
                for depth_idx in range(0, gate.depth):
                    for qubit_idx in gate.qubits_idx:
                        gate_info = {
                            'gate': 'h', 'which_qubits': [qubit_idx], 'theta': None
                        }
                        gate_history.append(gate_info)
            elif isinstance(gate, WeakSuperpositionLayer):
                for depth_idx in range(0, gate.depth):
                    for qubit_idx in gate.qubits_idx:
                        gate_info = {
                            'gate': 'ry', 'which_qubits': [qubit_idx],
                            'theta': paddle.to_tensor([pi / 4])
                        }
                        gate_history.append(gate_info)
            elif isinstance(gate, LinearEntangledLayer):
                for depth_idx in range(0, gate.depth):
                    for idx, qubit_idx in enumerate(gate.qubits_idx):
                        gate_info = {
                            'gate': 'ry', 'which_qubits': [qubit_idx],
                            'theta': gate.parameters()[0][depth_idx][idx][0]
                        }
                        gate_history.append(gate_info)
                    for idx in range(0, len(gate.qubits_idx) - 1):
                        gate_info = {
                            'gate': 'cnot', 'which_qubits': [gate.qubits_idx[idx], gate.qubits_idx[idx + 1]],
                            'theta': None
                        }
                        gate_history.append(gate_info)
                    for idx, qubit_idx in enumerate(gate.qubits_idx):
                        gate_info = {
                            'gate': 'rz', 'which_qubits': [qubit_idx],
                            'theta': gate.parameters()[0][depth_idx][idx][1]
                        }
                        gate_history.append(gate_info)
                    for idx in range(0, len(gate.qubits_idx) - 1):
                        gate_info = {
                            'gate': 'cnot', 'which_qubits': [gate.qubits_idx[idx], gate.qubits_idx[idx + 1]],
                            'theta': None
                        }
                        gate_history.append(gate_info)
            elif isinstance(gate, RealEntangledLayer):
                for depth_idx in range(0, gate.depth):
                    for idx, qubit_idx in enumerate(gate.qubits_idx):
                        gate_info = {
                            'gate': 'ry', 'which_qubits': [qubit_idx],
                            'theta': gate.parameters()[0][depth_idx][idx]
                        }
                        gate_history.append(gate_info)
                    for idx in range(0, len(gate.qubits_idx)):
                        gate_info = {
                            'gate': 'cnot',
                            'which_qubits': [
                                gate.qubits_idx[idx],
                                gate.qubits_idx[(idx + 1) %
                                                len(gate.qubits_idx)]
                            ],
                            'theta': None
                        }
                        gate_history.append(gate_info)
            elif isinstance(gate, ComplexEntangledLayer):
                for depth_idx in range(0, gate.depth):
                    for idx, qubit_idx in enumerate(gate.qubits_idx):
                        gate_info = {
                            'gate': 'u', 'which_qubits': [qubit_idx], 'theta': None
                        }
                        gate_history.append(gate_info)
                    for idx in range(0, len(gate.qubits_idx)):
                        gate_info = {
                            'gate': 'cnot',
                            'which_qubits': [
                                gate.qubits_idx[idx],
                                gate.qubits_idx[(idx + 1) %
                                                len(gate.qubits_idx)]
                            ],
                            'theta': None
                        }
                        gate_history.append(gate_info)
            else:
                gate_name = get_gate_name(gate)
                if gate_name in single_qubit_gate:
                    for depth_idx in range(0, gate.depth):
                        for idx, qubit_idx in enumerate(gate.qubits_idx):
                            gate_info = {'gate': gate_name,
                                         'which_qubits': [qubit_idx]}
                            param = None
                            if gate_name in {'rx', 'ry', 'rz'}:
                                param = gate.theta[depth_idx][idx]
                            gate_info['theta'] = param
                            gate_history.append(gate_info)
                else:
                    for depth_idx in range(0, gate.depth):
                        for idx, qubit_idx in enumerate(gate.qubits_idx):
                            gate_info = {'gate': gate_name,
                                         'which_qubits': qubit_idx}
                            param = None
                            if gate_name in {'cp', 'crx', 'cry', 'crz', 'rxx', 'ryy', 'rzz'}:
                                param = gate.parameters()[0][depth_idx][idx]
                            gate_info['theta'] = param
                            gate_history.append(gate_info)
        return gate_history

    def __count_history(self, history):
        # Record length of each section
        length = [5]
        n = self.__num_qubits
        # Record current section number for every qubit
        qubit = [0] * n
        # Number of sections
        qubit_max = max(qubit)
        # Record section number for each gate
        gate = []

        for current_gate in history:
            # Single-qubit gates with no params to print
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u', 'sdg', 'tdg'}:
                curr_qubit = current_gate['which_qubits'][0]
                gate.append(qubit[curr_qubit])
                qubit[curr_qubit] = qubit[curr_qubit] + 1
                # A new section is added
                if qubit[curr_qubit] > qubit_max:
                    length.append(5)
                    qubit_max = qubit[curr_qubit]
            # Gates with params to print
            elif current_gate['gate'] in {'p', 'rx', 'ry', 'rz'}:
                curr_qubit = current_gate['which_qubits'][0]
                gate.append(qubit[curr_qubit])
                if length[qubit[curr_qubit]] == 5:
                    length[qubit[curr_qubit]] = 13
                qubit[curr_qubit] = qubit[curr_qubit] + 1
                if qubit[curr_qubit] > qubit_max:
                    length.append(5)
                    qubit_max = qubit[curr_qubit]
            # Two-qubit gates or Three-qubit gates
            elif (
                    current_gate['gate'] in {
                        'cnot', 'swap', 'rxx', 'ryy', 'rzz', 'ms',
                        'cy', 'cz', 'cu', 'cp', 'crx', 'cry', 'crz'} or
                    current_gate['gate'] in {'cswap', 'ccx'}
            ):
                a = max(current_gate['which_qubits'])
                b = min(current_gate['which_qubits'])
                ind = max(qubit[b: a + 1])
                gate.append(ind)
                if length[ind] < 13 and current_gate['gate'] in {'rxx', 'ryy', 'rzz',
                                                                 'cp', 'crx', 'cry', 'crz'}:
                    length[ind] = 13
                for j in range(b, a + 1):
                    qubit[j] = ind + 1
                if ind + 1 > qubit_max:
                    length.append(5)
                    qubit_max = ind + 1

        return length, gate

    @property
    def qubit_history(self) -> List[List[Tuple[Dict[str, Union[str, List[int], paddle.Tensor]], int]]]:
        r""" gate information on each qubit

        Returns:
            list of gate history on each qubit

        Note:
            The entry ``qubit_history[i][j][0/1]`` returns the gate information / gate index of the j-th gate
            applied on the i-th qubit.
        """
        history_qubit = []
        for i in range(self.num_qubits):
            history_i = []
            history_qubit.append(history_i)
        for idx, i in enumerate(self.gate_history):
            qubits = i["which_qubits"]
            for j in qubits:
                history_qubit[j].append([i, idx])
        return history_qubit

    def __str__(self) -> str:
        history = self.gate_history
        num_qubits = self.__num_qubits
        length, gate = self.__count_history(history)
        # Ignore the unused section
        total_length = sum(length) - 5

        print_list = [['-' if i % 2 == 0 else ' '] *
                      total_length for i in range(num_qubits * 2)]

        for i, current_gate in enumerate(history):
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u'}:
                # Calculate starting position ind of current gate
                sec = gate[i]
                ind = sum(length[:sec])
                print_list[current_gate['which_qubits'][0] * 2][ind +
                                                                length[sec] // 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'sdg'}:
                sec = gate[i]
                ind = sum(length[:sec])
                print_list[current_gate['which_qubits'][0] * 2][
                    ind + length[sec] // 2 - 1: ind + length[sec] // 2 + 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'tdg'}:
                sec = gate[i]
                ind = sum(length[:sec])
                print_list[current_gate['which_qubits'][0] * 2][
                    ind + length[sec] // 2 - 1: ind + length[sec] // 2 + 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'p', 'rx', 'ry', 'rz'}:
                sec = gate[i]
                ind = sum(length[:sec])
                line = current_gate['which_qubits'][0] * 2
                # param = self.__param[current_gate['theta'][2 if current_gate['gate'] == 'rz' else 0]]
                param = current_gate['theta']
                if current_gate['gate'] == 'p':
                    print_list[line][ind + 2] = 'P'
                    print_list[line][ind + 3] = ' '
                else:
                    print_list[line][ind + 2] = 'R'
                    print_list[line][ind + 3] = current_gate['gate'][1]
                print_list[line][ind + 4] = '('
                print_list[line][ind + 5: ind +
                                 10] = format(float(param.numpy()), '.3f')[:5]
                print_list[line][ind + 10] = ')'
            # Two-qubit gates
            elif current_gate['gate'] in {'cnot', 'swap', 'rxx', 'ryy', 'rzz', 'ms', 'cz', 'cy',
                                          'cu', 'crx', 'cry', 'crz'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit = current_gate['which_qubits'][0]
                tqubit = current_gate['which_qubits'][1]
                if current_gate['gate'] in {'cnot', 'swap', 'cy', 'cz', 'cu'}:
                    print_list[cqubit * 2][ind + length[sec] // 2] = \
                        '*' if current_gate['gate'] in {'cnot',
                                                        'cy', 'cz', 'cu'} else 'x'
                    print_list[tqubit * 2][ind + length[sec] // 2] = \
                        'x' if current_gate['gate'] in {
                            'swap', 'cnot'} else current_gate['gate'][1]
                elif current_gate['gate'] == 'ms':
                    for qubit in {cqubit, tqubit}:
                        print_list[qubit * 2][ind + length[sec] // 2 - 1] = 'M'
                        print_list[qubit * 2][ind + length[sec] // 2] = '_'
                        print_list[qubit * 2][ind + length[sec] // 2 + 1] = 'S'
                elif current_gate['gate'] in {'rxx', 'ryy', 'rzz'}:
                    # param = self.__param[current_gate['theta'][0]]
                    param = current_gate['theta']
                    for line in {cqubit * 2, tqubit * 2}:
                        print_list[line][ind + 2] = 'R'
                        print_list[line][ind + 3: ind +
                                         5] = current_gate['gate'][1:3].lower()
                        print_list[line][ind + 5] = '('
                        print_list[line][ind + 6: ind +
                                         10] = format(float(param.numpy()), '.2f')[:4]
                        print_list[line][ind + 10] = ')'
                elif current_gate['gate'] in {'crx', 'cry', 'crz'}:
                    # param = self.__param[current_gate['theta'][2 if current_gate['gate'] == 'crz' else 0]]
                    param = current_gate['theta']
                    print_list[cqubit * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit * 2][ind + 2] = 'R'
                    print_list[tqubit * 2][ind + 3] = current_gate['gate'][2]
                    print_list[tqubit * 2][ind + 4] = '('
                    print_list[tqubit * 2][ind + 5: ind +
                                           10] = format(float(param.numpy()), '.3f')[:5]
                    print_list[tqubit * 2][ind + 10] = ')'
                start_line = min(cqubit, tqubit)
                end_line = max(cqubit, tqubit)
                for k in range(start_line * 2 + 1, end_line * 2):
                    print_list[k][ind + length[sec] // 2] = '|'
            # Three-qubit gates
            elif current_gate['gate'] in {'cswap'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit = current_gate['which_qubits'][0]
                tqubit1 = current_gate['which_qubits'][1]
                tqubit2 = current_gate['which_qubits'][2]
                start_line = min(current_gate['which_qubits'])
                end_line = max(current_gate['which_qubits'])
                for k in range(start_line * 2 + 1, end_line * 2):
                    print_list[k][ind + length[sec] // 2] = '|'
                if current_gate['gate'] in {'cswap'}:
                    print_list[cqubit * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit1 * 2][ind + length[sec] // 2] = 'x'
                    print_list[tqubit2 * 2][ind + length[sec] // 2] = 'x'
            elif current_gate['gate'] in {'ccx'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit1 = current_gate['which_qubits'][0]
                cqubit2 = current_gate['which_qubits'][1]
                tqubit = current_gate['which_qubits'][2]
                start_line = min(current_gate['which_qubits'])
                end_line = max(current_gate['which_qubits'])
                for k in range(start_line * 2 + 1, end_line * 2):
                    print_list[k][ind + length[sec] // 2] = '|'
                if current_gate['gate'] in {'ccx'}:
                    print_list[cqubit1 * 2][ind + length[sec] // 2] = '*'
                    print_list[cqubit2 * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit * 2][ind + length[sec] // 2] = 'X'

        print_list = list(map(''.join, print_list))
        return_str = '\n'.join(print_list)

        return return_str

    def forward(self, state:  Optional[State] = None) -> State:
        r""" forward the input

        Args:
            state: initial state

        Returns:
            output quantum state

        """
        if state is None:
            assert self.__num_qubits is not None, "Information about num_qubits is required before running the circuit"
            state = zero_state(self.__num_qubits, self.backend, self.dtype)

        return super().forward(state)