circuit.py 82.6 KB
Newer Older
Q
Quleaf 已提交
1
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
Q
Quleaf 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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
import warnings
Q
Quleaf 已提交
16 17
import numpy as np
import math
Q
Quleaf 已提交
18 19 20
from functools import reduce
from collections import defaultdict
import matplotlib.pyplot as plt
Q
Quleaf 已提交
21
from paddle_quantum.simulator import transfer_state, init_state_gen, measure_state
Q
Quleaf 已提交
22
import paddle
Q
Quleaf 已提交
23
from paddle import matmul, trace, real, imag, reshape
Q
Quleaf 已提交
24
from paddle_quantum.utils import dagger, pauli_str_to_matrix
Q
Quleaf 已提交
25 26
from paddle_quantum.intrinsic import *
from paddle_quantum.state import density_op
Q
Quleaf 已提交
27 28 29

__all__ = [
    "UAnsatz",
Q
Quleaf 已提交
30
    "H_prob"
Q
Quleaf 已提交
31 32 33
]


Q
Quleaf 已提交
34
class UAnsatz:
Q
Quleaf 已提交
35
    r"""基于 PaddlePaddle 的动态图机制实现量子电路的 ``class`` 。
Q
Quleaf 已提交
36

Q
Quleaf 已提交
37
    用户可以通过实例化该 ``class`` 来搭建自己的量子电路。
Q
Quleaf 已提交
38

Q
Quleaf 已提交
39
    Attributes:
Q
Quleaf 已提交
40
        n (int): 该电路的量子比特数
Q
Quleaf 已提交
41 42
    """

Q
Quleaf 已提交
43
    def __init__(self, n):
Q
Quleaf 已提交
44
        r"""UAnsatz 的构造函数,用于实例化一个 UAnsatz 对象
Q
Quleaf 已提交
45

Q
Quleaf 已提交
46
        Args:
Q
Quleaf 已提交
47
            n (int): 该电路的量子比特数
Q
Quleaf 已提交
48

Q
Quleaf 已提交
49 50
        """
        self.n = n
Q
Quleaf 已提交
51
        self.__has_channel = False
Q
Quleaf 已提交
52 53 54 55
        self.__state = None
        self.__run_state = ''
        # Record history of adding gates to the circuit
        self.__history = []
Q
Quleaf 已提交
56 57 58
        
    def _count_history(self):
        r"""calculate how many blocks needed for printing
Q
Quleaf 已提交
59

Q
Quleaf 已提交
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
        Note:
        这是内部函数,你并不需要直接调用到该函数。
        """
        # Record length of each section
        length = [5]
        n = self.n
        # Record current section number for every qubit
        qubit = [0] * n
        # Number of sections
        qubit_max = max(qubit)
        # Record section number for each gate
        gate = []
        history = self.__history
        
        for current_gate in history:
            # Single-qubit gates with no params to print
            if current_gate[0] in {'h', 's', 't', 'x', 'y', 'z', 'u'}:
                curr_qubit = current_gate[1][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[0] in {'rx', 'ry', 'rz'}:
                curr_qubit = current_gate[1][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
            elif current_gate[0] in {'CNOT', 'SWAP', 'RXX_gate', 'RYY_gate', 'RZZ_gate', 'MS_gate'}:
                p = current_gate[1][0]
                q = current_gate[1][1]
                a = max(p, q)
                b = min(p, q)
                ind = max(qubit[b: a + 1])
                gate.append(ind)
                if length[ind] < 13 and current_gate[0] in {'RXX_gate', 'RYY_gate', 'RZZ_gate'}:
                    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
    
    def __str__(self):
        r"""实现画电路的功能
        
        Returns:
            string: 用来print的字符串
        
        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            import numpy as np
            
            cir = UAnsatz(5)
            cir.superposition_layer()
            rotations = paddle.to_tensor(np.random.uniform(-2, 2, size=(3, 5, 1)))
            cir.real_entangled_layer(rotations, 3)
            
            print(cir)
        ::
            
            The printed circuit is:
            
            --H----Ry(-0.14)----*-------------------X----Ry(-0.77)----*-------------------X--
                                |                   |                 |                   |  
            --H----Ry(-1.00)----X----*--------------|----Ry(-0.83)----X----*--------------|--
                                     |              |                      |              |  
            --H----Ry(-1.88)---------X----*---------|----Ry(-0.98)---------X----*---------|--
                                          |         |                           |         |  
            --H----Ry(1.024)--------------X----*----|----Ry(-0.37)--------------X----*----|--
                                               |    |                                |    |  
            --H----Ry(1.905)-------------------X----*----Ry(-1.82)-------------------X----*--
                                                                                             
        """
        length, gate = self._count_history()
        history = self.__history
        n = self.n
        # Ignore the unused section 
        total_length = sum(length) - 5
    
        print_list = [['-' if i % 2 == 0 else ' '] * total_length for i in range(n * 2)]

        for i, current_gate in enumerate(history):
            if current_gate[0] 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[1][0] * 2][ind + length[sec] // 2] = current_gate[0].upper()
            elif current_gate[0] in {'rx', 'ry', 'rz'}:
                sec = gate[i]
                ind = sum(length[:sec])
                line = current_gate[1][0] * 2
                param = current_gate[2][2 if current_gate[0] == 'rz' else 0]
                print_list[line][ind + 2] = 'R'
                print_list[line][ind + 3] = current_gate[0][1]
                print_list[line][ind + 4] = '('
                print_list[line][ind + 5: ind + 10] = format(float(param.numpy()), '.3f')[:5]
                print_list[line][ind + 10] = ')'
            elif current_gate[0] in {'CNOT', 'SWAP', 'RXX_gate', 'RYY_gate', 'RZZ_gate', 'MS_gate'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit = current_gate[1][0]
                tqubit = current_gate[1][1]
                if current_gate[0] in {'CNOT', 'SWAP'}:
                    print_list[cqubit * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit * 2][ind + length[sec] // 2] = 'X' if current_gate[0] == 'CNOT' else '*'
                elif current_gate[0] == 'MS_gate':
                    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[0] in {'RXX_gate', 'RYY_gate', 'RZZ_gate'}:
                    param = current_gate[2]
                    for line in {cqubit * 2, tqubit * 2}:
                        print_list[line][ind + 2] = 'R'
                        print_list[line][ind + 3: ind + 5] = current_gate[0][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] = ')'
                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] = '|'

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

        return return_str
        
Q
Quleaf 已提交
202
    def run_state_vector(self, input_state=None, store_state=True):
Q
Quleaf 已提交
203 204 205 206
        r"""运行当前的量子电路,输入输出的形式为态矢量。

        Warning:
            该方法只能运行无噪声的电路。
Q
Quleaf 已提交
207
        
Q
Quleaf 已提交
208
        Args:
Q
Quleaf 已提交
209
            input_state (Tensor, optional): 输入的态矢量,默认为 :math:`|00...0\rangle`
Q
Quleaf 已提交
210
            store_state (Bool, optional): 是否存储输出的态矢量,默认为 ``True`` ,即存储
Q
Quleaf 已提交
211
        
Q
Quleaf 已提交
212
        Returns:
Q
Quleaf 已提交
213
            Tensor: 量子电路输出的态矢量
Q
Quleaf 已提交
214
        
Q
Quleaf 已提交
215
        代码示例:
Q
Quleaf 已提交
216

Q
Quleaf 已提交
217
        .. code-block:: python
Q
Quleaf 已提交
218

Q
Quleaf 已提交
219
            import numpy as np
Q
Quleaf 已提交
220
            import paddle
Q
Quleaf 已提交
221
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
222
            from paddle_quantum.state import vec
Q
Quleaf 已提交
223 224
            n = 2
            theta = np.ones(3)
Q
Quleaf 已提交
225 226 227 228 229 230 231 232 233

            input_state = paddle.to_tensor(vec(n))
            theta = paddle.to_tensor(theta)
            cir = UAnsatz(n)
            cir.h(0)
            cir.ry(theta[0], 1)
            cir.rz(theta[1], 1)
            output_state = cir.run_state_vector(input_state).numpy()
            print(f"The output state vector is {output_state}")
Q
Quleaf 已提交
234

Q
Quleaf 已提交
235
        ::
Q
Quleaf 已提交
236

Q
Quleaf 已提交
237
            The output state vector is [[0.62054458+0.j 0.18316521+0.28526291j 0.62054458+0.j 0.18316521+0.28526291j]]
Q
Quleaf 已提交
238
        """
Q
Quleaf 已提交
239
        # Throw a warning when cir has channel
Q
Quleaf 已提交
240
        if self.__has_channel:
Q
Quleaf 已提交
241
            warnings.warn('The noiseless circuit will be run.', RuntimeWarning)
Q
Quleaf 已提交
242 243 244
        state = init_state_gen(self.n, 0) if input_state is None else input_state
        old_shape = state.shape
        assert reduce(lambda x, y: x * y, old_shape) == 2 ** self.n, 'The length of the input vector is not right'
Q
Quleaf 已提交
245
        state = reshape(state, (2 ** self.n,))
Q
Quleaf 已提交
246

Q
Quleaf 已提交
247
        state_conj = paddle.conj(state)
Q
Quleaf 已提交
248
        assert paddle.abs(real(paddle.sum(paddle.multiply(state_conj, state))) - 1) < 1e-8, \
Q
Quleaf 已提交
249
            'Input state is not a normalized vector'
Q
Quleaf 已提交
250

Q
Quleaf 已提交
251
        state = transfer_by_history(state, self.__history)
Q
Quleaf 已提交
252 253 254 255 256 257

        if store_state:
            self.__state = state
            # Add info about which function user called
            self.__run_state = 'state_vector'

Q
Quleaf 已提交
258
        return reshape(state, old_shape)
Q
Quleaf 已提交
259 260

    def run_density_matrix(self, input_state=None, store_state=True):
Q
Quleaf 已提交
261
        r"""运行当前的量子电路,输入输出的形式为密度矩阵。
Q
Quleaf 已提交
262
        
Q
Quleaf 已提交
263
        Args:
Q
Quleaf 已提交
264
            input_state (Tensor, optional): 输入的密度矩阵,默认为 :math:`|00...0\rangle \langle00...0|`
Q
Quleaf 已提交
265
            store_state (bool, optional): 是否存储输出的密度矩阵,默认为 ``True`` ,即存储
Q
Quleaf 已提交
266
        
Q
Quleaf 已提交
267
        Returns:
Q
Quleaf 已提交
268
            Tensor: 量子电路输出的密度矩阵
Q
Quleaf 已提交
269 270 271 272

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
273

Q
Quleaf 已提交
274
            import numpy as np
Q
Quleaf 已提交
275
            import paddle
Q
Quleaf 已提交
276
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
277
            from paddle_quantum.state import density_op
Q
Quleaf 已提交
278 279
            n = 1
            theta = np.ones(3)
Q
Quleaf 已提交
280 281 282 283 284 285 286 287 288

            input_state = paddle.to_tensor(density_op(n))
            theta = paddle.to_tensor(theta)
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.ry(theta[1], 0)
            cir.rz(theta[2], 0)
            density_matrix = cir.run_density_matrix(input_state).numpy()
            print(f"The output density matrix is\n{density_matrix}")
Q
Quleaf 已提交
289 290 291

        ::

Q
Quleaf 已提交
292
            The output density matrix is
Q
Quleaf 已提交
293 294
            [[0.64596329+0.j         0.47686058+0.03603751j]
            [0.47686058-0.03603751j 0.35403671+0.j        ]]
Q
Quleaf 已提交
295
        """
Q
Quleaf 已提交
296
        state = paddle.to_tensor(density_op(self.n)) if input_state is None else input_state
Q
Quleaf 已提交
297
        assert state.shape == [2 ** self.n, 2 ** self.n], "The dimension is not right"
Q
Quleaf 已提交
298

Q
Quleaf 已提交
299
        if not self.__has_channel:
Q
Quleaf 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
            state = matmul(self.U, matmul(state, dagger(self.U)))
        else:
            dim = 2 ** self.n
            shape = (dim, dim)
            num_ele = dim ** 2
            identity = paddle.eye(dim, dtype='float64')
            identity = paddle.cast(identity, 'complex128')
            identity = reshape(identity, [num_ele])

            u_start = 0
            for i, history_ele in enumerate(self.__history):
                if history_ele[0] == 'channel':
                    # Combine preceding unitary operations
                    unitary = transfer_by_history(identity, self.__history[u_start:i])
                    sub_state = paddle.zeros(shape, dtype='complex128')
Q
Quleaf 已提交
315
                    # Sum all the terms corresponding to different Kraus operators
Q
Quleaf 已提交
316 317 318 319 320 321 322 323
                    for op in history_ele[1]:
                        pseudo_u = reshape(transfer_state(unitary, op, history_ele[2]), shape)
                        sub_state += pseudo_u @ state @ dagger(pseudo_u)
                    state = sub_state
                    u_start = i + 1
            # Apply unitary operations left
            unitary = reshape(transfer_by_history(identity, self.__history[u_start:(i + 1)]), shape)
            state = matmul(unitary, matmul(state, dagger(unitary)))
Q
Quleaf 已提交
324

Q
Quleaf 已提交
325 326 327 328 329 330 331 332 333
        if store_state:
            self.__state = state
            # Add info about which function user called
            self.__run_state = 'density_matrix'

        return state

    @property
    def U(self):
Q
Quleaf 已提交
334 335 336 337
        r"""量子电路的酉矩阵形式。

        Warning:
            该属性只限于无噪声的电路。
Q
Quleaf 已提交
338
        
Q
Quleaf 已提交
339
        Returns:
Q
Quleaf 已提交
340
            Tensor: 当前电路的酉矩阵表示
Q
Quleaf 已提交
341 342 343 344

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
345

Q
Quleaf 已提交
346
            import paddle
Q
Quleaf 已提交
347 348
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
349 350 351 352 353
            cir = UAnsatz(2)
            cir.h(0)
            cir.cnot([0, 1])
            unitary_matrix = cir.U
            print("The unitary matrix of the circuit for Bell state preparation is\n", unitary_matrix.numpy())
Q
Quleaf 已提交
354 355 356

        ::

Q
Quleaf 已提交
357
            The unitary matrix of the circuit for Bell state preparation is
Q
Quleaf 已提交
358 359 360 361
            [[ 0.70710678+0.j  0.        +0.j  0.70710678+0.j  0.        +0.j]
            [ 0.        +0.j  0.70710678+0.j  0.        +0.j  0.70710678+0.j]
            [ 0.        +0.j  0.70710678+0.j  0.        +0.j -0.70710678+0.j]
            [ 0.70710678+0.j  0.        +0.j -0.70710678+0.j  0.        +0.j]]
Q
Quleaf 已提交
362
        """
Q
Quleaf 已提交
363
        # Throw a warning when cir has channel
Q
Quleaf 已提交
364
        if self.__has_channel:
Q
Quleaf 已提交
365 366 367 368 369
            warnings.warn('The unitary matrix of the noiseless circuit will be given.', RuntimeWarning)
        dim = 2 ** self.n
        shape = (dim, dim)
        num_ele = dim ** 2
        state = paddle.eye(dim, dtype='float64')
Q
Quleaf 已提交
370
        state = paddle.cast(state, 'complex128')
Q
Quleaf 已提交
371 372
        state = reshape(state, [num_ele])
        state = transfer_by_history(state, self.__history)
Q
Quleaf 已提交
373

Q
Quleaf 已提交
374
        return reshape(state, shape)
Q
Quleaf 已提交
375

Q
Quleaf 已提交
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
    def basis_encoding(self, x, invert=False):
        r"""将输入的经典数据使用基态编码的方式编码成量子态。

        在 basis encoding 中,输入的经典数据只能包括 0 或 1。如输入数据为 1101,则编码后的量子态为 :math:`|1101\rangle` 。
        这里假设量子态在编码前为全 0 的态,即 :math:`|00\ldots 0\rangle` 。

        Args:
            x (Tensor): 待编码的向量
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
        x = paddle.flatten(x)
        x = paddle.cast(x, dtype="int32")
        assert x.size == self.n, "the number of classical data should be equal to the number of qubits"
        for idx, element in enumerate(x):
            if element:
                self.x(idx)

    def amplitude_encoding(self, x, mode):
        r"""将输入的经典数据使用振幅编码的方式编码成量子态。

        Args:
            x (Tensor): 待编码的向量
            mode (str): 生成的量子态的表示方式,``"state_vector"`` 代表态矢量表示, ``"density_matrix"`` 代表密度矩阵表示

        Returns:
            Tensor: 一个形状为 ``(2 ** n, )`` 或 ``(2 ** n, 2 ** n)`` 的张量,表示编码之后的量子态。

        """
        assert x.size <= 2 ** self.n, "the number of classical data should be equal to the number of qubits"
        x = paddle.flatten(x)
        pad_num = 2 ** self.n - x.size
        if pad_num > 0:
            zero_tensor = paddle.zeros((pad_num,), x.dtype)
            x = paddle.concat([x, zero_tensor])
        length = paddle.norm(x, p=2)
        x = paddle.divide(x, length)
        if mode == "state_vector":
            x = paddle.cast(x, dtype="complex128")
        elif mode == "density_matrix":
            x = paddle.reshape(x, (2**self.n, 1))
            x = matmul(x, dagger(x))
        else:
            raise ValueError("the mode should be state_vector or density_matrix")
        return x

    def angle_encoding(self, x, encoding_gate, invert=False):
        r"""将输入的经典数据使用角度编码的方式进行编码。

        Args:
            x (Tensor): 待编码的向量
            encoding_gate (str): 编码要用的量子门,可以是 ``"rx"`` 、 ``"ry"`` 和 ``"rz"``
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
        assert x.size <= self.n, "the number of classical data should be equal to the number of qubits"
        x = paddle.flatten(x)
        if invert:
            x = -x

        def add_encoding_gate(theta, idx, gate):
            if gate == "rx":
                self.rx(theta, idx)
            elif gate == "ry":
                self.ry(theta, idx)
            elif gate == "rz":
                self.rz(theta, idx)
            else:
                raise ValueError("the encoding_gate should be rx, ry, or rz")

        for idx, element in enumerate(x):
            add_encoding_gate(element[0], idx, encoding_gate)

    def iqp_encoding(self, x, num_repeats=1, pattern=None, invert=False):
        r"""将输入的经典数据使用 IQP 编码的方式进行编码。

        Args:
            x (Tensor): 待编码的向量
            num_repeats (int): 编码层的层数
            pattern (list): 量子比特的纠缠方式
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
        assert x.size <= self.n, "the number of classical data should be equal to the number of qubits"
        num_x = x.size
        x = paddle.flatten(x)
        if pattern is None:
            pattern = list()
            for idx0 in range(0, self.n):
                for idx1 in range(idx0 + 1, self.n):
                    pattern.append((idx0, idx1))

        while num_repeats > 0:
            num_repeats -= 1
            if invert:
                for item in pattern:
                    self.cnot(list(item))
                    self.rz(-x[item[0]]*x[item[1]], item[1])
                    self.cnot(list(item))
                for idx in range(0, num_x):
                    self.rz(-x[idx], idx)
                for idx in range(0, num_x):
                    self.h(idx)
            else:
                for idx in range(0, num_x):
                    self.h(idx)
                for idx in range(0, num_x):
                    self.rz(x[idx], idx)
                for item in pattern:
                    self.cnot(list(item))
                    self.rz(x[item[0]]*x[item[1]], item[1])
                    self.cnot(list(item))

Q
Quleaf 已提交
486
    """
Q
Quleaf 已提交
487
    Common Gates
Q
Quleaf 已提交
488 489
    """

Q
Quleaf 已提交
490
    def rx(self, theta, which_qubit):
Q
Quleaf 已提交
491 492
        r"""添加关于 x 轴的单量子比特旋转门。

Q
Quleaf 已提交
493
        其矩阵形式为:
Q
Quleaf 已提交
494
        
Q
Quleaf 已提交
495
        .. math::
Q
Quleaf 已提交
496
        
Q
Quleaf 已提交
497
            \begin{bmatrix} \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\ -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}
Q
Quleaf 已提交
498

Q
Quleaf 已提交
499
        Args:
Q
Quleaf 已提交
500
            theta (Tensor): 旋转角度
Q
Quleaf 已提交
501
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
502

Q
Quleaf 已提交
503 504 505
        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
506
            import paddle
Q
Quleaf 已提交
507 508
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
509 510 511 512 513 514
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rx(theta[0], which_qubit)

Q
Quleaf 已提交
515
        """
Q
Quleaf 已提交
516 517 518 519
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append(['rx', [which_qubit], [theta,
                                                     paddle.to_tensor(np.array([-math.pi / 2])),
                                                     paddle.to_tensor(np.array([math.pi / 2]))]])
Q
Quleaf 已提交
520 521

    def ry(self, theta, which_qubit):
Q
Quleaf 已提交
522
        r"""添加关于 y 轴的单量子比特旋转门。
Q
Quleaf 已提交
523 524

        其矩阵形式为:
Q
Quleaf 已提交
525
        
Q
Quleaf 已提交
526
        .. math::
Q
Quleaf 已提交
527
        
Q
Quleaf 已提交
528 529 530
            \begin{bmatrix} \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\ \sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}

        Args:
Q
Quleaf 已提交
531
            theta (Tensor): 旋转角度
Q
Quleaf 已提交
532
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
533 534

        ..  code-block:: python
Q
Quleaf 已提交
535
        
Q
Quleaf 已提交
536
            import numpy as np
Q
Quleaf 已提交
537
            import paddle
Q
Quleaf 已提交
538 539
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
540 541 542 543 544
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.ry(theta[0], which_qubit)
Q
Quleaf 已提交
545
        """
Q
Quleaf 已提交
546 547 548 549
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append(['ry', [which_qubit], [theta,
                                                     paddle.to_tensor(np.array([0.0])),
                                                     paddle.to_tensor(np.array([0.0]))]])
Q
Quleaf 已提交
550 551

    def rz(self, theta, which_qubit):
Q
Quleaf 已提交
552 553
        r"""添加关于 z 轴的单量子比特旋转门。

Q
Quleaf 已提交
554
        其矩阵形式为:
Q
Quleaf 已提交
555
        
Q
Quleaf 已提交
556
        .. math::
Q
Quleaf 已提交
557

Q
Quleaf 已提交
558
            \begin{bmatrix} 1 & 0 \\ 0 & e^{i\theta} \end{bmatrix}
Q
Quleaf 已提交
559

Q
Quleaf 已提交
560
        Args:
Q
Quleaf 已提交
561
            theta (Tensor): 旋转角度
Q
Quleaf 已提交
562
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
563

Q
Quleaf 已提交
564
        ..  code-block:: python
Q
Quleaf 已提交
565
        
Q
Quleaf 已提交
566
            import numpy as np
Q
Quleaf 已提交
567
            import paddle
Q
Quleaf 已提交
568 569
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
570 571 572 573 574
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rz(theta[0], which_qubit)
Q
Quleaf 已提交
575
        """
Q
Quleaf 已提交
576 577 578 579
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append(['rz', [which_qubit], [paddle.to_tensor(np.array([0.0])),
                                                     paddle.to_tensor(np.array([0.0])),
                                                     theta]])
Q
Quleaf 已提交
580 581

    def cnot(self, control):
Q
Quleaf 已提交
582 583
        r"""添加一个 CNOT 门。

Q
Quleaf 已提交
584
        对于 2 量子比特的量子电路,当 ``control`` 为 ``[0, 1]`` 时,其矩阵形式为:
Q
Quleaf 已提交
585

Q
Quleaf 已提交
586
        .. math::
Q
Quleaf 已提交
587
        
Q
Quleaf 已提交
588 589 590 591
            \begin{align}
            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}
Q
Quleaf 已提交
592

Q
Quleaf 已提交
593
        Args:
Q
Quleaf 已提交
594
            control (list): 作用在的 qubit 的编号,``control[0]`` 为控制位,``control[1]`` 为目标位,其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
595 596

        ..  code-block:: python
Q
Quleaf 已提交
597
        
Q
Quleaf 已提交
598
            import numpy as np
Q
Quleaf 已提交
599
            import paddle
Q
Quleaf 已提交
600 601
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
602 603
            cir = UAnsatz(num_qubits)
            cir.cnot([0, 1])
Q
Quleaf 已提交
604 605
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n,\
Q
Quleaf 已提交
606
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
607
        assert control[0] != control[1], "the control qubit is the same as the target qubit"
Q
Quleaf 已提交
608
        self.__history.append(['CNOT', control, None])
Q
Quleaf 已提交
609

Q
Quleaf 已提交
610 611 612 613 614 615 616 617
    def swap(self, control):
        r"""添加一个 SWAP 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
618
            SWAP = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}
Q
Quleaf 已提交
619 620 621
            \end{align}

        Args:
Q
Quleaf 已提交
622
            control (list): 作用在的 qubit 的编号,``control[0]`` 和 ``control[1]`` 是想要交换的位,其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
623 624 625 626

        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
627
            import paddle 
Q
Quleaf 已提交
628 629
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
630 631
            cir = UAnsatz(num_qubits)
            cir.swap([0, 1])
Q
Quleaf 已提交
632
        """
Q
Quleaf 已提交
633
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n,\
Q
Quleaf 已提交
634
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
635
        assert control[0] != control[1], "the indices needed to be swapped should not be the same"
Q
Quleaf 已提交
636
        self.__history.append(['SWAP', control, None])
Q
Quleaf 已提交
637

Q
Quleaf 已提交
638
    def x(self, which_qubit):
Q
Quleaf 已提交
639 640
        r"""添加单量子比特 X 门。

Q
Quleaf 已提交
641
        其矩阵形式为:
Q
Quleaf 已提交
642
        
Q
Quleaf 已提交
643
        .. math::
Q
Quleaf 已提交
644
        
Q
Quleaf 已提交
645
            \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}
Q
Quleaf 已提交
646

Q
Quleaf 已提交
647
        Args:
Q
Quleaf 已提交
648
            which_qubit (int): 作用在的qubit的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
649

Q
Quleaf 已提交
650
        .. code-block:: python
Q
Quleaf 已提交
651 652
            
            import paddle
Q
Quleaf 已提交
653
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
654 655 656 657 658 659 660 661 662 663
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.x(which_qubit)
            cir.run_state_vector()
            print(cir.measure(shots = 0))

        ::

            {'0': 0.0, '1': 1.0}
Q
Quleaf 已提交
664
        """
Q
Quleaf 已提交
665
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
666 667 668
        self.__history.append(['x', [which_qubit], None])

    def y(self, which_qubit):
Q
Quleaf 已提交
669 670
        r"""添加单量子比特 Y 门。

Q
Quleaf 已提交
671
        其矩阵形式为:
Q
Quleaf 已提交
672
        
Q
Quleaf 已提交
673
        .. math::
Q
Quleaf 已提交
674
        
Q
Quleaf 已提交
675
            \begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}
Q
Quleaf 已提交
676

Q
Quleaf 已提交
677
        Args:
Q
Quleaf 已提交
678
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
679

Q
Quleaf 已提交
680
        .. code-block:: python
Q
Quleaf 已提交
681 682
            
            import paddle
Q
Quleaf 已提交
683
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
684 685 686 687 688 689 690 691 692 693
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.y(which_qubit)
            cir.run_state_vector()
            print(cir.measure(shots = 0))

        ::

            {'0': 0.0, '1': 1.0}
Q
Quleaf 已提交
694
        """
Q
Quleaf 已提交
695
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
696 697 698
        self.__history.append(['y', [which_qubit], None])

    def z(self, which_qubit):
Q
Quleaf 已提交
699 700
        r"""添加单量子比特 Z 门。

Q
Quleaf 已提交
701
        其矩阵形式为:
Q
Quleaf 已提交
702
        
Q
Quleaf 已提交
703
        .. math::
Q
Quleaf 已提交
704
        
Q
Quleaf 已提交
705
            \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}
Q
Quleaf 已提交
706

Q
Quleaf 已提交
707
        Args:
Q
Quleaf 已提交
708
            which_qubit (int): 作用在的qubit的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
709

Q
Quleaf 已提交
710
        .. code-block:: python
Q
Quleaf 已提交
711 712
        
            import paddle
Q
Quleaf 已提交
713
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
714 715 716 717 718 719 720 721 722 723
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.z(which_qubit)
            cir.run_state_vector()
            print(cir.measure(shots = 0))

        ::

            {'0': 1.0, '1': 0.0}
Q
Quleaf 已提交
724
        """
Q
Quleaf 已提交
725
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
726 727 728
        self.__history.append(['z', [which_qubit], None])

    def h(self, which_qubit):
Q
Quleaf 已提交
729
        r"""添加一个单量子比特的 Hadamard 门。
Q
Quleaf 已提交
730

Q
Quleaf 已提交
731
        其矩阵形式为:
Q
Quleaf 已提交
732 733

        .. math::
Q
Quleaf 已提交
734
        
Q
Quleaf 已提交
735 736 737
            H = \frac{1}{\sqrt{2}}\begin{bmatrix} 1&1\\1&-1 \end{bmatrix}

        Args:
Q
Quleaf 已提交
738
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
739
        """
Q
Quleaf 已提交
740
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
741 742 743
        self.__history.append(['h', [which_qubit], None])

    def s(self, which_qubit):
Q
Quleaf 已提交
744
        r"""添加一个单量子比特的 S 门。
Q
Quleaf 已提交
745

Q
Quleaf 已提交
746
        其矩阵形式为:
Q
Quleaf 已提交
747 748

        .. math::
Q
Quleaf 已提交
749
        
Q
Quleaf 已提交
750 751 752
            S = \begin{bmatrix} 1&0\\0&i \end{bmatrix}

        Args:
Q
Quleaf 已提交
753
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
754
        """
Q
Quleaf 已提交
755 756
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append(['s', [which_qubit], [paddle.to_tensor(np.array([0.0])),
Q
Quleaf 已提交
757 758
                                                    paddle.to_tensor(np.array([0.0])),
                                                    paddle.to_tensor(np.array([math.pi / 2]))]])
Q
Quleaf 已提交
759 760

    def t(self, which_qubit):
Q
Quleaf 已提交
761
        r"""添加一个单量子比特的 T 门。
Q
Quleaf 已提交
762

Q
Quleaf 已提交
763
        其矩阵形式为:
Q
Quleaf 已提交
764 765 766 767

        .. math::

            T = \begin{bmatrix} 1&0\\0&e^\frac{i\pi}{4} \end{bmatrix}
Q
Quleaf 已提交
768

Q
Quleaf 已提交
769
        Args:
Q
Quleaf 已提交
770
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
771
        """
Q
Quleaf 已提交
772 773
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append(['t', [which_qubit], [paddle.to_tensor(np.array([0.0])),
Q
Quleaf 已提交
774 775
                                                    paddle.to_tensor(np.array([0.0])),
                                                    paddle.to_tensor(np.array([math.pi / 4]))]])
Q
Quleaf 已提交
776 777 778 779

    def u3(self, theta, phi, lam, which_qubit):
        r"""添加一个单量子比特的旋转门。

Q
Quleaf 已提交
780
        其矩阵形式为:
Q
Quleaf 已提交
781

Q
Quleaf 已提交
782
        .. math::
Q
Quleaf 已提交
783
        
Q
Quleaf 已提交
784 785 786 787 788 789 790 791 792
            \begin{align}
            U3(\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:
Q
Quleaf 已提交
793 794 795
              theta (Tensor): 旋转角度 :math:`\theta` 。
              phi (Tensor): 旋转角度 :math:`\phi` 。
              lam (Tensor): 旋转角度 :math:`\lambda` 。
Q
Quleaf 已提交
796
              which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
797
        """
Q
Quleaf 已提交
798
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
799
        self.__history.append(['u', [which_qubit], [theta, phi, lam]])
Q
Quleaf 已提交
800

Q
Quleaf 已提交
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
    def rxx(self, theta, which_qubits):
        r"""添加一个 RXX 门。

        其矩阵形式为:

        .. math::

            \begin{align}
            RXX(\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:
            theta (Tensor): 旋转角度
            which_qubits (list): 作用在的两个量子比特的编号,其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            cir.rxx(paddle.to_tensor(np.array([np.pi/2])), [0, 1])
        """
        assert 0 <= which_qubits[0] < self.n and 0 <= which_qubits[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubits[0] != which_qubits[1], "the indices of two qubits should be different"
        self.__history.append(['RXX_gate', which_qubits, theta])

    def ryy(self, theta, which_qubits):
        r"""添加一个 RYY 门。

        其矩阵形式为:

        .. math::

            \begin{align}
            RYY(\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:
            theta (Tensor): 旋转角度
            which_qubits (list): 作用在的两个量子比特的编号,其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            cir.ryy(paddle.to_tensor(np.array([np.pi/2])), [0, 1])
        """
        assert 0 <= which_qubits[0] < self.n and 0 <= which_qubits[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubits[0] != which_qubits[1], "the indices of two qubits should be different"
        self.__history.append(['RYY_gate', which_qubits, theta])

    def rzz(self, theta, which_qubits):
        r"""添加一个 RZZ 门。

        其矩阵形式为:

        .. math::

            \begin{align}
            RZZ(\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:
            theta (Tensor): 旋转角度
            which_qubits (list): 作用在的两个量子比特的编号,其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            cir.rzz(paddle.to_tensor(np.array([np.pi/2])), [0, 1])
        """
        assert 0 <= which_qubits[0] < self.n and 0 <= which_qubits[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubits[0] != which_qubits[1], "the indices of two qubits should be different"
        self.__history.append(['RZZ_gate', which_qubits, theta])

    def ms(self, which_qubits):
        r"""添加一个 Mølmer-Sørensen (MS) 门,用于离子阱设备。

        其矩阵形式为:

        .. math::

            \begin{align}
            MS = RXX(-\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:
            which_qubits (list): 作用在的两个量子比特的编号,其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        Note:
            参考文献 https://arxiv.org/abs/quant-ph/9810040

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            cir.ms([0, 1])
        """
        assert 0 <= which_qubits[0] < self.n and 0 <= which_qubits[1] < self.n, \
            "the qubit should >= 0 and < n(the number of qubit)"
        assert which_qubits[0] != which_qubits[1], "the indices of two qubits should be different"
        self.__history.append(['MS_gate', which_qubits, paddle.to_tensor(-np.array([np.pi / 2]))])

Q
Quleaf 已提交
943 944 945 946
    def universal_2_qubit_gate(self, theta, which_qubits):
        r"""添加 2-qubit 通用门,这个通用门需要 15 个参数。

        Args:
Q
Quleaf 已提交
947
            theta (Tensor): 2-qubit 通用门的参数,其维度为 ``(15, )``
Q
Quleaf 已提交
948 949 950 951 952 953 954
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
955
            import paddle
Q
Quleaf 已提交
956 957
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
958 959 960 961 962
            theta = paddle.to_tensor(np.ones(15))
            cir = UAnsatz(n)
            cir.universal_2_qubit_gate(theta, [0, 1])
            cir.run_state_vector()
            print(cir.measure(shots = 0))
Q
Quleaf 已提交
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

        ::

            {'00': 0.4306256106527819, '01': 0.07994547866706268, '10': 0.07994547866706264, '11': 0.40948343201309334}
        """
 
        assert len(theta.shape) == 1, 'The shape of theta is not right'
        assert len(theta) == 15, 'This Ansatz accepts 15 parameters'
        assert len(which_qubits) == 2, "You should add this gate on two qubits"

        a, b = which_qubits
    
        self.u3(theta[0], theta[1], theta[2], a)
        self.u3(theta[3], theta[4], theta[5], b)
        self.cnot([b, a])
        self.rz(theta[6], a)
        self.ry(theta[7], b)
        self.cnot([a, b])
        self.ry(theta[8], b)
        self.cnot([b, a])
        self.u3(theta[9], theta[10], theta[11], a)
        self.u3(theta[12], theta[13], theta[14], b)

    def __u3qg_U(self, theta, which_qubits):
        r"""
        用于构建 universal_3_qubit_gate
        """
        self.cnot(which_qubits[1:])
        self.ry(theta[0], which_qubits[1])
        self.cnot(which_qubits[:2])
        self.ry(theta[1], which_qubits[1])
        self.cnot(which_qubits[:2])
        self.cnot(which_qubits[1:])
        self.h(which_qubits[2])
        self.cnot([which_qubits[1], which_qubits[0]])
        self.cnot([which_qubits[0], which_qubits[2]])
        self.cnot(which_qubits[1:])
        self.rz(theta[2], which_qubits[2])
        self.cnot(which_qubits[1:])
        self.cnot([which_qubits[0], which_qubits[2]])

    def __u3qg_V(self, theta, which_qubits):
        r"""
        用于构建 universal_3_qubit_gate
        """
        self.cnot([which_qubits[2], which_qubits[0]])
        self.cnot(which_qubits[:2])
        self.cnot([which_qubits[2], which_qubits[1]])
        self.ry(theta[0], which_qubits[2])
        self.cnot(which_qubits[1:])
        self.ry(theta[1], which_qubits[2])
        self.cnot(which_qubits[1:])
        self.s(which_qubits[2])
        self.cnot([which_qubits[2], which_qubits[0]])
        self.cnot(which_qubits[:2])
        self.cnot([which_qubits[1], which_qubits[0]])
        self.h(which_qubits[2])
        self.cnot([which_qubits[0], which_qubits[2]])
        self.rz(theta[2], which_qubits[2])
        self.cnot([which_qubits[0], which_qubits[2]])

    def universal_3_qubit_gate(self, theta, which_qubits):
        r"""添加 3-qubit 通用门,这个通用门需要 81 个参数。

        Note:
            参考: https://cds.cern.ch/record/708846/files/0401178.pdf

        Args:
Q
Quleaf 已提交
1031
            theta (Tensor): 3-qubit 通用门的参数,其维度为 ``(81, )``
Q
Quleaf 已提交
1032 1033 1034 1035 1036 1037 1038
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
1039
            import paddle
Q
Quleaf 已提交
1040 1041
            from paddle_quantum.circuit import UAnsatz
            n = 3
Q
Quleaf 已提交
1042 1043 1044 1045 1046
            theta = paddle.to_tensor(np.ones(81))
            cir = UAnsatz(n)
            cir.universal_3_qubit_gate(theta, [0, 1, 2])
            cir.run_state_vector()
            print(cir.measure(shots = 0))
Q
Quleaf 已提交
1047 1048 1049 1050 1051 1052 1053 1054

        ::

            {'000': 0.06697926831547105, '001': 0.13206788591381013, '010': 0.2806525391078656, '011': 0.13821526515701105, '100': 0.1390530116439897, '101': 0.004381404333075108, '110': 0.18403296778911565, '111': 0.05461765773966483}
        """
        assert len(which_qubits) == 3, "You should add this gate on three qubits"
        assert len(theta) == 81, "The length of theta is supposed to be 81"

Q
Quleaf 已提交
1055 1056
        psi = reshape(x=theta[: 60], shape=[4, 15])
        phi = reshape(x=theta[60:], shape=[7, 3])
Q
Quleaf 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        self.universal_2_qubit_gate(psi[0], which_qubits[:2])
        self.u3(phi[0][0], phi[0][1], phi[0][2], which_qubits[2])

        self.__u3qg_U(phi[1], which_qubits)

        self.universal_2_qubit_gate(psi[1], which_qubits[:2])
        self.u3(phi[2][0], phi[2][1], phi[2][2], which_qubits[2])

        self.__u3qg_V(phi[3], which_qubits)

        self.universal_2_qubit_gate(psi[2], which_qubits[:2])
        self.u3(phi[4][0], phi[4][1], phi[4][2], which_qubits[2])

        self.__u3qg_U(phi[5], which_qubits)

        self.universal_2_qubit_gate(psi[3], which_qubits[:2])
        self.u3(phi[6][0], phi[6][1], phi[6][2], which_qubits[2])

Q
Quleaf 已提交
1075
    """
Q
Quleaf 已提交
1076
    Measurements
Q
Quleaf 已提交
1077 1078
    """

Q
Quleaf 已提交
1079 1080 1081 1082
    def __process_string(self, s, which_qubits):
        r"""
        This functions return part of string s baesd on which_qubits
        If s = 'abcdefg', which_qubits = [0,2,5], then it returns 'acf'
Q
Quleaf 已提交
1083

Q
Quleaf 已提交
1084 1085 1086 1087 1088
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        new_s = ''.join(s[j] for j in which_qubits)
        return new_s
Q
Quleaf 已提交
1089

Q
Quleaf 已提交
1090 1091 1092 1093
    def __process_similiar(self, result):
        r"""
        This functions merges values based on identical keys.
        If result = [('00', 10), ('01', 20), ('11', 30), ('11', 40), ('11', 50), ('00', 60)], then it returns {'00': 70, '01': 20, '11': 120}
Q
Quleaf 已提交
1094

Q
Quleaf 已提交
1095 1096 1097 1098 1099 1100
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        data = defaultdict(int)
        for idx, val in result:
            data[idx] += val
Q
Quleaf 已提交
1101

Q
Quleaf 已提交
1102
        return dict(data)
Q
Quleaf 已提交
1103

Q
Quleaf 已提交
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
    def __measure_hist(self, result, which_qubits, shots):
        r"""将测量的结果以柱状图的形式呈现。

        Note:
            这是内部函数,你并不需要直接调用到该函数。

        Args:
              result (dictionary): 测量结果
              which_qubits (list): 测量的量子比特,如测量所有则是 ``None``
              shots(int): 测量次数

        Returns
            dict: 测量结果

        """
        n = self.n if which_qubits is None else len(which_qubits)
        assert n < 6, "Too many qubits to plot"

        ylabel = "Measured Probabilities"
        if shots == 0:
            shots = 1
            ylabel = "Probabilities"

        state_list = [np.binary_repr(index, width=n) for index in range(0, 2 ** n)]
        freq = []
        for state in state_list:
            freq.append(result.get(state, 0.0) / shots)

        plt.bar(range(2 ** n), freq, tick_label=state_list)
        plt.xticks(rotation=90)
        plt.xlabel("Qubit State")
        plt.ylabel(ylabel)
        plt.show()

        return result

    # Which_qubits is list-like
    def measure(self, which_qubits=None, shots=2 ** 10, plot=False):
Q
Quleaf 已提交
1142
        r"""对量子电路输出的量子态进行测量。
Q
Quleaf 已提交
1143 1144

        Warning:
Q
Quleaf 已提交
1145
            当 ``plot`` 为 ``True`` 时,当前量子电路的量子比特数需要小于 6 ,否则无法绘制图片,会抛出异常。
Q
Quleaf 已提交
1146 1147 1148

        Args:
            which_qubits (list, optional): 要测量的qubit的编号,默认全都测量
Q
Quleaf 已提交
1149
            shots (int, optional): 该量子电路输出的量子态的测量次数,默认为 1024 次;若为 0,则返回测量结果的精确概率分布
Q
Quleaf 已提交
1150
            plot (bool, optional): 是否绘制测量结果图,默认为 ``False`` ,即不绘制
Q
Quleaf 已提交
1151
        
Q
Quleaf 已提交
1152 1153 1154 1155 1156 1157
        Returns:
            dict: 测量的结果

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1158
        
Q
Quleaf 已提交
1159 1160
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1161 1162 1163 1164 1165 1166
            cir = UAnsatz(2)
            cir.h(0)
            cir.cnot([0,1])
            cir.run_state_vector()
            result = cir.measure(shots = 2048, which_qubits = [1])
            print(f"The results of measuring qubit 1 2048 times are {result}")
Q
Quleaf 已提交
1167 1168 1169

        ::

Q
Quleaf 已提交
1170
            The results of measuring qubit 1 2048 times are {'0': 964, '1': 1084}
Q
Quleaf 已提交
1171 1172

        .. code-block:: python
Q
Quleaf 已提交
1173

Q
Quleaf 已提交
1174 1175
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1176 1177 1178 1179 1180 1181
            cir = UAnsatz(2)
            cir.h(0)
            cir.cnot([0,1])
            cir.run_state_vector()
            result = cir.measure(shots = 0, which_qubits = [1])
            print(f"The probability distribution of measurement results on qubit 1 is {result}")
Q
Quleaf 已提交
1182 1183 1184

        ::

Q
Quleaf 已提交
1185
            The probability distribution of measurement results on qubit 1 is {'0': 0.4999999999999999, '1': 0.4999999999999999}
Q
Quleaf 已提交
1186 1187 1188 1189 1190 1191
        """
        if self.__run_state == 'state_vector':
            state = self.__state
        elif self.__run_state == 'density_matrix':
            # Take the diagonal of the density matrix as a probability distribution
            diag = np.diag(self.__state.numpy())
Q
Quleaf 已提交
1192
            state = paddle.to_tensor(np.sqrt(diag))
Q
Quleaf 已提交
1193 1194 1195 1196 1197 1198 1199 1200
        else:
            # Raise error
            raise ValueError("no state for measurement; please run the circuit first")

        if shots == 0:  # Returns probability distribution over all measurement results
            dic2to10, dic10to2 = dic_between2and10(self.n)
            result = {}
            for i in range(2 ** self.n):
Q
Quleaf 已提交
1201
                result[dic10to2[i]] = (real(state)[i] ** 2 + imag(state)[i] ** 2).numpy()[0]
Q
Quleaf 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

            if which_qubits is not None:
                new_result = [(self.__process_string(key, which_qubits), value) for key, value in result.items()]
                result = self.__process_similiar(new_result)
        else:
            if which_qubits is None:  # Return all the qubits
                result = measure_state(state, shots)
            else:
                assert all([e < self.n for e in which_qubits]), 'Qubit index out of range'
                which_qubits.sort()  # Sort in ascending order

                collapse_all = measure_state(state, shots)
                new_collapse_all = [(self.__process_string(key, which_qubits), value) for key, value in
                                    collapse_all.items()]
                result = self.__process_similiar(new_collapse_all)

        return result if not plot else self.__measure_hist(result, which_qubits, shots)

    def expecval(self, H):
Q
Quleaf 已提交
1221
        r"""量子电路输出的量子态关于可观测量 H 的期望值。
Q
Quleaf 已提交
1222 1223 1224 1225 1226 1227

        Hint:
            如果想输入的可观测量的矩阵为 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I` 。则 ``H`` 应为 ``[[0.7, 'z0,x1'], [0.2, 'z1']]`` 。
        Args:
            H (list): 可观测量的相关信息
        Returns:
Q
Quleaf 已提交
1228
            Tensor: 量子电路输出的量子态关于 H 的期望值
Q
Quleaf 已提交
1229 1230

        代码示例:
Q
Quleaf 已提交
1231
        
Q
Quleaf 已提交
1232
        .. code-block:: python
Q
Quleaf 已提交
1233 1234
            
            import paddle
Q
Quleaf 已提交
1235 1236 1237
            from paddle_quantum.circuit import UAnsatz
            n = 5
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
Q
Quleaf 已提交
1238
            theta = paddle.ones([3], dtype='float64')
Q
Quleaf 已提交
1239 1240 1241 1242 1243 1244 1245
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.rz(theta[1], 1)
            cir.rx(theta[2], 2)
            cir.run_state_vector()
            expect_value = cir.expecval(H_info).numpy()
            print(f'Calculated expectation value of {H_info} is {expect_value}')
Q
Quleaf 已提交
1246

Q
Quleaf 已提交
1247
        ::
Q
Quleaf 已提交
1248

Q
Quleaf 已提交
1249
            Calculated expectation value of [[0.1, 'x1'], [0.2, 'y0,z4']] is [-0.1682942]
Q
Quleaf 已提交
1250

Q
Quleaf 已提交
1251 1252
        """
        if self.__run_state == 'state_vector':
Q
Quleaf 已提交
1253
            return real(vec_expecval(H, self.__state))
Q
Quleaf 已提交
1254 1255
        elif self.__run_state == 'density_matrix':
            state = self.__state
Q
Quleaf 已提交
1256 1257
            H_mat = paddle.to_tensor(pauli_str_to_matrix(H, self.n))
            return real(trace(matmul(state, H_mat)))
Q
Quleaf 已提交
1258 1259 1260
        else:
            # Raise error
            raise ValueError("no state for measurement; please run the circuit first")
Q
Quleaf 已提交
1261 1262

    """
Q
Quleaf 已提交
1263
    Circuit Templates
Q
Quleaf 已提交
1264 1265
    """

Q
Quleaf 已提交
1266
    def superposition_layer(self):
Q
Quleaf 已提交
1267
        r"""添加一层 Hadamard 门。
Q
Quleaf 已提交
1268 1269 1270 1271

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1272
        
Q
Quleaf 已提交
1273 1274
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1275 1276 1277 1278 1279
            cir = UAnsatz(2)
            cir.superposition_layer()
            cir.run_state_vector()
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")
Q
Quleaf 已提交
1280 1281 1282

        ::

Q
Quleaf 已提交
1283
            The probability distribution of measurement results on both qubits is {'00': 0.2499999999999999, '01': 0.2499999999999999, '10': 0.2499999999999999, '11': 0.2499999999999999}
Q
Quleaf 已提交
1284
        """
Q
Quleaf 已提交
1285 1286 1287 1288
        for i in range(self.n):
            self.h(i)

    def weak_superposition_layer(self):
Q
Quleaf 已提交
1289
        r"""添加一层旋转角度为 :math:`\pi/4` 的 Ry 门。
Q
Quleaf 已提交
1290 1291 1292 1293

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1294
        
Q
Quleaf 已提交
1295 1296
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1297 1298 1299 1300 1301
            cir = UAnsatz(2)
            cir.weak_superposition_layer()
            cir.run_state_vector()
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")
Q
Quleaf 已提交
1302 1303 1304

        ::

Q
Quleaf 已提交
1305
            The probability distribution of measurement results on both qubits is {'00': 0.7285533905932737, '01': 0.12500000000000003, '10': 0.12500000000000003, '11': 0.021446609406726238}
Q
Quleaf 已提交
1306
        """
Q
Quleaf 已提交
1307
        _theta = paddle.to_tensor(np.array([np.pi / 4]))  # Used in fixed Ry gate
Q
Quleaf 已提交
1308 1309
        for i in range(self.n):
            self.ry(_theta, i)
Q
Quleaf 已提交
1310

Q
Quleaf 已提交
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
    def linear_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 Ry 门,Rz 门和 CNOT 门的线性纠缠层。

        Attention:
            ``theta`` 的维度为 ``(depth, n, 2)`` ,最低维内容为对应的 ``ry`` 和 ``rz`` 的参数。

        Args:
            theta (Tensor): Ry 门和 Rz 门的旋转角度
            depth (int): 纠缠层的深度
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
            theta = paddle.ones([DEPTH, n, 2], dtype='float64')
            cir = UAnsatz(n)
            cir.linear_entangled_layer(theta, DEPTH, [0, 1])
            cir.run_state_vector()
            print(cir.measure(shots = 0))

        ::

            {'00': 0.646611169077063, '01': 0.06790630495474384, '10': 0.19073671025717626, '11': 0.09474581571101756}
        """
        assert self.n > 1, 'you need at least 2 qubits'
        assert len(theta.shape) == 3, 'the shape of theta is not right'
        assert theta.shape[2] == 2, 'the shape of theta is not right'
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'

        if which_qubits is None:
            which_qubits = np.arange(self.n)

        for repeat in range(depth):
            for i, q in enumerate(which_qubits):
                self.ry(theta[repeat][i][0], q)
            for i in range(len(which_qubits) - 1):
                self.cnot([which_qubits[i], which_qubits[i + 1]])
            for i, q in enumerate(which_qubits):
                self.rz(theta[repeat][i][1], q)
            for i in range(len(which_qubits) - 1):
                self.cnot([which_qubits[i + 1], which_qubits[i]])

Q
Quleaf 已提交
1359 1360
    def real_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 Ry 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
1361

Q
Quleaf 已提交
1362 1363
        Note:
            这一层量子门的数学表示形式为实数酉矩阵。
Q
Quleaf 已提交
1364

Q
Quleaf 已提交
1365
        Attention:
Q
Quleaf 已提交
1366
            ``theta`` 的维度为 ``(depth, n, 1)`` 。
Q
Quleaf 已提交
1367

Q
Quleaf 已提交
1368
        Args:
Q
Quleaf 已提交
1369
            theta (Tensor): Ry 门的旋转角度
Q
Quleaf 已提交
1370
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
1371
            which_qubits(list): 作用的量子比特编号
Q
Quleaf 已提交
1372 1373 1374 1375

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1376

Q
Quleaf 已提交
1377
            import paddle
Q
Quleaf 已提交
1378 1379 1380
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
1381
            theta = paddle.ones([DEPTH, n, 1], dtype='float64')
Q
Quleaf 已提交
1382 1383 1384 1385 1386
            cir = UAnsatz(n)
            cir.real_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
            print(cir.measure(shots = 0))
        
Q
Quleaf 已提交
1387 1388 1389
        ::

            {'00': 2.52129874867343e-05, '01': 0.295456784923382, '10': 0.7045028818254718, '11': 1.5120263659845063e-05}
Q
Quleaf 已提交
1390
        """
Q
Quleaf 已提交
1391 1392 1393
        assert self.n > 1, 'you need at least 2 qubits'
        assert len(theta.shape) == 3, 'the shape of theta is not right'
        assert theta.shape[2] == 1, 'the shape of theta is not right'
Q
Quleaf 已提交
1394
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
1395 1396
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'

Q
Quleaf 已提交
1397 1398 1399
        if which_qubits is None:
            which_qubits = np.arange(self.n)

Q
Quleaf 已提交
1400
        for repeat in range(depth):
Q
Quleaf 已提交
1401
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
1402
                self.ry(theta[repeat][i][0], q)
Q
Quleaf 已提交
1403 1404 1405
            for i in range(len(which_qubits) - 1):
                self.cnot([which_qubits[i], which_qubits[i + 1]])
            self.cnot([which_qubits[-1], which_qubits[0]])
Q
Quleaf 已提交
1406

Q
Quleaf 已提交
1407 1408
    def complex_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
1409 1410 1411

        Note:
            这一层量子门的数学表示形式为复数酉矩阵。
Q
Quleaf 已提交
1412
        
Q
Quleaf 已提交
1413
        Attention:
Q
Quleaf 已提交
1414
            ``theta`` 的维度为 ``(depth, n, 3)`` ,最低维内容为对应的 ``u3`` 的参数 ``(theta, phi, lam)`` 。
Q
Quleaf 已提交
1415
        
Q
Quleaf 已提交
1416
        Args:
Q
Quleaf 已提交
1417
            theta (Tensor): U3 门的旋转角度
Q
Quleaf 已提交
1418
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
1419
            which_qubits(list): 作用的量子比特编号
Q
Quleaf 已提交
1420 1421 1422 1423

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1424 1425
        
            import paddle
Q
Quleaf 已提交
1426 1427 1428
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
1429
            theta = paddle.ones([DEPTH, n, 3], dtype='float64')
Q
Quleaf 已提交
1430 1431 1432 1433 1434
            cir = UAnsatz(n)
            cir.complex_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
            print(cir.measure(shots = 0))
        
Q
Quleaf 已提交
1435 1436 1437
        ::

            {'00': 0.15032627279218896, '01': 0.564191201239618, '10': 0.03285998070292556, '11': 0.25262254526526823}
Q
Quleaf 已提交
1438
        """
Q
Quleaf 已提交
1439 1440 1441
        assert self.n > 1, 'you need at least 2 qubits'
        assert len(theta.shape) == 3, 'the shape of theta is not right'
        assert theta.shape[2] == 3, 'the shape of theta is not right'
Q
Quleaf 已提交
1442
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
1443
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'
Q
Quleaf 已提交
1444

Q
Quleaf 已提交
1445 1446
        if which_qubits is None:
            which_qubits = np.arange(self.n)
Q
Quleaf 已提交
1447

Q
Quleaf 已提交
1448 1449
        for repeat in range(depth):
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
1450
                self.u3(theta[repeat][i][0], theta[repeat][i][1], theta[repeat][i][2], q)
Q
Quleaf 已提交
1451 1452 1453
            for i in range(len(which_qubits) - 1):
                self.cnot([which_qubits[i], which_qubits[i + 1]])
            self.cnot([which_qubits[-1], which_qubits[0]])
Q
Quleaf 已提交
1454 1455 1456 1457 1458 1459 1460

    def __add_real_block(self, theta, position):
        r"""
        Add a real block to the circuit in (position). theta is a one dimensional tensor

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
1461
        """
Q
Quleaf 已提交
1462 1463 1464 1465
        assert len(theta) == 4, 'the length of theta is not right'
        assert 0 <= position[0] < self.n and 0 <= position[1] < self.n, 'position is out of range'
        self.ry(theta[0], position[0])
        self.ry(theta[1], position[1])
Q
Quleaf 已提交
1466

Q
Quleaf 已提交
1467
        self.cnot([position[0], position[1]])
Q
Quleaf 已提交
1468

Q
Quleaf 已提交
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
        self.ry(theta[2], position[0])
        self.ry(theta[3], position[1])

    def __add_complex_block(self, theta, position):
        r"""
        Add a complex block to the circuit in (position). theta is a one dimensional tensor

        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        assert len(theta) == 12, 'the length of theta is not right'
        assert 0 <= position[0] < self.n and 0 <= position[1] < self.n, 'position is out of range'
        self.u3(theta[0], theta[1], theta[2], position[0])
        self.u3(theta[3], theta[4], theta[5], position[1])

        self.cnot([position[0], position[1]])

        self.u3(theta[6], theta[7], theta[8], position[0])
        self.u3(theta[9], theta[10], theta[11], position[1])

    def __add_real_layer(self, theta, position):
        r"""
        Add a real layer on the circuit. theta is a two dimensional tensor. position is the qubit range the layer needs to cover

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
1495
        """
Q
Quleaf 已提交
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        assert theta.shape[1] == 4 and theta.shape[0] == (position[1] - position[0] + 1) / 2,\
            'the shape of theta is not right'
        for i in range(position[0], position[1], 2):
            self.__add_real_block(theta[int((i - position[0]) / 2)], [i, i + 1])

    def __add_complex_layer(self, theta, position):
        r"""
        Add a complex layer on the circuit. theta is a two dimensional tensor. position is the qubit range the layer needs to cover

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
1507
        """
Q
Quleaf 已提交
1508 1509 1510 1511
        assert theta.shape[1] == 12 and theta.shape[0] == (position[1] - position[0] + 1) / 2,\
            'the shape of theta is not right'
        for i in range(position[0], position[1], 2):
            self.__add_complex_block(theta[int((i - position[0]) / 2)], [i, i + 1])
Q
Quleaf 已提交
1512

Q
Quleaf 已提交
1513
    def real_block_layer(self, theta, depth):
Q
Quleaf 已提交
1514
        r"""添加 ``depth`` 层包含 Ry 门和 CNOT 门的弱纠缠层。
Q
Quleaf 已提交
1515

Q
Quleaf 已提交
1516 1517
        Note:
            这一层量子门的数学表示形式为实数酉矩阵。
Q
Quleaf 已提交
1518
        
Q
Quleaf 已提交
1519
        Attention:
Q
Quleaf 已提交
1520
            ``theta`` 的维度为 ``(depth, n-1, 4)`` 。
Q
Quleaf 已提交
1521
        
Q
Quleaf 已提交
1522
        Args:
Q
Quleaf 已提交
1523
            theta(Tensor): Ry 门的旋转角度
Q
Quleaf 已提交
1524 1525 1526 1527 1528
            depth(int): 纠缠层的深度

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1529 1530 1531
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1532 1533
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
1534
            theta = paddle.ones([DEPTH, n - 1, 4], dtype='float64')
Q
Quleaf 已提交
1535 1536 1537 1538 1539
            cir = UAnsatz(n)
            cir.real_block_layer(paddle.to_tensor(theta), DEPTH)
            cir.run_density_matrix()
            print(cir.measure(shots = 0, which_qubits = [0]))
        
Q
Quleaf 已提交
1540 1541 1542
        ::

            {'0': 0.9646724056906162, '1': 0.035327594309385896}
Q
Quleaf 已提交
1543
        """
Q
Quleaf 已提交
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
        assert self.n > 1, 'you need at least 2 qubits'
        assert len(theta.shape) == 3, 'The dimension of theta is not right'
        _depth, m, block = theta.shape
        assert depth > 0, 'depth must be greater than zero'
        assert _depth == depth, 'the depth of parameters has a mismatch'
        assert m == self.n - 1 and block == 4, 'The shape of theta is not right'

        if self.n % 2 == 0:
            for i in range(depth):
                self.__add_real_layer(theta[i][:int(self.n / 2)], [0, self.n - 1])
                self.__add_real_layer(theta[i][int(self.n / 2):], [1, self.n - 2]) if self.n > 2 else None
        else:
            for i in range(depth):
                self.__add_real_layer(theta[i][:int((self.n - 1) / 2)], [0, self.n - 2])
                self.__add_real_layer(theta[i][int((self.n - 1) / 2):], [1, self.n - 1])

    def complex_block_layer(self, theta, depth):
Q
Quleaf 已提交
1561 1562
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的弱纠缠层。

Q
Quleaf 已提交
1563 1564 1565 1566
        Note:
            这一层量子门的数学表示形式为复数酉矩阵。

        Attention:
Q
Quleaf 已提交
1567
            ``theta`` 的维度为 ``(depth, n-1, 12)`` 。
Q
Quleaf 已提交
1568

Q
Quleaf 已提交
1569
        Args:
Q
Quleaf 已提交
1570
            theta (Tensor): U3 门的角度信息
Q
Quleaf 已提交
1571 1572 1573 1574 1575
            depth (int): 纠缠层的深度

        代码示例:

        .. code-block:: python
Q
Quleaf 已提交
1576 1577 1578
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1579 1580
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
1581
            theta = paddle.ones([DEPTH, n - 1, 12], dtype='float64')
Q
Quleaf 已提交
1582 1583 1584 1585 1586
            cir = UAnsatz(n)
            cir.complex_block_layer(paddle.to_tensor(theta), DEPTH)
            cir.run_density_matrix()
            print(cir.measure(shots = 0, which_qubits = [0]))
        
Q
Quleaf 已提交
1587
        ::
Q
Quleaf 已提交
1588

Q
Quleaf 已提交
1589
            {'0': 0.5271554811768046, '1': 0.4728445188231988}
Q
Quleaf 已提交
1590
        """
Q
Quleaf 已提交
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        assert self.n > 1, 'you need at least 2 qubits'
        assert len(theta.shape) == 3, 'The dimension of theta is not right'
        assert depth > 0, 'depth must be greater than zero'
        _depth, m, block = theta.shape
        assert _depth == depth, 'the depth of parameters has a mismatch'
        assert m == self.n - 1 and block == 12, 'The shape of theta is not right'

        if self.n % 2 == 0:
            for i in range(depth):
                self.__add_complex_layer(theta[i][:int(self.n / 2)], [0, self.n - 1])
                self.__add_complex_layer(theta[i][int(self.n / 2):], [1, self.n - 2]) if self.n > 2 else None
        else:
            for i in range(depth):
                self.__add_complex_layer(theta[i][:int((self.n - 1) / 2)], [0, self.n - 2])
                self.__add_complex_layer(theta[i][int((self.n - 1) / 2):], [1, self.n - 1])

Q
Quleaf 已提交
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
    """
    Channels
    """

    @apply_channel
    def amplitude_damping(self, gamma, which_qubit):
        r"""添加振幅阻尼信道。

        其 Kraus 算符为:
        
        .. math::

            E_0 = \begin{bmatrix} 1 & 0 \\ 0 & \sqrt{1-\gamma} \end{bmatrix},
            E_1 = \begin{bmatrix} 0 & \sqrt{\gamma} \\ 0 & 0 \end{bmatrix}.

        Args:
            gamma (float): 减振概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            gamma = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1635
            cir.cnot([0, 1])
Q
Quleaf 已提交
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
            cir.amplitude_damping(gamma, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.5       +0.j 0.        +0.j 0.        +0.j 0.47434165+0.j]
             [0.        +0.j 0.05      +0.j 0.        +0.j 0.        +0.j]
             [0.        +0.j 0.        +0.j 0.        +0.j 0.        +0.j]
             [0.47434165+0.j 0.        +0.j 0.        +0.j 0.45      +0.j]]
        """
        assert 0 <= gamma <= 1, 'the parameter gamma should be in range [0, 1]'

        e0 = paddle.to_tensor([[1, 0], [0, np.sqrt(1 - gamma)]], dtype='complex128')
        e1 = paddle.to_tensor([[0, np.sqrt(gamma)], [0, 0]], dtype='complex128')

        return [e0, e1]

    @apply_channel
    def generalized_amplitude_damping(self, gamma, p, which_qubit):
        r"""添加广义振幅阻尼信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \sqrt{p} \begin{bmatrix} 1 & 0 \\ 0 & \sqrt{1-\gamma} \end{bmatrix},
            E_1 = \sqrt{p} \begin{bmatrix} 0 & \sqrt{\gamma} \\ 0 & 0 \end{bmatrix},\\
            E_2 = \sqrt{1-p} \begin{bmatrix} \sqrt{1-\gamma} & 0 \\ 0 & 1 \end{bmatrix},
            E_3 = \sqrt{1-p} \begin{bmatrix} 0 & 0 \\ \sqrt{\gamma} & 0 \end{bmatrix}.

        Args:
            gamma (float): 减振概率,其值应该在 :math:`[0, 1]` 区间内
            p (float): 激发概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            gamma = 0.1
            p = 0.2
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1682
            cir.cnot([0, 1])
Q
Quleaf 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
            cir.generalized_amplitude_damping(gamma, p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.46      +0.j 0.        +0.j 0.        +0.j 0.47434165+0.j]
             [0.        +0.j 0.01      +0.j 0.        +0.j 0.        +0.j]
             [0.        +0.j 0.        +0.j 0.04      +0.j 0.        +0.j]
             [0.47434165+0.j 0.        +0.j 0.        +0.j 0.49      +0.j]]
        """
        assert 0 <= gamma <= 1, 'the parameter gamma should be in range [0, 1]'
        assert 0 <= p <= 1, 'The parameter p should be in range [0, 1]'

        e0 = paddle.to_tensor(np.sqrt(p) * np.array([[1, 0], [0, np.sqrt(1 - gamma)]], dtype='complex128'))
        e1 = paddle.to_tensor(np.sqrt(p) * np.array([[0, np.sqrt(gamma)], [0, 0]]), dtype='complex128')
        e2 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[np.sqrt(1 - gamma), 0], [0, 1]], dtype='complex128'))
        e3 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[0, 0], [np.sqrt(gamma), 0]]), dtype='complex128')

        return [e0, e1, e2, e3]

    @apply_channel
    def phase_damping(self, gamma, which_qubit):
        r"""添加相位阻尼信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \begin{bmatrix} 1 & 0 \\ 0 & \sqrt{1-\gamma} \end{bmatrix},
            E_1 = \begin{bmatrix} 0 & 0 \\ 0 & \sqrt{\gamma} \end{bmatrix}.

        Args:
            gamma (float): phase damping 信道的参数,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1728
            cir.cnot([0, 1])
Q
Quleaf 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
            cir.phase_damping(p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.5       +0.j 0.        +0.j 0.        +0.j 0.47434165+0.j]
             [0.        +0.j 0.        +0.j 0.        +0.j 0.        +0.j]
             [0.        +0.j 0.        +0.j 0.        +0.j 0.        +0.j]
             [0.47434165+0.j 0.        +0.j 0.        +0.j 0.5       +0.j]]
        """
        assert 0 <= gamma <= 1, 'the parameter gamma should be in range [0, 1]'

        e0 = paddle.to_tensor([[1, 0], [0, np.sqrt(1 - gamma)]], dtype='complex128')
        e1 = paddle.to_tensor([[0, 0], [0, np.sqrt(gamma)]], dtype='complex128')

        return [e0, e1]

    @apply_channel
    def bit_flip(self, p, which_qubit):
        r"""添加比特反转信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \sqrt{1-p} I,
            E_1 = \sqrt{p} X.

        Args:
            p (float): 发生 bit flip 的概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1771
            cir.cnot([0, 1])
Q
Quleaf 已提交
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
            cir.bit_flip(p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.45+0.j 0.  +0.j 0.  +0.j 0.45+0.j]
             [0.  +0.j 0.05+0.j 0.05+0.j 0.  +0.j]
             [0.  +0.j 0.05+0.j 0.05+0.j 0.  +0.j]
             [0.45+0.j 0.  +0.j 0.  +0.j 0.45+0.j]]
        """
        assert 0 <= p <= 1, 'the probability p of a bit flip should be in range [0, 1]'

        e0 = paddle.to_tensor([[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]], dtype='complex128')
        e1 = paddle.to_tensor([[0, np.sqrt(p)], [np.sqrt(p), 0]], dtype='complex128')

        return [e0, e1]

    @apply_channel
    def phase_flip(self, p, which_qubit):
        r"""添加相位反转信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \sqrt{1 - p} I,
            E_1 = \sqrt{p} Z.

        Args:
            p (float): 发生 phase flip 的概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1814
            cir.cnot([0, 1])
Q
Quleaf 已提交
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
            cir.phase_flip(p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.5+0.j 0. +0.j 0. +0.j 0.4+0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
             [0.4+0.j 0. +0.j 0. +0.j 0.5+0.j]]
        """
        assert 0 <= p <= 1, 'the probability p of a phase flip should be in range [0, 1]'

        e0 = paddle.to_tensor([[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]], dtype='complex128')
        e1 = paddle.to_tensor([[np.sqrt(p), 0], [0, -np.sqrt(p)]], dtype='complex128')

        return [e0, e1]

    @apply_channel
    def bit_phase_flip(self, p, which_qubit):
        r"""添加比特相位反转信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \sqrt{1 - p} I,
            E_1 = \sqrt{p} Y.

        Args:
            p (float): 发生 bit phase flip 的概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1857
            cir.cnot([0, 1])
Q
Quleaf 已提交
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
            cir.bit_phase_flip(p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[ 0.45+0.j  0.  +0.j  0.  +0.j  0.45+0.j]
             [ 0.  +0.j  0.05+0.j -0.05+0.j  0.  +0.j]
             [ 0.  +0.j -0.05+0.j  0.05+0.j  0.  +0.j]
             [ 0.45+0.j  0.  +0.j  0.  +0.j  0.45+0.j]]
        """
        assert 0 <= p <= 1, 'the probability p of a bit phase flip should be in range [0, 1]'

        e0 = paddle.to_tensor([[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]], dtype='complex128')
        e1 = paddle.to_tensor([[0, -1j * np.sqrt(p)], [1j * np.sqrt(p), 0]], dtype='complex128')

        return [e0, e1]

    @apply_channel
    def depolarizing(self, p, which_qubit):
        r"""添加去极化信道。

        其 Kraus 算符为:

        .. math::

            E_0 = \sqrt{1-p} I,
            E_1 = \sqrt{p/3} X,
            E_2 = \sqrt{p/3} Y,
            E_3 = \sqrt{p/3} Z.

        Args:
            p (float): depolarizing 信道的参数,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 0.1
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1902
            cir.cnot([0, 1])
Q
Quleaf 已提交
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
            cir.depolarizing(p, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.46666667+0.j 0.        +0.j 0.        +0.j 0.43333333+0.j]
             [0.        +0.j 0.03333333+0.j 0.        +0.j 0.        +0.j]
             [0.        +0.j 0.        +0.j 0.03333333+0.j 0.        +0.j]
             [0.43333333+0.j 0.        +0.j 0.        +0.j 0.46666667+0.j]]
        """
        assert 0 <= p <= 1, 'the parameter p should be in range [0, 1]'

        e0 = paddle.to_tensor([[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]], dtype='complex128')
        e1 = paddle.to_tensor([[0, np.sqrt(p/3)], [np.sqrt(p/3), 0]], dtype='complex128')
        e2 = paddle.to_tensor([[0, -1j * np.sqrt(p/3)], [1j * np.sqrt(p/3), 0]], dtype='complex128')
        e3 = paddle.to_tensor([[np.sqrt(p/3), 0], [0, -np.sqrt(p/3)]], dtype='complex128')

        return [e0, e1, e2, e3]

    @apply_channel
    def pauli_channel(self, p_x, p_y, p_z, which_qubit):
        r"""添加泡利信道。

        Args:
            p_x (float): 泡利矩阵 X 的对应概率,其值应该在 :math:`[0, 1]` 区间内
            p_y (float): 泡利矩阵 Y 的对应概率,其值应该在 :math:`[0, 1]` 区间内
            p_z (float): 泡利矩阵 Z 的对应概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        Note:
            三个输入的概率加起来需要小于等于 1。

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            p_x = 0.1
            p_y = 0.2
            p_z = 0.3
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
1947
            cir.cnot([0, 1])
Q
Quleaf 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
            cir.pauli_channel(p_x, p_y, p_z, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[ 0.35+0.j  0.  +0.j  0.  +0.j  0.05+0.j]
             [ 0.  +0.j  0.15+0.j -0.05+0.j  0.  +0.j]
             [ 0.  +0.j -0.05+0.j  0.15+0.j  0.  +0.j]
             [ 0.05+0.j  0.  +0.j  0.  +0.j  0.35+0.j]]
        """
        prob_list = [p_x, p_y, p_z]
        assert sum(prob_list) <= 1, 'the sum of probabilities should be smaller than or equal to 1 '
        X = np.array([[0, 1], [1, 0]], dtype='complex128')
        Y = np.array([[0, -1j], [1j, 0]], dtype='complex128')
        Z = np.array([[1, 0], [0, -1]], dtype='complex128')
        I = np.array([[1, 0], [0, 1]], dtype='complex128')

        op_list = [X, Y, Z]
        for i, prob in enumerate(prob_list):
            assert 0 <= prob <= 1, 'the parameter p' + str(i + 1) + ' should be in range [0, 1]'
            op_list[i] = paddle.to_tensor(np.sqrt(prob_list[i]) * op_list[i])
        op_list.append(paddle.to_tensor(np.sqrt(1 - sum(prob_list)) * I))

        return op_list

Q
Quleaf 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
    @apply_channel
    def reset(self, p, q, which_qubit):
        r"""添加重置信道。有 p 的概率将量子态重置为 :math:`|0\rangle` 并有 q 的概率重置为 :math:`|1\rangle`。
        
        其 Kraus 算符为:
        
        .. math::
        
            E_0 = \begin{bmatrix} \sqrt{p} & 0 \\ 0 & 0 \end{bmatrix},
            E_1 = \begin{bmatrix} 0 & \sqrt{p} \\ 0 & 0 \end{bmatrix},\\
            E_2 = \begin{bmatrix} 0 & 0 \\ \sqrt{q} & 0 \end{bmatrix},
            E_3 = \begin{bmatrix} 0 & 0 \\ 0 & \sqrt{q} \end{bmatrix},\\
            E_4 = \sqrt{1-p-q} I.
            
        Args:
            p (float): 重置为 :math:`|0\rangle`的概率,其值应该在 :math:`[0, 1]` 区间内
            q (float): 重置为 :math:`|1\rangle`的概率,其值应该在 :math:`[0, 1]` 区间内
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
        
        Note:
            两个输入的概率加起来需要小于等于 1。
        
        代码示例:
        
        .. code-block:: python
        
            from paddle_quantum.circuit import UAnsatz
            N = 2
            p = 1
            q = 0
            cir = UAnsatz(N)
            cir.h(0)
            cir.cnot([0, 1])
            cir.reset(p, q, 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())
            
        ::
        
            [[0.5+0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0.5+0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]]
        """
        assert p + q <= 1, 'the sum of probabilities should be smaller than or equal to 1 '
        
        e0 = paddle.to_tensor([[np.sqrt(p), 0], [0, 0]], dtype='complex128')
        e1 = paddle.to_tensor([[0, np.sqrt(p)], [0, 0]], dtype='complex128')
        e2 = paddle.to_tensor([[0, 0], [np.sqrt(q), 0]], dtype='complex128')
        e3 = paddle.to_tensor([[0, 0], [0, np.sqrt(q)]], dtype='complex128')
        e4 = paddle.to_tensor([[np.sqrt(1 - (p + q)), 0], [0, np.sqrt(1 - (p + q))]], dtype='complex128')
        
        return [e0, e1, e2, e3, e4]
        
    @apply_channel
    def thermal_relaxation(self, t1, t2, time, which_qubit):
        r"""添加热弛豫信道,模拟超导硬件上的 T1 和 T2 混合过程。

        Args:
            t1 (float): :math:`T_1` 过程的弛豫时间常数,单位是微秒
            t2 (float): :math:`T_2` 过程的弛豫时间常数,单位是微秒
            time (float): 弛豫过程中量子门的执行时间,单位是纳秒
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        Note:
            时间常数必须满足 :math:`T_2 \le T_1`,参考文献 https://arxiv.org/abs/2101.02109

        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz
            N = 2
            t1 = 30
            t2 = 20
            tg = 200
            cir = UAnsatz(N)
            cir.h(0)
            cir.cnot([0, 1])
            cir.thermal_relaxation(t1, t2, tg, 0)
            cir.thermal_relaxation(t1, t2, tg, 1)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.5   +0.j 0.    +0.j 0.    +0.j 0.4901+0.j]
             [0.    +0.j 0.0033+0.j 0.    +0.j 0.    +0.j]
             [0.    +0.j 0.    +0.j 0.0033+0.j 0.    +0.j]
             [0.4901+0.j 0.    +0.j 0.    +0.j 0.4934+0.j]]

        """
        assert 0 <= t2 <= t1, 'Relaxation time constants are not valid as 0 <= T2 <= T1!'
        assert 0 <= time, 'Invalid gate time!'
        
        # Change time scale
        time = time / 1000
        # Probability of resetting the state to |0>
        p_reset = 1 - np.exp(-time / t1)          
        # Probability of phase flip
        p_z = (1 - p_reset) * (1 - np.exp(-time / t2) * np.exp(time / t1)) / 2 
        # Probability of identity
        p_i = 1- p_reset - p_z
        
        e0 = paddle.to_tensor([[np.sqrt(p_i), 0], [0, np.sqrt(p_i)]], dtype='complex128')
        e1 = paddle.to_tensor([[np.sqrt(p_z), 0], [0, -np.sqrt(p_z)]], dtype='complex128')
        e2 = paddle.to_tensor([[np.sqrt(p_reset), 0], [0, 0]], dtype='complex128')
        e3 = paddle.to_tensor([[0, np.sqrt(p_reset)], [0, 0]], dtype='complex128')
        
        return [e0, e1, e2, e3]
        
Q
Quleaf 已提交
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    @apply_channel
    def customized_channel(self, ops, which_qubit):
        r"""添加自定义的量子信道。

        Args:
            ops (list): 表示信道的 Kraus 算符的列表
            which_qubit (int): 该信道作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            N = 2
            k1 = paddle.to_tensor([[1, 0], [0, 0]], dtype='complex128')
            k2 = paddle.to_tensor([[0, 0], [0, 1]], dtype='complex128')
            cir = UAnsatz(N)
            cir.h(0)
Q
Quleaf 已提交
2104
            cir.cnot([0, 1])
Q
Quleaf 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
            cir.customized_channel([k1, k2], 0)
            final_state = cir.run_density_matrix()
            print(final_state.numpy())

        ::

            [[0.5+0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
             [0. +0.j 0. +0.j 0. +0.j 0.5+0.j]]
        """
        completeness = paddle.to_tensor([[0, 0], [0, 0]], dtype='complex128')
        for op in ops:
            assert isinstance(op, paddle.Tensor), 'The input operators should be Tensors.'
            assert op.shape == [2, 2], 'The shape of each operator should be [2, 2].'
            assert op.dtype.name == 'COMPLEX128', 'The dtype of each operator should be COMPLEX128.'
            completeness += matmul(dagger(op), op)
        assert np.allclose(completeness.numpy(), np.eye(2, dtype='complex128')), 'Kraus operators should satisfy completeness.'

        return ops

Q
Quleaf 已提交
2126

Q
Quleaf 已提交
2127
def _local_H_prob(cir, hamiltonian, shots=1024):
Q
Quleaf 已提交
2128
    r"""
Q
Quleaf 已提交
2129
    构造出 Pauli 测量电路并测量 ancilla,处理实验结果来得到 ``H`` (只有一项)期望值的实验测量值。
Q
Quleaf 已提交
2130 2131 2132 2133 2134 2135

    Note:
        这是内部函数,你并不需要直接调用到该函数。
    """
    # Add one ancilla, which we later measure and process the result
    new_cir = UAnsatz(cir.n + 1)
Q
Quleaf 已提交
2136
    input_state = paddle.kron(cir.run_state_vector(store_state=False), init_state_gen(1))
Q
Quleaf 已提交
2137
    # Used in fixed Rz gate
Q
Quleaf 已提交
2138
    _theta = paddle.to_tensor(np.array([-np.pi / 2]))
Q
Quleaf 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171

    op_list = hamiltonian.split(',')
    # Set up pauli measurement circuit
    for op in op_list:
        element = op[0]
        index = int(op[1:])
        if element == 'x':
            new_cir.h(index)
            new_cir.cnot([index, cir.n])
        elif element == 'z':
            new_cir.cnot([index, cir.n])
        elif element == 'y':
            new_cir.rz(_theta, index)
            new_cir.h(index)
            new_cir.cnot([index, cir.n])

    new_cir.run_state_vector(input_state)
    prob_result = new_cir.measure(shots=shots, which_qubits=[cir.n])
    if shots > 0:
        if len(prob_result) == 1:
            if '0' in prob_result:
                result = (prob_result['0']) / shots
            else:
                result = (prob_result['1']) / shots
        else:
            result = (prob_result['0'] - prob_result['1']) / shots
    else:
        result = (prob_result['0'] - prob_result['1'])

    return result


def H_prob(cir, H, shots=1024):
Q
Quleaf 已提交
2172 2173
    r"""构造 Pauli 测量电路并测量关于 H 的期望值。

Q
Quleaf 已提交
2174
    Args:
Q
Quleaf 已提交
2175
        cir (UAnsatz): UAnsatz 的一个实例化对象
Q
Quleaf 已提交
2176
        H (list): 记录哈密顿量信息的列表
Q
Quleaf 已提交
2177 2178
        shots (int, optional): 默认为 1024,表示测量次数;若为 0,则表示返回测量期望值的精确值,即测量无穷次后的期望值

Q
Quleaf 已提交
2179 2180
    Returns:
        float: 测量得到的H的期望值
Q
Quleaf 已提交
2181
    
Q
Quleaf 已提交
2182 2183 2184
    代码示例:

    .. code-block:: python
Q
Quleaf 已提交
2185
        
Q
Quleaf 已提交
2186
        import numpy as np
Q
Quleaf 已提交
2187
        import paddle
Q
Quleaf 已提交
2188 2189 2190 2191
        from paddle_quantum.circuit import UAnsatz, H_prob
        n = 4
        experiment_shots = 2**10
        H_info = [[0.1, 'x2'], [0.3, 'y1,z3']]
Q
Quleaf 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201

        theta = paddle.to_tensor(np.ones(3))
        cir = UAnsatz(n)
        cir.rx(theta[0], 0)
        cir.ry(theta[1], 1)
        cir.rz(theta[2], 1)
        result_1 = H_prob(cir, H_info, shots = experiment_shots)
        result_2 = H_prob(cir, H_info, shots = 0)
        print(f'The expectation value obtained by {experiment_shots} measurements is {result_1}')
        print(f'The accurate expectation value of H is {result_2}')
Q
Quleaf 已提交
2202 2203 2204

    ::

Q
Quleaf 已提交
2205
        The expectation value obtained by 1024 measurements is 0.2177734375
Q
Quleaf 已提交
2206
        The accurate expectation value of H is 0.21242202548207134
Q
Quleaf 已提交
2207 2208 2209
    """
    expval = 0
    for term in H:
Q
Quleaf 已提交
2210
        expval += term[0] * _local_H_prob(cir, term[1], shots=shots)
Q
Quleaf 已提交
2211
    return expval