circuit.py 153.1 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
import copy
Q
Quleaf 已提交
17
import math
Q
Quleaf 已提交
18 19
import re
import matplotlib.pyplot as plt
Q
Quleaf 已提交
20 21
from functools import reduce
from collections import defaultdict
Q
Quleaf 已提交
22
import numpy as np
Q
Quleaf 已提交
23
import paddle
Q
Quleaf 已提交
24 25 26 27
from paddle_quantum.simulator import transfer_state, init_state_gen, measure_state
from paddle import imag, real, reshape, kron, matmul, trace
from paddle_quantum.utils import partial_trace, dagger, pauli_str_to_matrix
from paddle_quantum import shadow
Q
Quleaf 已提交
28
from paddle_quantum.intrinsic import *
Y
yangguohao 已提交
29
from paddle_quantum.state import density_op,vec
Q
Quleaf 已提交
30 31 32

__all__ = [
    "UAnsatz",
Q
Quleaf 已提交
33
    "swap_test"
Q
Quleaf 已提交
34 35 36
]


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

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

Q
Quleaf 已提交
42
    Attributes:
Q
Quleaf 已提交
43
        n (int): 该电路的量子比特数
Q
Quleaf 已提交
44 45
    """

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

Q
Quleaf 已提交
49
        Args:
Q
Quleaf 已提交
50
            n (int): 该电路的量子比特数
Q
Quleaf 已提交
51 52
        """
        self.n = n
Q
Quleaf 已提交
53
        self.__has_channel = False
Q
Quleaf 已提交
54
        self.__state = None
Q
Quleaf 已提交
55 56 57 58 59
        self.__run_mode = ''
        # Record parameters in the circuit
        self.__param = [paddle.to_tensor(np.array([0.0])),
                        paddle.to_tensor(np.array([math.pi / 2])), paddle.to_tensor(np.array([-math.pi / 2])),
                        paddle.to_tensor(np.array([math.pi / 4])), paddle.to_tensor(np.array([-math.pi / 4]))]
Q
Quleaf 已提交
60 61
        # Record history of adding gates to the circuit
        self.__history = []
Y
yangguohao 已提交
62

Y
yangguohao 已提交
63 64 65 66 67 68 69
    def expand(self,new_n):
        """
        为原来的量子电路进行比特数扩展

        Args:
            new_n(int):扩展后的量子比特数
        """
Y
yangguohao 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83
        assert new_n>=self.n,'扩展后量子比特数要大于原量子比特数'
        diff = new_n-self.n
        dim = 2**diff
        if self.__state is not None:
            if self.__run_mode=='density_matrix':
                shape = (dim,dim)
                _state = paddle.to_tensor(density_op(diff))
            elif self.__run_mode=='state_vector':
                shape = (dim,)
                _state = paddle.to_tensor(vec(0,diff))
            
            _state= paddle.reshape(_state,shape)
            _state = kron(self.__state,_state)
            self.__state = _state
Y
yangguohao 已提交
84
        self.n = new_n
Q
QuLeaf 已提交
85

Q
Quleaf 已提交
86 87 88 89 90 91 92 93
    def __add__(self, cir):
        r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路

        Args:
            cir (UAnsatz): 拼接到现有电路上的电路
        
        Returns:
            UAnsatz: 拼接后的新电路
Q
Quleaf 已提交
94
        
Q
Quleaf 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        代码示例:

        .. code-block:: python

            from paddle_quantum.circuit import UAnsatz

            print('cir1: ')
            cir1 = UAnsatz(2)
            cir1.superposition_layer()
            print(cir1)

            print('cir2: ')
            cir2 = UAnsatz(2)
            cir2.cnot([0,1])
            print(cir2)

            print('cir3: ')
            cir3 = cir1 + cir2
            print(cir3)
        ::

            cir1: 
            --H--
                
            --H--
                
            cir2: 
            --*--
              |  
            --x--
                
            cir3: 
            --H----*--
                   |  
            --H----x--

        """
        assert self.n == cir.n, "two circuits does not have the same dimension"

        # Construct a new circuit that adds the two together
        cir_out = UAnsatz(self.n)
        cir_out.__param = copy.copy(self.__param)
        cir_out.__history = copy.copy(self.__history)
        cir_out._add_history(cir.__history, cir.__param)

        return cir_out

    def _get_history(self):
        r"""获取当前电路加门的历史

        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        return self.__history, self.__param

    def _add_history(self, histories, param):
        r"""往当前 UAnsatz 里直接添加历史

        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        if type(histories) is dict:
            histories = [histories]

        for history_ele in histories:
            param_idx = history_ele['theta']
            if param_idx is None:
                self.__history.append(copy.copy(history_ele))
            else:
                new_param_idx = []
                curr_idx = len(self.__param)
                for idx in param_idx:
                    self.__param.append(param[idx])
                    new_param_idx.append(curr_idx)
                    curr_idx += 1
                self.__history.append({'gate': history_ele['gate'],
                                       'which_qubits': history_ele['which_qubits'],
                                       'theta': new_param_idx})

    def get_run_mode(self):
        r"""获取当前电路的运行模式。

        Returns:
            string: 当前电路的运行模式,态矢量或者是密度矩阵

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            import numpy as np

            cir = UAnsatz(5)
            cir.superposition_layer()
            cir.run_state_vector()

            print(cir.get_run_mode())

        ::

            state_vector
        """
        return self.__run_mode

    def get_state(self):
        r"""获取当前电路运行后的态

        Returns:
            paddle.Tensor: 当前电路运行后的态

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            import numpy as np

            cir = UAnsatz(5)
            cir.superposition_layer()
            cir.run_state_vector()

            print(cir.get_state())

        ::

            Tensor(shape=[4], dtype=complex128, place=CPUPlace, stop_gradient=True,
                   [(0.4999999999999999+0j), (0.4999999999999999+0j), (0.4999999999999999+0j), (0.4999999999999999+0j)])
        """
        return self.__state

Q
Quleaf 已提交
227 228
    def _count_history(self):
        r"""calculate how many blocks needed for printing
Q
Quleaf 已提交
229

Q
Quleaf 已提交
230
        Note:
Q
Quleaf 已提交
231
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
232 233 234 235 236 237 238 239 240 241 242
        """
        # 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
Q
Quleaf 已提交
243

Q
Quleaf 已提交
244 245
        for current_gate in history:
            # Single-qubit gates with no params to print
Q
Quleaf 已提交
246 247
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u', 'sdg', 'tdg'}:
                curr_qubit = current_gate['which_qubits'][0]
Q
Quleaf 已提交
248 249 250 251 252 253 254
                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
Q
Quleaf 已提交
255 256
            elif current_gate['gate'] in {'rx', 'ry', 'rz'}:
                curr_qubit = current_gate['which_qubits'][0]
Q
Quleaf 已提交
257 258 259 260 261 262 263
                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]
Q
Quleaf 已提交
264 265 266 267 268
            # Two-qubit gates or Three-qubit gates
            elif current_gate['gate'] in {'CNOT', 'SWAP', 'RXX_gate', 'RYY_gate', 'RZZ_gate', 'MS_gate', 'cy', 'cz',
                                          'CU', 'crx', 'cry', 'crz'} or current_gate['gate'] in {'CSWAP', 'CCX'}:
                a = max(current_gate['which_qubits'])
                b = min(current_gate['which_qubits'])
Q
Quleaf 已提交
269 270
                ind = max(qubit[b: a + 1])
                gate.append(ind)
Q
Quleaf 已提交
271 272
                if length[ind] < 13 and current_gate['gate'] in {'RXX_gate', 'RYY_gate', 'RZZ_gate', 'crx', 'cry',
                                                                 'crz'}:
Q
Quleaf 已提交
273 274 275 276 277 278
                    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
Q
Quleaf 已提交
279

Q
Quleaf 已提交
280
        return length, gate
Q
Quleaf 已提交
281

Q
Quleaf 已提交
282 283
    def __str__(self):
        r"""实现画电路的功能
Q
Quleaf 已提交
284

Q
Quleaf 已提交
285 286
        Returns:
            string: 用来print的字符串
Q
Quleaf 已提交
287

Q
Quleaf 已提交
288 289 290 291 292 293 294
        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            import numpy as np
Q
Quleaf 已提交
295

Q
Quleaf 已提交
296 297 298 299
            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)
Q
Quleaf 已提交
300

Q
Quleaf 已提交
301 302
            print(cir)
        ::
Q
Quleaf 已提交
303

Q
Quleaf 已提交
304
            The printed circuit is:
Q
Quleaf 已提交
305

Q
Quleaf 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318
            --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
Q
Quleaf 已提交
319
        # Ignore the unused section
Q
Quleaf 已提交
320
        total_length = sum(length) - 5
Q
Quleaf 已提交
321

Q
Quleaf 已提交
322 323 324
        print_list = [['-' if i % 2 == 0 else ' '] * total_length for i in range(n * 2)]

        for i, current_gate in enumerate(history):
Q
Quleaf 已提交
325
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u'}:
Q
Quleaf 已提交
326 327 328
                # Calculate starting position ind of current gate
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
329 330 331 332 333 334 335 336 337 338 339 340
                print_list[current_gate['which_qubits'][0] * 2][ind + length[sec] // 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'sdg'}:
                sec = gate[i]
                ind = sum(length[:sec])
                print_list[current_gate['which_qubits'][0] * 2][
                    ind + length[sec] // 2 - 1: ind + length[sec] // 2 + 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'tdg'}:
                sec = gate[i]
                ind = sum(length[:sec])
                print_list[current_gate['which_qubits'][0] * 2][
                    ind + length[sec] // 2 - 1: ind + length[sec] // 2 + 2] = current_gate['gate'].upper()
            elif current_gate['gate'] in {'rx', 'ry', 'rz'}:
Q
Quleaf 已提交
341 342
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
343 344
                line = current_gate['which_qubits'][0] * 2
                param = self.__param[current_gate['theta'][2 if current_gate['gate'] == 'rz' else 0]]
Q
Quleaf 已提交
345
                print_list[line][ind + 2] = 'R'
Q
Quleaf 已提交
346
                print_list[line][ind + 3] = current_gate['gate'][1]
Q
Quleaf 已提交
347 348 349
                print_list[line][ind + 4] = '('
                print_list[line][ind + 5: ind + 10] = format(float(param.numpy()), '.3f')[:5]
                print_list[line][ind + 10] = ')'
Q
Quleaf 已提交
350 351 352
            # Two-qubit gates
            elif current_gate['gate'] in {'CNOT', 'SWAP', 'RXX_gate', 'RYY_gate', 'RZZ_gate', 'MS_gate', 'cz', 'cy',
                                          'CU', 'crx', 'cry', 'crz'}:
Q
Quleaf 已提交
353 354
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
355 356 357 358 359 360 361 362
                cqubit = current_gate['which_qubits'][0]
                tqubit = current_gate['which_qubits'][1]
                if current_gate['gate'] in {'CNOT', 'SWAP', 'cy', 'cz', 'CU'}:
                    print_list[cqubit * 2][ind + length[sec] // 2] = \
                        '*' if current_gate['gate'] in {'CNOT', 'cy', 'cz', 'CU'} else 'x'
                    print_list[tqubit * 2][ind + length[sec] // 2] = \
                        'x' if current_gate['gate'] in {'SWAP', 'CNOT'} else current_gate['gate'][1]
                elif current_gate['gate'] == 'MS_gate':
Q
Quleaf 已提交
363 364 365 366
                    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'
Q
Quleaf 已提交
367 368
                elif current_gate['gate'] in {'RXX_gate', 'RYY_gate', 'RZZ_gate'}:
                    param = self.__param[current_gate['theta'][0]]
Q
Quleaf 已提交
369 370
                    for line in {cqubit * 2, tqubit * 2}:
                        print_list[line][ind + 2] = 'R'
Q
Quleaf 已提交
371
                        print_list[line][ind + 3: ind + 5] = current_gate['gate'][1:3].lower()
Q
Quleaf 已提交
372 373 374
                        print_list[line][ind + 5] = '('
                        print_list[line][ind + 6: ind + 10] = format(float(param.numpy()), '.2f')[:4]
                        print_list[line][ind + 10] = ')'
Q
Quleaf 已提交
375 376 377 378 379 380 381 382
                elif current_gate['gate'] in {'crx', 'cry', 'crz'}:
                    param = self.__param[current_gate['theta'][2 if current_gate['gate'] == 'crz' else 0]]
                    print_list[cqubit * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit * 2][ind + 2] = 'R'
                    print_list[tqubit * 2][ind + 3] = current_gate['gate'][2]
                    print_list[tqubit * 2][ind + 4] = '('
                    print_list[tqubit * 2][ind + 5: ind + 10] = format(float(param.numpy()), '.3f')[:5]
                    print_list[tqubit * 2][ind + 10] = ')'
Q
Quleaf 已提交
383 384 385 386
                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] = '|'
Q
Quleaf 已提交
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
            # Three-qubit gates
            elif current_gate['gate'] in {'CSWAP'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit = current_gate['which_qubits'][0]
                tqubit1 = current_gate['which_qubits'][1]
                tqubit2 = current_gate['which_qubits'][2]
                start_line = min(current_gate['which_qubits'])
                end_line = max(current_gate['which_qubits'])
                for k in range(start_line * 2 + 1, end_line * 2):
                    print_list[k][ind + length[sec] // 2] = '|'
                if current_gate['gate'] in {'CSWAP'}:
                    print_list[cqubit * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit1 * 2][ind + length[sec] // 2] = 'x'
                    print_list[tqubit2 * 2][ind + length[sec] // 2] = 'x'
            elif current_gate['gate'] in {'CCX'}:
                sec = gate[i]
                ind = sum(length[:sec])
                cqubit1 = current_gate['which_qubits'][0]
                cqubit2 = current_gate['which_qubits'][1]
                tqubit = current_gate['which_qubits'][2]
                start_line = min(current_gate['which_qubits'])
                end_line = max(current_gate['which_qubits'])
                for k in range(start_line * 2 + 1, end_line * 2):
                    print_list[k][ind + length[sec] // 2] = '|'
                if current_gate['gate'] in {'CCX'}:
                    print_list[cqubit1 * 2][ind + length[sec] // 2] = '*'
                    print_list[cqubit2 * 2][ind + length[sec] // 2] = '*'
                    print_list[tqubit * 2][ind + length[sec] // 2] = 'X'
Q
Quleaf 已提交
416 417 418 419 420

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

        return return_str
Q
Quleaf 已提交
421

Q
Quleaf 已提交
422
    def run_state_vector(self, input_state=None, store_state=True):
Q
Quleaf 已提交
423 424 425 426
        r"""运行当前的量子电路,输入输出的形式为态矢量。

        Warning:
            该方法只能运行无噪声的电路。
Q
Quleaf 已提交
427

Q
Quleaf 已提交
428
        Args:
Q
Quleaf 已提交
429
            input_state (Tensor, optional): 输入的态矢量,默认为 :math:`|00...0\rangle`
Q
Quleaf 已提交
430
            store_state (Bool, optional): 是否存储输出的态矢量,默认为 ``True`` ,即存储
Q
Quleaf 已提交
431

Q
Quleaf 已提交
432
        Returns:
Q
Quleaf 已提交
433
            Tensor: 量子电路输出的态矢量
Q
Quleaf 已提交
434

Q
Quleaf 已提交
435
        代码示例:
Q
Quleaf 已提交
436

Q
Quleaf 已提交
437
        .. code-block:: python
Q
Quleaf 已提交
438

Q
Quleaf 已提交
439
            import numpy as np
Q
Quleaf 已提交
440
            import paddle
Q
Quleaf 已提交
441
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
442
            from paddle_quantum.state import vec
Q
Quleaf 已提交
443 444
            n = 2
            theta = np.ones(3)
Q
Quleaf 已提交
445

Q
Quleaf 已提交
446
            input_state = paddle.to_tensor(vec(0, n))
Q
Quleaf 已提交
447 448 449 450 451 452 453
            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 已提交
454

Q
Quleaf 已提交
455
        ::
Q
Quleaf 已提交
456

Q
Quleaf 已提交
457
            The output state vector is [[0.62054458+0.j 0.18316521+0.28526291j 0.62054458+0.j 0.18316521+0.28526291j]]
Q
Quleaf 已提交
458
        """
Q
Quleaf 已提交
459
        # Throw a warning when cir has channel
Q
Quleaf 已提交
460
        if self.__has_channel:
Q
Quleaf 已提交
461
            warnings.warn('The noiseless circuit will be run.', RuntimeWarning)
Q
Quleaf 已提交
462 463
        state = init_state_gen(self.n, 0) if input_state is None else input_state
        old_shape = state.shape
Q
Quleaf 已提交
464 465
        assert reduce(lambda x, y: x * y, old_shape) == 2 ** self.n, \
            'The length of the input vector is not right'
Q
Quleaf 已提交
466
        state = reshape(state, (2 ** self.n,))
Q
Quleaf 已提交
467

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

Q
Quleaf 已提交
472
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
473 474 475 476

        if store_state:
            self.__state = state
            # Add info about which function user called
Q
Quleaf 已提交
477
            self.__run_mode = 'state_vector'
Q
Quleaf 已提交
478

Q
Quleaf 已提交
479
        return reshape(state, old_shape)
Q
Quleaf 已提交
480 481

    def run_density_matrix(self, input_state=None, store_state=True):
Q
Quleaf 已提交
482
        r"""运行当前的量子电路,输入输出的形式为密度矩阵。
Q
Quleaf 已提交
483

Q
Quleaf 已提交
484
        Args:
Q
Quleaf 已提交
485
            input_state (Tensor, optional): 输入的密度矩阵,默认为 :math:`|00...0\rangle \langle00...0|`
Q
Quleaf 已提交
486
            store_state (bool, optional): 是否存储输出的密度矩阵,默认为 ``True`` ,即存储
Q
Quleaf 已提交
487

Q
Quleaf 已提交
488
        Returns:
Q
Quleaf 已提交
489
            Tensor: 量子电路输出的密度矩阵
Q
Quleaf 已提交
490 491 492 493

        代码示例:

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

Q
Quleaf 已提交
495
            import numpy as np
Q
Quleaf 已提交
496
            import paddle
Q
Quleaf 已提交
497
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
498
            from paddle_quantum.state import density_op
Q
Quleaf 已提交
499 500
            n = 1
            theta = np.ones(3)
Q
Quleaf 已提交
501 502 503 504 505 506 507 508 509

            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 已提交
510 511 512

        ::

Q
Quleaf 已提交
513
            The output density matrix is
Q
Quleaf 已提交
514 515
            [[0.64596329+0.j         0.47686058+0.03603751j]
            [0.47686058-0.03603751j 0.35403671+0.j        ]]
Q
Quleaf 已提交
516
        """
Q
Quleaf 已提交
517
        state = paddle.to_tensor(density_op(self.n)) if input_state is None else input_state
Q
Quleaf 已提交
518 519
        assert state.shape == [2 ** self.n, 2 ** self.n], \
            "The dimension is not right"
Q
Quleaf 已提交
520

Q
Quleaf 已提交
521
        if not self.__has_channel:
Q
Quleaf 已提交
522 523 524 525 526 527 528 529 530 531
            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
Q
Quleaf 已提交
532
            i = 0
Q
Quleaf 已提交
533
            for i, history_ele in enumerate(self.__history):
Q
Quleaf 已提交
534
                if history_ele['gate'] == 'channel':
Q
Quleaf 已提交
535
                    # Combine preceding unitary operations
Q
Quleaf 已提交
536
                    unitary = transfer_by_history(identity, self.__history[u_start:i], self.__param)
Q
Quleaf 已提交
537
                    sub_state = paddle.zeros(shape, dtype='complex128')
Q
Quleaf 已提交
538
                    # Sum all the terms corresponding to different Kraus operators
Q
Quleaf 已提交
539 540 541
                    for op in history_ele['operators']:
                        pseudo_u = reshape(transfer_state(unitary, op, history_ele['which_qubits']), shape)
                        sub_state += matmul(pseudo_u, matmul(state, dagger(pseudo_u)))
Q
Quleaf 已提交
542 543 544
                    state = sub_state
                    u_start = i + 1
            # Apply unitary operations left
Q
Quleaf 已提交
545
            unitary = reshape(transfer_by_history(identity, self.__history[u_start:(i + 1)], self.__param), shape)
Q
Quleaf 已提交
546
            state = matmul(unitary, matmul(state, dagger(unitary)))
Q
Quleaf 已提交
547

Q
Quleaf 已提交
548 549 550
        if store_state:
            self.__state = state
            # Add info about which function user called
Q
Quleaf 已提交
551
            self.__run_mode = 'density_matrix'
Q
Quleaf 已提交
552 553 554

        return state

Q
Quleaf 已提交
555 556 557 558 559 560
    def reset_state(self, state, which_qubits):
        r"""对当前电路中的量子态的部分量子比特进行重置。

        Args:
            state (paddle.Tensor): 输入的量子态,表示要把选定的量子比特重置为该量子态
            which_qubits (list): 需要被重置的量子比特编号
Q
Quleaf 已提交
561 562 563

        Returns:
            paddle.Tensor: 重置后的量子态
Q
Quleaf 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
        """
        qubits_list = which_qubits
        n = self.n
        m = len(qubits_list)
        assert max(qubits_list) <= n, "qubit index out of range"

        origin_seq = list(range(0, n))
        target_seq = [idx for idx in origin_seq if idx not in qubits_list]
        target_seq = qubits_list + target_seq

        swapped = [False] * n
        swap_list = list()
        for idx in range(0, n):
            if not swapped[idx]:
                next_idx = idx
                swapped[next_idx] = True
                while not swapped[target_seq[next_idx]]:
                    swapped[target_seq[next_idx]] = True
                    swap_list.append((next_idx, target_seq[next_idx]))
                    next_idx = target_seq[next_idx]

        cir0 = UAnsatz(n)
        for a, b in swap_list:
            cir0.swap([a, b])

        cir1 = UAnsatz(n)
        swap_list.reverse()
        for a, b in swap_list:
            cir1.swap([a, b])

        _state = self.__state

        if self.__run_mode == 'state_vector':
            raise NotImplementedError('This feature is not implemented yet.')
        elif self.__run_mode == 'density_matrix':
            _state = cir0.run_density_matrix(_state)
            _state = partial_trace(_state, 2 ** m, 2 ** (n - m), 1)
            _state = kron(state, _state)
            _state = cir1.run_density_matrix(_state)
        else:
            raise ValueError("Can't recognize the mode of quantum state.")
        self.__state = _state
Q
Quleaf 已提交
606
        return _state
Q
Quleaf 已提交
607

Q
Quleaf 已提交
608 609
    @property
    def U(self):
Q
Quleaf 已提交
610 611 612 613
        r"""量子电路的酉矩阵形式。

        Warning:
            该属性只限于无噪声的电路。
Q
Quleaf 已提交
614

Q
Quleaf 已提交
615
        Returns:
Q
Quleaf 已提交
616
            Tensor: 当前电路的酉矩阵表示
Q
Quleaf 已提交
617 618 619 620

        代码示例:

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

Q
Quleaf 已提交
622
            import paddle
Q
Quleaf 已提交
623 624
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
625 626 627 628 629
            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 已提交
630 631 632

        ::

Q
Quleaf 已提交
633
            The unitary matrix of the circuit for Bell state preparation is
Q
Quleaf 已提交
634 635 636 637
            [[ 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 已提交
638
        """
Q
Quleaf 已提交
639
        # Throw a warning when cir has channel
Q
Quleaf 已提交
640
        if self.__has_channel:
Q
Quleaf 已提交
641 642 643 644 645
            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 已提交
646
        state = paddle.cast(state, 'complex128')
Q
Quleaf 已提交
647
        state = reshape(state, [num_ele])
Q
Quleaf 已提交
648
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
649

Q
Quleaf 已提交
650
        return reshape(state, shape)
Q
Quleaf 已提交
651

Q
Quleaf 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    def __input_which_qubits_check(self, which_qubits):
        r"""实现3个功能:

        1. 检查 which_qubits 长度有无超过 qubits 的个数, (应小于等于qubits)
        2. 检查 which_qubits 有无重复的值
        3. 检查 which_qubits 的每个值有无超过量子 qubits 的序号, (应小于qubits,从 0 开始编号)

        Args:
            which_qubits (list) : 用于编码的量子比特

        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        which_qubits_len = len(which_qubits)
        set_list = set(which_qubits)
        assert which_qubits_len <= self.n, \
            "the length of which_qubit_list should less than the number of qubits"
        assert which_qubits_len == len(set_list), \
            "the which_qubits can not have duplicate elements"
        for qubit_idx in which_qubits:
            assert qubit_idx < self.n, \
                "the value of which_qubit_list should less than the number of qubits"

    def basis_encoding(self, x, which_qubits=None, invert=False):
Q
Quleaf 已提交
676 677 678 679 680 681 682
        r"""将输入的经典数据使用基态编码的方式编码成量子态。

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

        Args:
            x (Tensor): 待编码的向量
Q
Quleaf 已提交
683
            which_qubits (list): 用于编码的量子比特
Q
Quleaf 已提交
684 685 686 687
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
        x = paddle.flatten(x)
        x = paddle.cast(x, dtype="int32")
Q
Quleaf 已提交
688 689 690 691 692 693 694 695 696
        assert x.size <= self.n, \
            "the number of classical data should less than or equal to the number of qubits"
        if which_qubits is None:
            which_qubits = list(range(self.n))
        else:
            self.__input_which_qubits_check(which_qubits)
            assert x.size <= len(which_qubits), \
                "the number of classical data should less than or equal to the number of 'which_qubits'"

Q
Quleaf 已提交
697 698
        for idx, element in enumerate(x):
            if element:
Q
Quleaf 已提交
699
                self.x(which_qubits[idx])
Q
Quleaf 已提交
700

Q
Quleaf 已提交
701
    def amplitude_encoding(self, x, mode, which_qubits=None):
Q
Quleaf 已提交
702 703 704 705 706
        r"""将输入的经典数据使用振幅编码的方式编码成量子态。

        Args:
            x (Tensor): 待编码的向量
            mode (str): 生成的量子态的表示方式,``"state_vector"`` 代表态矢量表示, ``"density_matrix"`` 代表密度矩阵表示
Q
Quleaf 已提交
707
            which_qubits (list): 用于编码的量子比特
Q
Quleaf 已提交
708 709 710 711

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

Q
Quleaf 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 3
            built_in_amplitude_enc = UAnsatz(n)
            # 经典信息 x 需要是 Tensor 的形式
            x = paddle.to_tensor([0.3, 0.4, 0.5, 0.6])
            state = built_in_amplitude_enc.amplitude_encoding(x, 'state_vector', [0,2])
            print(state.numpy())

        ::

            [0.32349834+0.j 0.4313311 +0.j 0.        +0.j 0.        +0.j
            0.53916389+0.j 0.64699668+0.j 0.        +0.j 0.        +0.j]

Q
Quleaf 已提交
730
        """
Q
Quleaf 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        assert x.size <= 2 ** self.n, \
            "the number of classical data should less than or equal to the number of qubits"

        if which_qubits is None:
            which_qubits_len = math.ceil(math.log2(x.size))
            which_qubits = list(range(which_qubits_len))
        else:
            self.__input_which_qubits_check(which_qubits)
            which_qubits_len = len(which_qubits)
        assert x.size <= 2 ** which_qubits_len, \
            "the number of classical data should <= 2^(which_qubits)"
        assert x.size > 2 ** (which_qubits_len - 1), \
            "the number of classical data should >= 2^(which_qubits-1)"

        def calc_location(location_of_bits_list):
            r"""递归计算需要参与编码的量子态展开后的序号
            方式:全排列,递归计算

            Args:
                location_of_bits_list (list): 标识了指定 qubits 的序号值,如指定编码第3个qubit(序号2),
                    则它处在展开后的 2**(3-1)=4 位置上。

            Returns:
                list : 标识了将要参与编码的量子位展开后的序号
            """
            if len(location_of_bits_list) <= 1:
                result_list = [0, location_of_bits_list[0]]
            else:
                current_tmp = location_of_bits_list[0]
                inner_location_of_qubits_list = calc_location(location_of_bits_list[1:])
                current_list_len = len(inner_location_of_qubits_list)
                for each in range(current_list_len):
                    inner_location_of_qubits_list.append(inner_location_of_qubits_list[each] + current_tmp)
                result_list = inner_location_of_qubits_list

            return result_list

        def encoding_location_list(which_qubits):
            r"""计算每一个经典数据将要编码到量子态展开后的哪一个位置

            Args:
                which_qubits (list): 标识了参与编码的量子 qubits 的序号, 此参数与外部 which_qubits 参数应保持一致

            Returns:
                (list) : 将要参与编码的量子 qubits 展开后的序号,即位置序号
            """
            location_of_bits_list = []
            for each in range(len(which_qubits)):
                tmp = 2 ** (self.n - which_qubits[each] - 1)
                location_of_bits_list.append(tmp)
            result_list = calc_location(location_of_bits_list)

            return sorted(result_list)

        # Get the specific position of the code, denoted by sequence number (list)
        location_of_qubits_list = encoding_location_list(which_qubits)
        # Classical data preprocessing
Q
Quleaf 已提交
788 789
        x = paddle.flatten(x)
        length = paddle.norm(x, p=2)
Q
Quleaf 已提交
790
        # Normalization
Q
Quleaf 已提交
791
        x = paddle.divide(x, length)
Q
Quleaf 已提交
792 793 794 795 796 797 798
        # Create a quantum state with all zero amplitudes
        zero_tensor = paddle.zeros((2 ** self.n,), x.dtype)
        # The value of the encoded amplitude is filled into the specified qubits
        for i in range(len(x)):
            zero_tensor[location_of_qubits_list[i]] = x[i]
        # The quantum state that stores the result
        result_tensor = zero_tensor
Q
Quleaf 已提交
799
        if mode == "state_vector":
Q
Quleaf 已提交
800
            result_tensor = paddle.cast(result_tensor, dtype="complex128")
Q
Quleaf 已提交
801
        elif mode == "density_matrix":
Q
Quleaf 已提交
802 803
            result_tensor = paddle.reshape(result_tensor, (2 ** self.n, 1))
            result_tensor = matmul(result_tensor, dagger(result_tensor))
Q
Quleaf 已提交
804 805 806
        else:
            raise ValueError("the mode should be state_vector or density_matrix")

Q
Quleaf 已提交
807 808 809
        return result_tensor

    def angle_encoding(self, x, encoding_gate, which_qubits=None, invert=False):
Q
Quleaf 已提交
810 811 812 813 814
        r"""将输入的经典数据使用角度编码的方式进行编码。

        Args:
            x (Tensor): 待编码的向量
            encoding_gate (str): 编码要用的量子门,可以是 ``"rx"`` 、 ``"ry"`` 和 ``"rz"``
Q
Quleaf 已提交
815
            which_qubits (list): 用于编码的量子比特
Q
Quleaf 已提交
816 817
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
Q
Quleaf 已提交
818 819 820 821 822 823 824 825 826
        assert x.size <= self.n, \
            "the number of classical data should be equal to the number of qubits"
        if which_qubits is None:
            which_qubits = list(range(self.n))
        else:
            self.__input_which_qubits_check(which_qubits)
            assert x.size <= len(which_qubits), \
                "the number of classical data should less than or equal to the number of 'which_qubits'"

Q
Quleaf 已提交
827 828 829 830
        x = paddle.flatten(x)
        if invert:
            x = -x

Q
Quleaf 已提交
831
        def add_encoding_gate(theta, which, gate):
Q
Quleaf 已提交
832
            if gate == "rx":
Q
Quleaf 已提交
833
                self.rx(theta, which)
Q
Quleaf 已提交
834
            elif gate == "ry":
Q
Quleaf 已提交
835
                self.ry(theta, which)
Q
Quleaf 已提交
836
            elif gate == "rz":
Q
Quleaf 已提交
837
                self.rz(theta, which)
Q
Quleaf 已提交
838 839 840 841
            else:
                raise ValueError("the encoding_gate should be rx, ry, or rz")

        for idx, element in enumerate(x):
Q
Quleaf 已提交
842
            add_encoding_gate(element[0], which_qubits[idx], encoding_gate)
Q
Quleaf 已提交
843 844 845 846 847 848 849 850 851 852

    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`` ,即添加正常的编码电路
        """
Q
Quleaf 已提交
853 854
        assert x.size <= self.n, \
            "the number of classical data should be equal to the number of qubits"
Q
Quleaf 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867
        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))
Q
Quleaf 已提交
868
                    self.rz(-x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
869 870 871 872 873 874 875 876 877 878 879 880
                    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))
Q
Quleaf 已提交
881
                    self.rz(x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
882 883
                    self.cnot(list(item))

Q
Quleaf 已提交
884
    """
Q
Quleaf 已提交
885
    Common Gates
Q
Quleaf 已提交
886 887
    """

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

Q
Quleaf 已提交
891
        其矩阵形式为:
Q
Quleaf 已提交
892

Q
Quleaf 已提交
893
        .. math::
Q
Quleaf 已提交
894 895 896 897 898

            \begin{bmatrix}
                \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\
                -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2}
            \end{bmatrix}
Q
Quleaf 已提交
899

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

Q
Quleaf 已提交
904 905 906
        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
907
            import paddle
Q
Quleaf 已提交
908 909
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
910 911 912 913 914 915
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rx(theta[0], which_qubit)

Q
Quleaf 已提交
916
        """
Q
Quleaf 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        assert 0 <= which_qubit < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'rx', 'which_qubits': [which_qubit], 'theta': [curr_idx, 2, 1]})
        self.__param.append(theta)

    def crx(self, theta, which_qubit):
        r"""添加关于 x 轴的控制单量子比特旋转门。

        其矩阵形式为:

        .. math::

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

        Args:
            theta (Tensor): 旋转角度
            which_qubit (list): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            theta = paddle.to_tensor(theta)
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            which_qubit = [0, 1]
            cir.crx(theta[0], which_qubit)

        """
        assert 0 <= which_qubit[0] < self.n and 0 <= which_qubit[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubit[0] != which_qubit[1], \
            "the control qubit is the same as the target qubit"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'crx', 'which_qubits': which_qubit, 'theta': [curr_idx, 2, 1]})
        self.__param.append(theta)
Q
Quleaf 已提交
965 966

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

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

Q
Quleaf 已提交
971
        .. math::
Q
Quleaf 已提交
972 973 974 975 976

            \begin{bmatrix}
                \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\
                \sin\frac{\theta}{2} & \cos\frac{\theta}{2}
            \end{bmatrix}
Q
Quleaf 已提交
977 978

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

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

Q
Quleaf 已提交
984
            import numpy as np
Q
Quleaf 已提交
985
            import paddle
Q
Quleaf 已提交
986 987
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
988 989 990 991 992
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.ry(theta[0], which_qubit)
Q
Quleaf 已提交
993
        """
Q
Quleaf 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        assert 0 <= which_qubit < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'ry', 'which_qubits': [which_qubit], 'theta': [curr_idx, 0, 0]})
        self.__param.append(theta)

    def cry(self, theta, which_qubit):
        r"""添加关于 y 轴的控制单量子比特旋转门。

        其矩阵形式为:

        .. math::

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

        Args:
            theta (Tensor): 旋转角度
            which_qubit (list): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            theta = paddle.to_tensor(theta)
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            which_qubit = [0, 1]
            cir.cry(theta[0], which_qubit)
        """
        assert 0 <= which_qubit[0] < self.n and 0 <= which_qubit[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubit[0] != which_qubit[1], \
            "the control qubit is the same as the target qubit"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'cry', 'which_qubits': which_qubit, 'theta': [curr_idx, 0, 0]})
        self.__param.append(theta)
Q
Quleaf 已提交
1041 1042

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

Q
Quleaf 已提交
1045
        其矩阵形式为:
Q
Quleaf 已提交
1046

Q
Quleaf 已提交
1047
        .. math::
Q
Quleaf 已提交
1048

Q
Quleaf 已提交
1049 1050 1051 1052
            \begin{bmatrix}
                1 & 0 \\
                0 & e^{i\theta}
            \end{bmatrix}
Q
Quleaf 已提交
1053

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

Q
Quleaf 已提交
1058
        ..  code-block:: python
Q
Quleaf 已提交
1059

Q
Quleaf 已提交
1060
            import numpy as np
Q
Quleaf 已提交
1061
            import paddle
Q
Quleaf 已提交
1062 1063
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
1064 1065 1066 1067 1068
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rz(theta[0], which_qubit)
Q
Quleaf 已提交
1069
        """
Q
Quleaf 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        assert 0 <= which_qubit < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'rz', 'which_qubits': [which_qubit], 'theta': [0, 0, curr_idx]})
        self.__param.append(theta)

    def crz(self, theta, which_qubit):
        r"""添加关于 z 轴的控制单量子比特旋转门。

        其矩阵形式为:

        .. math::

            \begin{align}
                CNOT &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes rx\\
                &=
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 0 & 0 & e^{i\theta}
                \end{bmatrix}
            \end{align}

        Args:
            theta (Tensor): 旋转角度
            which_qubit (list): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            theta = paddle.to_tensor(theta)
            num_qubits = 2
            cir = UAnsatz(num_qubits)
            which_qubit = [0, 1]
            cir.crz(theta[0], which_qubit)
        """
        assert 0 <= which_qubit[0] < self.n and 0 <= which_qubit[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert which_qubit[0] != which_qubit[1], \
            "the control qubit is the same as the target qubit"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'crz', 'which_qubits': which_qubit, 'theta': [0, 0, curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1117 1118

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

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

Q
Quleaf 已提交
1123
        .. math::
Q
Quleaf 已提交
1124

Q
Quleaf 已提交
1125
            \begin{align}
Q
Quleaf 已提交
1126 1127 1128 1129 1130 1131 1132 1133
                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}
Q
Quleaf 已提交
1134
            \end{align}
Q
Quleaf 已提交
1135

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

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

Q
Quleaf 已提交
1142
            import numpy as np
Q
Quleaf 已提交
1143
            import paddle
Q
Quleaf 已提交
1144 1145
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
1146 1147
            cir = UAnsatz(num_qubits)
            cir.cnot([0, 1])
Q
Quleaf 已提交
1148
        """
Q
Quleaf 已提交
1149
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
Q
Quleaf 已提交
1150
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        assert control[0] != control[1], \
            "the control qubit is the same as the target qubit"
        self.__history.append({'gate': 'CNOT', 'which_qubits': control, 'theta': None})

    def cy(self, control):
        r"""添加一个 cy 门。

        对于 2 量子比特的量子电路,当 ``control`` 为 ``[0, 1]`` 时,其矩阵形式为:

        .. math::

            \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 & -1j \\
                    0 & 0 & 1j & 0
                \end{bmatrix}
            \end{align}

        Args:
            control (list): 作用在的量子比特的编号,``control[0]`` 为控制位,``control[1]`` 为目标位,
                其值都应该在 :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.cy([0, 1])
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert control[0] != control[1], \
            "the control qubit is the same as the target qubit"
        self.__history.append({'gate': 'cy', 'which_qubits': control, 'theta': None})

    def cz(self, control):
        r"""添加一个 cz 门。

        对于 2 量子比特的量子电路,当 ``control`` 为 ``[0, 1]`` 时,其矩阵形式为:

        .. math::

            \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 & 1 & 0 \\
                    0 & 0 & 0 & -1
                \end{bmatrix}
            \end{align}

        Args:
            control (list): 作用在的量子比特的编号,``control[0]`` 为控制位,``control[1]`` 为目标位,
                其值都应该在 :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.cz([0, 1])
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert control[0] != control[1], \
            "the control qubit is the same as the target qubit"
        self.__history.append({'gate': 'cz', 'which_qubits': control, 'theta': None})

    def cu(self, theta, phi, lam, control):
        r"""添加一个控制 U 门。

        对于 2 量子比特的量子电路,当 ``control`` 为 ``[0, 1]`` 时,其矩阵形式为:

        .. math::

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

        Args:
            theta (Tensor): 旋转角度 :math:`\theta` 。
            phi (Tensor): 旋转角度 :math:`\phi` 。
            lam (Tensor): 旋转角度 :math:`\lambda` 。
            control (list): 作用在的量子比特的编号,``control[0]`` 为控制位,``control[1]`` 为目标位,
                其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            num_qubits = 2
            cir = UAnsatz(num_qubits)
            theta = paddle.to_tensor(np.array([np.pi], np.float64), stop_gradient=False)
            phi = paddle.to_tensor(np.array([np.pi / 2], np.float64), stop_gradient=False)
            lam = paddle.to_tensor(np.array([np.pi / 4], np.float64), stop_gradient=False)
            cir.cu(theta, phi, lam, [0, 1])
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert control[0] != control[1], \
            "the control qubit is the same as the target qubit"
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'CU', 'which_qubits': control, 'theta': [curr_idx, curr_idx + 1, curr_idx + 2]})
        self.__param.extend([theta, phi, lam])
Q
Quleaf 已提交
1270

Q
Quleaf 已提交
1271 1272 1273 1274 1275 1276 1277 1278
    def swap(self, control):
        r"""添加一个 SWAP 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1279 1280 1281 1282 1283 1284 1285
                SWAP =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 1
                \end{bmatrix}
Q
Quleaf 已提交
1286 1287 1288
            \end{align}

        Args:
Q
Quleaf 已提交
1289 1290
            control (list): 作用在的量子比特的编号,``control[0]`` 和 ``control[1]`` 是想要交换的位,
                其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1291 1292 1293 1294

        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
1295
            import paddle
Q
Quleaf 已提交
1296 1297
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
1298 1299
            cir = UAnsatz(num_qubits)
            cir.swap([0, 1])
Q
Quleaf 已提交
1300
        """
Q
Quleaf 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert control[0] != control[1], \
            "the indices needed to be swapped should not be the same"
        self.__history.append({'gate': 'SWAP', 'which_qubits': control, 'theta': None})

    def cswap(self, control):
        r"""添加一个 CSWAP (Fredkin) 门。

        其矩阵形式为:

        .. math::

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

        Args:
            control (list): 作用在的量子比特的编号,``control[0]`` 为控制位,``control[1]`` 和 ``control[2]`` 是想要交换的目标位,
                其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 3
            cir = UAnsatz(num_qubits)
            cir.cswap([0, 1, 2])
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n and 0 <= control[2] < self.n, \
            "the qubit should >= 0 and < n (the number of qubit)"
        assert control[0] != control[1] and control[0] != control[
            2], "the control qubit is the same as the target qubit"
        assert control[1] != control[2], "the indices needed to be swapped should not be the same"
        self.__history.append({'gate': 'CSWAP', 'which_qubits': control, 'theta': None})

    def ccx(self, control):
        r"""添加一个 CCX (Toffoli) 门。

        其矩阵形式为:

        .. math::

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

        Args:
            control (list): 作用在的量子比特的编号, ``control[0]`` 和 ``control[1]`` 为控制位, ``control[2]`` 为目标位,
                当控制位值都为1时在该比特位作用X门。其值都应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数

        ..  code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 3
            cir = UAnsatz(num_qubits)
            cir.ccx([0, 1, 2])
        """
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n and 0 <= control[2] < self.n, \
Q
Quleaf 已提交
1383
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1384 1385 1386 1387 1388
        assert control[0] != control[2] and control[1] != control[2], \
            "the control qubits should not be the same as the target qubit"
        assert control[0] != control[1], \
            "two control qubits should not be the same"
        self.__history.append({'gate': 'CCX', 'which_qubits': control, 'theta': None})
Q
Quleaf 已提交
1389

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

Q
Quleaf 已提交
1393
        其矩阵形式为:
Q
Quleaf 已提交
1394

Q
Quleaf 已提交
1395
        .. math::
Q
Quleaf 已提交
1396 1397 1398 1399 1400

            \begin{bmatrix}
                0 & 1 \\
                1 & 0
            \end{bmatrix}
Q
Quleaf 已提交
1401

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

Q
Quleaf 已提交
1405
        .. code-block:: python
Q
Quleaf 已提交
1406

Q
Quleaf 已提交
1407
            import paddle
Q
Quleaf 已提交
1408
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
            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 已提交
1419
        """
Q
Quleaf 已提交
1420
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1421
        self.__history.append({'gate': 'x', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1422 1423

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

Q
Quleaf 已提交
1426
        其矩阵形式为:
Q
Quleaf 已提交
1427

Q
Quleaf 已提交
1428
        .. math::
Q
Quleaf 已提交
1429 1430 1431 1432 1433

            \begin{bmatrix}
                0 & -i \\
                i & 0
            \end{bmatrix}
Q
Quleaf 已提交
1434

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

Q
Quleaf 已提交
1438
        .. code-block:: python
Q
Quleaf 已提交
1439

Q
Quleaf 已提交
1440
            import paddle
Q
Quleaf 已提交
1441
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
            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 已提交
1452
        """
Q
Quleaf 已提交
1453
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1454
        self.__history.append({'gate': 'y', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1455 1456

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

Q
Quleaf 已提交
1459
        其矩阵形式为:
Q
Quleaf 已提交
1460

Q
Quleaf 已提交
1461
        .. math::
Q
Quleaf 已提交
1462 1463 1464 1465 1466

            \begin{bmatrix}
                1 & 0 \\
                0 & -1
            \end{bmatrix}
Q
Quleaf 已提交
1467

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

Q
Quleaf 已提交
1471
        .. code-block:: python
Q
Quleaf 已提交
1472

Q
Quleaf 已提交
1473
            import paddle
Q
Quleaf 已提交
1474
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            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 已提交
1485
        """
Q
Quleaf 已提交
1486
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1487
        self.__history.append({'gate': 'z', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1488 1489

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

Q
Quleaf 已提交
1492
        其矩阵形式为:
Q
Quleaf 已提交
1493 1494

        .. math::
Q
Quleaf 已提交
1495 1496 1497 1498 1499 1500

            H = \frac{1}{\sqrt{2}}
                \begin{bmatrix}
                    1&1\\
                    1&-1
                \end{bmatrix}
Q
Quleaf 已提交
1501 1502

        Args:
Q
Quleaf 已提交
1503
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1504
        """
Q
Quleaf 已提交
1505
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1506
        self.__history.append({'gate': 'h', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1507 1508

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

Q
Quleaf 已提交
1511
        其矩阵形式为:
Q
Quleaf 已提交
1512 1513

        .. math::
Q
Quleaf 已提交
1514 1515 1516 1517 1518 1519

            S =
                \begin{bmatrix}
                    1&0\\
                    0&i
                \end{bmatrix}
Q
Quleaf 已提交
1520 1521

        Args:
Q
Quleaf 已提交
1522
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1523
        """
Q
Quleaf 已提交
1524
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
        self.__history.append({'gate': 's', 'which_qubits': [which_qubit], 'theta': [0, 0, 1]})

    def sdg(self, which_qubit):
        r"""添加一个单量子比特的 S dagger 门。

        其矩阵形式为:

        .. math::

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

        Args:
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append({'gate': 'sdg', 'which_qubits': [which_qubit], 'theta': [0, 0, 2]})
Q
Quleaf 已提交
1545 1546

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

Q
Quleaf 已提交
1549
        其矩阵形式为:
Q
Quleaf 已提交
1550 1551 1552

        .. math::

Q
Quleaf 已提交
1553 1554 1555 1556 1557
            T =
                \begin{bmatrix}
                    1&0\\
                    0&e^\frac{i\pi}{4}
                \end{bmatrix}
Q
Quleaf 已提交
1558

Q
Quleaf 已提交
1559
        Args:
Q
Quleaf 已提交
1560
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1561
        """
Q
Quleaf 已提交
1562
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        self.__history.append({'gate': 't', 'which_qubits': [which_qubit], 'theta': [0, 0, 3]})

    def tdg(self, which_qubit):
        r"""添加一个单量子比特的 T dagger 门。

        其矩阵形式为:

        .. math::

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

        Args:
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
        self.__history.append({'gate': 'tdg', 'which_qubits': [which_qubit], 'theta': [0, 0, 4]})
Q
Quleaf 已提交
1583 1584 1585 1586

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

Q
Quleaf 已提交
1587
        其矩阵形式为:
Q
Quleaf 已提交
1588

Q
Quleaf 已提交
1589
        .. math::
Q
Quleaf 已提交
1590

Q
Quleaf 已提交
1591
            \begin{align}
Q
Quleaf 已提交
1592 1593 1594 1595 1596
                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}
Q
Quleaf 已提交
1597 1598 1599
            \end{align}

        Args:
Q
Quleaf 已提交
1600 1601 1602
              theta (Tensor): 旋转角度 :math:`\theta` 。
              phi (Tensor): 旋转角度 :math:`\phi` 。
              lam (Tensor): 旋转角度 :math:`\lambda` 。
Q
Quleaf 已提交
1603
              which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1604
        """
Q
Quleaf 已提交
1605
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1606 1607 1608 1609
        curr_idx = len(self.__param)
        self.__history.append(
            {'gate': 'u', 'which_qubits': [which_qubit], 'theta': [curr_idx, curr_idx + 1, curr_idx + 2]})
        self.__param.extend([theta, phi, lam])
Q
Quleaf 已提交
1610

Q
Quleaf 已提交
1611 1612 1613 1614 1615 1616 1617 1618
    def rxx(self, theta, which_qubits):
        r"""添加一个 RXX 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1619 1620 1621 1622 1623 1624 1625
                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}
Q
Quleaf 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
            \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"
Q
Quleaf 已提交
1644 1645 1646
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RXX_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1656 1657 1658 1659 1660 1661 1662
                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}
Q
Quleaf 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
            \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"
Q
Quleaf 已提交
1681 1682 1683
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RYY_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1693 1694 1695 1696 1697 1698 1699
                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}
Q
Quleaf 已提交
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
            \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"
Q
Quleaf 已提交
1718 1719 1720
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RZZ_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1730 1731 1732 1733 1734 1735 1736
                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}
Q
Quleaf 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
            \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"
Q
Quleaf 已提交
1757
        self.__history.append({'gate': 'MS_gate', 'which_qubits': which_qubits, 'theta': [2]})
Q
Quleaf 已提交
1758

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

        Args:
Q
Quleaf 已提交
1763
            theta (Tensor): 2-qubit 通用门的参数,其维度为 ``(15, )``
Q
Quleaf 已提交
1764 1765 1766 1767 1768 1769 1770
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
1771
            import paddle
Q
Quleaf 已提交
1772 1773
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
1774 1775 1776 1777 1778
            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 已提交
1779 1780 1781 1782 1783

        ::

            {'00': 0.4306256106527819, '01': 0.07994547866706268, '10': 0.07994547866706264, '11': 0.40948343201309334}
        """
Q
Quleaf 已提交
1784

Q
Quleaf 已提交
1785 1786 1787 1788 1789
        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
Q
Quleaf 已提交
1790

Q
Quleaf 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 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
        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]])

Q
Quleaf 已提交
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 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 1902 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 1947 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 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
    def universal_3_qubit_gate(self, theta, which_qubits):
        r"""添加 3-qubit 通用门,这个通用门需要 81 个参数。

        Args:
            theta (Tensor): 3-qubit 通用门的参数,其维度为 ``(81, )``
            which_qubits(list): 作用的量子比特编号

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

        代码示例:

        .. code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 3
            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))

        ::

            {'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"

        psi = reshape(x=theta[: 60], shape=[4, 15])
        phi = reshape(x=theta[60:], shape=[7, 3])
        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])

    def pauli_rotation_gate_partial(self, ind, gate_name):
        r"""计算传入的泡利旋转门的偏导。

        Args:
            ind (int): 该门在本电路中的序号
            gate_name (string): 门的名字

        Return:
            UAnsatz: 用电路表示的该门的偏导

        代码示例:

        .. code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            cir = UAnsatz(2)
            theta = paddle.to_tensor([np.pi, np.pi/2, np.pi/4], 'float64')
            cir.rx(theta[0], 0)
            cir.ryy(theta[1], [1, 0])
            cir.rz(theta[2], 1)
            print(cir.pauli_rotation_gate_partial(0, 'rx'))

        ::

            ------------x----Rx(3.142)----Ryy(1.57)---------------
                        |                     |                   
            ------------|-----------------Ryy(1.57)----Rz(0.785)--
                        |                                         
            --H---SDG---*--------H--------------------------------
        """
        history, param = self._get_history()
        assert ind <= len(history), "The index number should be less than or equal to %d" % len(history)
        assert gate_name in {'rx', 'ry', 'rz', 'RXX_gate', 'RYY_gate', 'RZZ_gate'}, "Gate not supported."
        assert gate_name == history[ind]['gate'], "Gate name incorrect."

        n = self.n
        new_circuit = UAnsatz(n + 1)
        new_circuit._add_history(history[:ind], param)
        new_circuit.h(n)
        new_circuit.sdg(n)
        if gate_name in {'rx', 'RXX_gate'}:
            new_circuit.cnot([n, history[ind]['which_qubits'][0]])
            if gate_name == 'RXX_gate':
                new_circuit.cnot([n, history[ind]['which_qubits'][1]])
        elif gate_name in {'ry', 'RYY_gate'}:
            new_circuit.cy([n, history[ind]['which_qubits'][0]])
            if gate_name == 'RYY_gate':
                new_circuit.cy([n, history[ind]['which_qubits'][1]])
        elif gate_name in {'rz', 'RZZ_gate'}:
            new_circuit.cz([n, history[ind]['which_qubits'][0]])
            if gate_name == 'RZZ_gate':
                new_circuit.cz([n, history[ind]['which_qubits'][1]])
        new_circuit.h(n)
        new_circuit._add_history(history[ind: len(history)], param)

        return new_circuit

    def control_rotation_gate_partial(self, ind, gate_name):
        r"""计算传入的控制旋转门的偏导。

        Args:
            ind (int): 该门在本电路中的序号
            gate_name (string): 门的名字

        Return:
            List: 用两个电路表示的该门的偏导

        代码示例:

        .. code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            cir = UAnsatz(2)
            theta = paddle.to_tensor([np.pi, np.pi/2, np.pi/4], 'float64')
            cir.rx(theta[0], 0)
            cir.ryy(theta[1], [1, 0])
            cir.crz(theta[2], [0, 1])
            print(cir.control_rotation_gate_partial(2, 'crz')[0])
            print(cir.control_rotation_gate_partial(2, 'crz')[1])

        ::

            --Rx(3.142)----Ryy(1.57)-------------*------
                               |                 |      
            ---------------Ryy(1.57)----z----Rz(0.785)--
                                        |               
            ------H-----------SDG-------*--------H------

            --Rx(3.142)----Ryy(1.57)----z-------------*------
                               |        |             |      
            ---------------Ryy(1.57)----|----z----Rz(0.785)--
                                        |    |               
            ------H------------S--------*----*--------H------
        """
        history, param = self._get_history()
        assert ind <= len(history), "The index number should be less than or equal to %d" % len(history)
        assert gate_name in {'crx', 'cry', 'crz'}, "Gate not supported."
        assert gate_name == history[ind]['gate'], "Gate name incorrect."

        n = self.n
        new_circuit = [UAnsatz(n + 1) for j in range(2)]
        for k in range(2):
            new_circuit[k]._add_history(history[:ind], param)
            new_circuit[k].h(n)
            new_circuit[k].sdg(n) if k == 0 else new_circuit[k].s(n)
            if k == 1:
                new_circuit[k].cz([n, history[ind]['which_qubits'][1]])
            if gate_name == 'crx':
                new_circuit[k].cnot([n, history[ind]['which_qubits'][0]])
            elif gate_name == 'cry':
                new_circuit[k].cy([n, history[ind]['which_qubits'][0]])
            elif gate_name == 'crz':
                new_circuit[k].cz([n, history[ind]['which_qubits'][0]])
            new_circuit[k].h(n)
            new_circuit[k]._add_history(history[ind: len(history)], param)

        return new_circuit

    def u3_partial(self, ind_history, ind_gate):
        r"""计算传入的 u3 门的一个参数的偏导。

        Args:
            ind_history (int): 该门在本电路中的序号
            ind_gate (int): u3 门参数的 index,可以是 0 或 1 或 2

        Return:
            UAnsatz: 用电路表示的该门的一个参数的偏导
Q
Quleaf 已提交
2022

Q
Quleaf 已提交
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
        代码示例:

        .. code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
            cir = UAnsatz(2)
            theta = paddle.to_tensor([np.pi, np.pi/2, np.pi/4], 'float64')
            cir.u3(theta[0], theta[1], theta[2], 0)
            print(cir.u3_partial(0, 0))

        ::

            ------------z----U--
                        |       
            ------------|-------
                        |       
            --H---SDG---*----H--
        """
        history, param = self._get_history()
        assert ind_history <= len(history), "The index number should be less than or equal to %d" % len(history)
        assert ind_gate in {0, 1, 2}, "U3 gate has only three parameters, please choose from {0, 1, 2}"
        assert history[ind_history]['gate'] == 'u', "Not a u3 gate."

        n = self.n
        new_circuit = UAnsatz(n + 1)
        assert ind_gate in {0, 1, 2}, "ind must be in {0, 1, 2}"
        new_circuit._add_history(history[:ind_history], param)
        if ind_gate == 0:
            new_circuit.h(n)
            new_circuit.sdg(n)
            new_circuit.cz([n, history[ind_history]['which_qubits'][0]])
            new_circuit.h(n)
            new_circuit._add_history(history[ind_history], param)
        elif ind_gate == 1:
            new_circuit.h(n)
            new_circuit.sdg(n)
            new_circuit.rz(self.__param[history[ind_history]['theta'][2]], history[ind_history]['which_qubits'][0])
            new_circuit.cy([n, history[ind_history]['which_qubits'][0]])
            new_circuit.ry(self.__param[history[ind_history]['theta'][0]], history[ind_history]['which_qubits'][0])
            new_circuit.rz(self.__param[history[ind_history]['theta'][1]], history[ind_history]['which_qubits'][0])
            new_circuit.h(n)
        elif ind_gate == 2:
            new_circuit.h(n)
            new_circuit.sdg(n)
            new_circuit.rz(self.__param[history[ind_history]['theta'][2]], history[ind_history]['which_qubits'][0])
            new_circuit.ry(self.__param[history[ind_history]['theta'][0]], history[ind_history]['which_qubits'][0])
            new_circuit.cz([n, history[ind_history]['which_qubits'][0]])
            new_circuit.rz(self.__param[history[ind_history]['theta'][1]], history[ind_history]['which_qubits'][0])
            new_circuit.h(n)
        new_circuit._add_history(history[ind_history + 1: len(history)], param)

        return new_circuit

    def cu3_partial(self, ind_history, ind_gate):
        r"""计算传入的 cu 门的一个参数的偏导。
Q
Quleaf 已提交
2080 2081

        Args:
Q
Quleaf 已提交
2082 2083 2084 2085 2086
            ind_history (int): 该门在本电路中的序号
            ind_gate (int): cu 门参数的 index,可以是 0 或 1 或 2

        Return:
            UAnsatz: 用电路表示的该门的一个参数的偏导
Q
Quleaf 已提交
2087 2088 2089 2090 2091 2092

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
2093
            import paddle
Q
Quleaf 已提交
2094
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2095 2096 2097 2098 2099
            cir = UAnsatz(2)
            theta = paddle.to_tensor([np.pi, np.pi/2, np.pi/4], 'float64')
            cir.cu(theta[0], theta[1], theta[2], [0, 1])
            print(cir.cu3_partial(0, 0)[0])
            print(cir.cu3_partial(0, 0)[1])
Q
Quleaf 已提交
2100 2101 2102

        ::

Q
Quleaf 已提交
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
            -----------------x--
                             |  
            ------------z----U--
                        |       
            --H---SDG---*----H--

            ------------z---------x--
                        |         |  
            ------------|----z----U--
                        |    |       
            --H----S----*----*----H--
Q
Quleaf 已提交
2114
        """
Q
Quleaf 已提交
2115 2116 2117 2118
        history, param = self._get_history()
        assert ind_history <= len(history), "The index number should be less than or equal to %d" % len(history)
        assert ind_gate in {0, 1, 2}, "CU gate has only three parameters, please choose from {0, 1, 2}"
        assert history[ind_history]['gate'] == 'CU', "Not a CU gate."
Q
Quleaf 已提交
2119

Q
Quleaf 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
        n = self.n
        new_circuit = [UAnsatz(n + 1) for j in range(2)]
        assert ind_gate in {0, 1, 2}, "ind must be in {0, 1, 2}"
        for k in range(2):
            new_circuit[k]._add_history(history[:ind_history], param)
            if ind_gate == 0:
                new_circuit[k].h(n)
                new_circuit[k].sdg(n) if k == 0 else new_circuit[k].s(n)
                if k == 1:
                    new_circuit[k].cz([n, history[ind_history]['which_qubits'][0]])
                new_circuit[k].cz([n, history[ind_history]['which_qubits'][1]])
                new_circuit[k].h(n)
                new_circuit[k]._add_history([history[ind_history]], param)
            elif ind_gate == 1:
                new_circuit[k].h(n)
                new_circuit[k].sdg(n) if k == 0 else new_circuit[k].s(n)
                new_circuit[k].crz(self.__param[history[ind_history]['theta'][2]], history[ind_history]['which_qubits'])
                if k == 1:
                    new_circuit[k].cz([n, history[ind_history]['which_qubits'][0]])
                new_circuit[k].cy([n, history[ind_history]['which_qubits'][0]])
                new_circuit[k].cry(self.__param[history[ind_history]['theta'][0]], history[ind_history]['which_qubits'])
                new_circuit[k].crz(self.__param[history[ind_history]['theta'][1]], history[ind_history]['which_qubits'])
                new_circuit[k].h(n)
            elif ind_gate == 2:
                new_circuit[k].h(n)
                new_circuit[k].sdg(n) if k == 0 else new_circuit[k].s(n)
                new_circuit[k].crz(self.__param[history[ind_history]['theta'][2]], history[ind_history]['which_qubits'])
                new_circuit[k].cry(self.__param[history[ind_history]['theta'][0]], history[ind_history]['which_qubits'])
                if k == 1:
                    new_circuit[k].cz([n, history[ind_history]['which_qubits'][0]])
                new_circuit[k].cz([n, history[ind_history]['which_qubits'][0]])
                new_circuit[k].crz(self.__param[history[ind_history]['theta'][1]], history[ind_history]['which_qubits'])
                new_circuit[k].h(n)

            new_circuit[k]._add_history(history[ind_history + 1: len(history)], param)

        return new_circuit

    def linear_combinations_gradient(self, H, shots=0):
        r"""用 linear combination 的方法计算电路中所有需要训练的参数的梯度。损失函数默认为计算哈密顿量的期望值。
Q
Quleaf 已提交
2160

Q
Quleaf 已提交
2161 2162 2163
        Args:
            H (list or Hamiltonian): 损失函数中用到的记录哈密顿量信息的列表或 ``Hamiltonian`` 类的对象
            shots (int, optional): 测量次数;默认为 0,表示返回期望值的精确值,即测量无穷次后的期望值
Q
Quleaf 已提交
2164

Q
Quleaf 已提交
2165 2166
        Return:
            Tensor: 该电路中所有需要训练的参数的梯度
Q
Quleaf 已提交
2167

Q
Quleaf 已提交
2168
        代码示例:
Q
Quleaf 已提交
2169

Q
Quleaf 已提交
2170
        .. code-block:: python
Q
Quleaf 已提交
2171

Q
Quleaf 已提交
2172 2173 2174
            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2175

Q
Quleaf 已提交
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
            def U_theta(theta, N, D):
                cir = UAnsatz(N)
                cir.complex_entangled_layer(theta[:D], D)
                for i in range(N):
                    cir.ry(theta=theta[D][i][0], which_qubit=i)
                cir.run_state_vector()
                return cir

            H = [[1.0, 'z0,z1']]
            theta = paddle.uniform(shape=[2, 2, 3], dtype='float64', min=0.0, max=np.pi * 2)
            theta.stop_gradient = False
            circuit = U_theta(theta, 2, 1)
            gradient = circuit.linear_combinations_gradient(H, shots=0)
            print(gradient)

        ::

            Tensor(shape=[8], dtype=float64, place=CPUPlace, stop_gradient=True,
                   [ 0.        , -0.11321444, -0.22238044,  0.        ,  0.04151700,  0.44496212, -0.19465690,  0.96022600])
        """
        history, param = self._get_history()
        grad = []

        if not isinstance(H, list):
            H = H.pauli_str
        H = copy.deepcopy(H)
        for i in H:
            i[1] += ',z' + str(self.n)

        for i, history_i in enumerate(history):
            if history_i['gate'] == 'rx' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'rx')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'ry' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'ry')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'rz' and self.__param[history_i['theta'][2]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'rz')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'crx' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.control_rotation_gate_partial(i, 'crx')
                for k in new_circuit:
                    if self.__run_mode == 'state_vector':
                        k.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        k.run_density_matrix()
                gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                grad.append(gradient)
            elif history_i['gate'] == 'cry' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.control_rotation_gate_partial(i, 'cry')
                for k in new_circuit:
                    if self.__run_mode == 'state_vector':
                        k.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        k.run_density_matrix()
                gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                grad.append(gradient)
            elif history_i['gate'] == 'crz' and self.__param[history_i['theta'][2]].stop_gradient is False:
                new_circuit = self.control_rotation_gate_partial(i, 'crz')
                for k in new_circuit:
                    if self.__run_mode == 'state_vector':
                        k.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        k.run_density_matrix()
                gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                grad.append(gradient)
            elif history_i['gate'] == 'RXX_gate' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'RXX_gate')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'RYY_gate' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'RYY_gate')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'RZZ_gate' and self.__param[history_i['theta'][0]].stop_gradient is False:
                new_circuit = self.pauli_rotation_gate_partial(i, 'RZZ_gate')
                if self.__run_mode == 'state_vector':
                    new_circuit.run_state_vector()
                elif self.__run_mode == 'density_matrix':
                    new_circuit.run_density_matrix()
                grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'u':
                if not self.__param[history_i['theta'][0]].stop_gradient:
                    new_circuit = self.u3_partial(i, 0)
                    if self.__run_mode == 'state_vector':
                        new_circuit.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        new_circuit.run_density_matrix()
                    grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
                if not self.__param[history_i['theta'][1]].stop_gradient:
                    new_circuit = self.u3_partial(i, 1)
                    if self.__run_mode == 'state_vector':
                        new_circuit.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        new_circuit.run_density_matrix()
                    grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
                if not self.__param[history_i['theta'][2]].stop_gradient:
                    new_circuit = self.u3_partial(i, 2)
                    if self.__run_mode == 'state_vector':
                        new_circuit.run_state_vector()
                    elif self.__run_mode == 'density_matrix':
                        new_circuit.run_density_matrix()
                    grad.append(paddle.to_tensor(new_circuit.expecval(H, shots), 'float64'))
            elif history_i['gate'] == 'CU':
                if not self.__param[history_i['theta'][0]].stop_gradient:
                    new_circuit = self.cu3_partial(i, 0)
                    for k in new_circuit:
                        if self.__run_mode == 'state_vector':
                            k.run_state_vector()
                        elif self.__run_mode == 'density_matrix':
                            k.run_density_matrix()
                    gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                    grad.append(gradient)
                if not self.__param[history_i['theta'][1]].stop_gradient:
                    new_circuit = self.cu3_partial(i, 1)
                    for k in new_circuit:
                        if self.__run_mode == 'state_vector':
                            k.run_state_vector()
                        elif self.__run_mode == 'density_matrix':
                            k.run_density_matrix()
                    gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                    grad.append(gradient)
                if not self.__param[history_i['theta'][2]].stop_gradient:
                    new_circuit = self.cu3_partial(i, 2)
                    for k in new_circuit:
                        if self.__run_mode == 'state_vector':
                            k.run_state_vector()
                        elif self.__run_mode == 'density_matrix':
                            k.run_density_matrix()
                    gradient = paddle.to_tensor(np.mean([circuit.expecval(H, shots) for circuit in new_circuit]), 'float64')
                    grad.append(gradient)
        grad = paddle.concat(grad)

        return grad
Q
Quleaf 已提交
2328

Q
Quleaf 已提交
2329
    """
Q
Quleaf 已提交
2330
    Measurements
Q
Quleaf 已提交
2331 2332
    """

Q
Quleaf 已提交
2333
    def __process_string(self, s, which_qubits):
Q
Quleaf 已提交
2334
        r"""该函数基于 which_qubits 返回 s 的一部分
Q
Quleaf 已提交
2335 2336
        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 已提交
2337

Q
Quleaf 已提交
2338 2339 2340 2341 2342
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        new_s = ''.join(s[j] for j in which_qubits)
        return new_s
Q
Quleaf 已提交
2343

Q
Quleaf 已提交
2344
    def __process_similiar(self, result):
Q
Quleaf 已提交
2345
        r"""该函数基于相同的键合并值。
Q
Quleaf 已提交
2346
        This functions merges values based on identical keys.
Q
Quleaf 已提交
2347 2348
        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 已提交
2349

Q
Quleaf 已提交
2350 2351 2352 2353 2354 2355
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        data = defaultdict(int)
        for idx, val in result:
            data[idx] += val
Q
Quleaf 已提交
2356

Q
Quleaf 已提交
2357
        return dict(data)
Q
Quleaf 已提交
2358

Q
Quleaf 已提交
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
    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 已提交
2397
        r"""对量子电路输出的量子态进行测量。
Q
Quleaf 已提交
2398 2399

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

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

Q
Quleaf 已提交
2407 2408 2409 2410 2411 2412
        Returns:
            dict: 测量的结果

        代码示例:

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

Q
Quleaf 已提交
2414 2415
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2416 2417 2418 2419 2420 2421
            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 已提交
2422 2423 2424

        ::

Q
Quleaf 已提交
2425
            The results of measuring qubit 1 2048 times are {'0': 964, '1': 1084}
Q
Quleaf 已提交
2426 2427

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

Q
Quleaf 已提交
2429 2430
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2431 2432 2433 2434 2435 2436
            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 已提交
2437 2438 2439

        ::

Q
Quleaf 已提交
2440
            The probability distribution of measurement results on qubit 1 is {'0': 0.4999999999999999, '1': 0.4999999999999999}
Q
Quleaf 已提交
2441
        """
Q
Quleaf 已提交
2442
        if self.__run_mode == 'state_vector':
Q
Quleaf 已提交
2443
            state = self.__state
Q
Quleaf 已提交
2444
        elif self.__run_mode == 'density_matrix':
Q
Quleaf 已提交
2445 2446
            # Take the diagonal of the density matrix as a probability distribution
            diag = np.diag(self.__state.numpy())
Q
Quleaf 已提交
2447
            state = paddle.to_tensor(np.sqrt(diag))
Q
Quleaf 已提交
2448 2449 2450 2451 2452 2453 2454 2455
        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 已提交
2456
                result[dic10to2[i]] = (real(state)[i] ** 2 + imag(state)[i] ** 2).numpy()[0]
Q
Quleaf 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474

            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)

Q
Quleaf 已提交
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    def measure_in_bell_basis(self, which_qubits, shots=0):
        r"""对量子电路输出的量子态进行贝尔基测量。

        Args:
            which_qubits(list): 要测量的量子比特
            shots(int): 测量的采样次数,默认为0,表示计算解析解

        Returns:
            list: 测量得到四个贝尔基的概率
        """
        assert which_qubits[0] != which_qubits[1], "You have to measure two different qubits."
        which_qubits.sort()
        i, j = which_qubits
        qubit_num = self.n
        input_state = self.__state
        mode = self.__run_mode
        cir = UAnsatz(qubit_num)
        cir.cnot([i, j])
        cir.h(i)

        if mode == 'state_vector':
            output_state = cir.run_state_vector(input_state).numpy()
        elif mode == 'density_matrix':
            output_density_matrix = cir.run_density_matrix(input_state).numpy()
            output_state = np.sqrt(np.diag(output_density_matrix))
        else:
            raise ValueError("Can't recognize the mode of quantum state.")

        prob_amplitude = np.abs(output_state).tolist()
        prob_amplitude = [item ** 2 for item in prob_amplitude]

        prob_array = [0] * 4
        for i in range(2 ** qubit_num):
            binary = bin(i)[2:]
            binary = '0' * (qubit_num - len(binary)) + binary
            target_qubits = str()
            for qubit_idx in which_qubits:
                target_qubits += binary[qubit_idx]
            prob_array[int(target_qubits, base=2)] += prob_amplitude[i]

        if shots == 0:
            result = prob_array
        else:
            result = [0] * 4
            samples = np.random.choice(list(range(4)), shots, p=prob_array)
            for item in samples:
                result[item] += 1
            result = [item / shots for item in result]

        return result

    def expecval(self, H, shots=0):
Q
Quleaf 已提交
2527
        r"""量子电路输出的量子态关于可观测量 H 的期望值。
Q
Quleaf 已提交
2528 2529

        Hint:
Q
Quleaf 已提交
2530 2531 2532
            如果想输入的可观测量的矩阵为 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I` ,
                则 ``H`` 的 ``list`` 形式为 ``[[0.7, 'Z0, X1'], [0.2, 'Z1']]`` 。

Q
Quleaf 已提交
2533
        Args:
Q
Quleaf 已提交
2534 2535 2536
            H (Hamiltonian or list): 可观测量的相关信息
            shots (int, optional): 测量次数;默认为 0,表示返回期望值的精确值,即测量无穷次后的期望值

Q
Quleaf 已提交
2537
        Returns:
Q
Quleaf 已提交
2538
            Tensor: 量子电路输出的量子态关于 ``H`` 的期望值
Q
Quleaf 已提交
2539 2540

        代码示例:
Q
Quleaf 已提交
2541

Q
Quleaf 已提交
2542
        .. code-block:: python
Q
Quleaf 已提交
2543 2544

            import numpy as np
Q
Quleaf 已提交
2545
            import paddle
Q
Quleaf 已提交
2546
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2547

Q
Quleaf 已提交
2548
            n = 5
Q
Quleaf 已提交
2549
            experiment_shots = 2**10
Q
Quleaf 已提交
2550
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
Q
Quleaf 已提交
2551
            theta = paddle.ones([3], dtype='float64')
Q
Quleaf 已提交
2552

Q
Quleaf 已提交
2553 2554 2555 2556 2557
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.rz(theta[1], 1)
            cir.rx(theta[2], 2)
            cir.run_state_vector()
Q
Quleaf 已提交
2558

Q
Quleaf 已提交
2559 2560 2561 2562 2563
            result_1 = cir.expecval(H_info, shots = experiment_shots).numpy()
            result_2 = cir.expecval(H_info, shots = 0).numpy()

            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 已提交
2564

Q
Quleaf 已提交
2565
        ::
Q
Quleaf 已提交
2566

Q
Quleaf 已提交
2567 2568
            The expectation value obtained by 1024 measurements is [-0.16328125]
            The accurate expectation value of H is [-0.1682942]
Q
Quleaf 已提交
2569
        """
Q
Quleaf 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
        expec_val = 0
        if not isinstance(H, list):
            H = H.pauli_str
        if shots == 0:
            if self.__run_mode == 'state_vector':
                expec_val = real(vec_expecval(H, self.__state))
            elif self.__run_mode == 'density_matrix':
                state = self.__state
                H_mat = paddle.to_tensor(pauli_str_to_matrix(H, self.n))
                expec_val = real(trace(matmul(state, H_mat)))
            else:
                # Raise error
                raise ValueError("no state for measurement; please run the circuit first")
Q
Quleaf 已提交
2583
        else:
Q
Quleaf 已提交
2584 2585 2586 2587 2588
            for term in H:
                expec_val += term[0] * _local_H_prob(self, term[1], shots=shots)
            expec_val = paddle.to_tensor(expec_val, 'float64')

        return expec_val
Q
Quleaf 已提交
2589 2590

    """
Q
Quleaf 已提交
2591
    Circuit Templates
Q
Quleaf 已提交
2592 2593
    """

Q
Quleaf 已提交
2594
    def superposition_layer(self):
Q
Quleaf 已提交
2595
        r"""添加一层 Hadamard 门。
Q
Quleaf 已提交
2596 2597 2598 2599

        代码示例:

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

Q
Quleaf 已提交
2601 2602
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2603 2604 2605 2606 2607
            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 已提交
2608 2609 2610

        ::

Q
Quleaf 已提交
2611 2612 2613
            The probability distribution of measurement results on both qubits is
                {'00': 0.2499999999999999, '01': 0.2499999999999999,
                '10': 0.2499999999999999, '11': 0.2499999999999999}
Q
Quleaf 已提交
2614
        """
Q
Quleaf 已提交
2615 2616 2617 2618
        for i in range(self.n):
            self.h(i)

    def weak_superposition_layer(self):
Q
Quleaf 已提交
2619
        r"""添加一层旋转角度为 :math:`\pi/4` 的 Ry 门。
Q
Quleaf 已提交
2620 2621 2622 2623

        代码示例:

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

Q
Quleaf 已提交
2625 2626
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2627 2628 2629 2630 2631
            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 已提交
2632 2633 2634

        ::

Q
Quleaf 已提交
2635 2636 2637
            The probability distribution of measurement results on both qubits is
                {'00': 0.7285533905932737, '01': 0.12500000000000003,
                '10': 0.12500000000000003, '11': 0.021446609406726238}
Q
Quleaf 已提交
2638
        """
Q
Quleaf 已提交
2639
        _theta = paddle.to_tensor(np.array([np.pi / 4]))  # Used in fixed Ry gate
Q
Quleaf 已提交
2640 2641
        for i in range(self.n):
            self.ry(_theta, i)
Q
Quleaf 已提交
2642

Q
Quleaf 已提交
2643 2644 2645 2646
    def linear_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 Ry 门,Rz 门和 CNOT 门的线性纠缠层。

        Attention:
Q
Quleaf 已提交
2647
            ``theta`` 的维度为 ``(depth, n, 2)`` ,最低维内容为对应的 ``ry`` 和 ``rz`` 的参数, ``n`` 为作用的量子比特数量。
Q
Quleaf 已提交
2648 2649 2650 2651

        Args:
            theta (Tensor): Ry 门和 Rz 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2652
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2653 2654 2655 2656 2657 2658 2659 2660 2661

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2662
            theta = paddle.ones([DEPTH, 2, 2], dtype='float64')
Q
Quleaf 已提交
2663 2664 2665
            cir = UAnsatz(n)
            cir.linear_entangled_layer(theta, DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2666 2667
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")
Q
Quleaf 已提交
2668 2669 2670

        ::

Q
Quleaf 已提交
2671 2672 2673
            The probability distribution of measurement results on both qubits is
                {'00': 0.646611169077063, '01': 0.06790630495474384,
                '10': 0.19073671025717626, '11': 0.09474581571101756}
Q
Quleaf 已提交
2674
        """
Q
Quleaf 已提交
2675 2676 2677 2678 2679 2680
        # reformat 1D theta list
        theta_flat = paddle.flatten(theta)
        width = len(which_qubits) if which_qubits is not None else self.n
        assert len(theta_flat) == depth * width * 2, 'the size of theta is not right'
        theta = paddle.reshape(theta_flat, [depth, width, 2])

Q
Quleaf 已提交
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
        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 已提交
2700 2701
    def real_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 Ry 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
2702

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

Q
Quleaf 已提交
2706
        Attention:
Q
Quleaf 已提交
2707
            ``theta`` 的维度为 ``(depth, n, 1)``, ``n`` 为作用的量子比特数量。
Q
Quleaf 已提交
2708

Q
Quleaf 已提交
2709
        Args:
Q
Quleaf 已提交
2710
            theta (Tensor): Ry 门的旋转角度
Q
Quleaf 已提交
2711
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2712
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2713 2714 2715 2716

        代码示例:

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

Q
Quleaf 已提交
2718
            import paddle
Q
Quleaf 已提交
2719 2720 2721
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2722
            theta = paddle.ones([DEPTH, 2, 1], dtype='float64')
Q
Quleaf 已提交
2723 2724 2725
            cir = UAnsatz(n)
            cir.real_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2726 2727 2728
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2729 2730
        ::

Q
Quleaf 已提交
2731 2732 2733
            The probability distribution of measurement results on both qubits is
                {'00': 2.52129874867343e-05, '01': 0.295456784923382,
                '10': 0.7045028818254718, '11': 1.5120263659845063e-05}
Q
Quleaf 已提交
2734
        """
Q
Quleaf 已提交
2735 2736 2737 2738 2739 2740
        # reformat 1D theta list
        theta_flat = paddle.flatten(theta)
        width = len(which_qubits) if which_qubits is not None else self.n
        assert len(theta_flat) == depth * width, 'the size of theta is not right'
        theta = paddle.reshape(theta_flat, [depth, width, 1])

Q
Quleaf 已提交
2741 2742 2743
        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 已提交
2744
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2745 2746
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'

Q
Quleaf 已提交
2747 2748 2749
        if which_qubits is None:
            which_qubits = np.arange(self.n)

Q
Quleaf 已提交
2750
        for repeat in range(depth):
Q
Quleaf 已提交
2751
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2752
                self.ry(theta[repeat][i][0], q)
Q
Quleaf 已提交
2753 2754 2755
            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 已提交
2756

Q
Quleaf 已提交
2757 2758
    def complex_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
2759 2760 2761

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

Q
Quleaf 已提交
2763
        Attention:
Q
Quleaf 已提交
2764 2765
            ``theta`` 的维度为 ``(depth, n, 3)`` ,最低维内容为对应的 ``u3`` 的参数 ``(theta, phi, lam)``, ``n`` 为作用的量子比特数量。

Q
Quleaf 已提交
2766
        Args:
Q
Quleaf 已提交
2767
            theta (Tensor): U3 门的旋转角度
Q
Quleaf 已提交
2768
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2769
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2770 2771 2772 2773

        代码示例:

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

Q
Quleaf 已提交
2775
            import paddle
Q
Quleaf 已提交
2776 2777 2778
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2779
            theta = paddle.ones([DEPTH, 2, 3], dtype='float64')
Q
Quleaf 已提交
2780 2781 2782
            cir = UAnsatz(n)
            cir.complex_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2783 2784 2785
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2786 2787
        ::

Q
Quleaf 已提交
2788 2789 2790
            The probability distribution of measurement results on both qubits is
                {'00': 0.15032627279218896, '01': 0.564191201239618,
                '10': 0.03285998070292556, '11': 0.25262254526526823}
Q
Quleaf 已提交
2791
        """
Q
Quleaf 已提交
2792 2793 2794 2795 2796 2797
        # reformat 1D theta list
        theta_flat = paddle.flatten(theta)
        width = len(which_qubits) if which_qubits is not None else self.n
        assert len(theta_flat) == depth * width * 3, 'the size of theta is not right'
        theta = paddle.reshape(theta_flat, [depth, width, 3])

Q
Quleaf 已提交
2798 2799 2800
        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 已提交
2801
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2802
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'
Q
Quleaf 已提交
2803

Q
Quleaf 已提交
2804 2805
        if which_qubits is None:
            which_qubits = np.arange(self.n)
Q
Quleaf 已提交
2806

Q
Quleaf 已提交
2807 2808
        for repeat in range(depth):
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2809
                self.u3(theta[repeat][i][0], theta[repeat][i][1], theta[repeat][i][2], q)
Q
Quleaf 已提交
2810 2811 2812
            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 已提交
2813 2814 2815 2816 2817 2818 2819

    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 已提交
2820
        """
Q
Quleaf 已提交
2821 2822 2823 2824
        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 已提交
2825

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

Q
Quleaf 已提交
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
        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"""
Q
Quleaf 已提交
2850 2851
        Add a real layer on the circuit. theta is a two dimensional tensor.
        position is the qubit range the layer needs to cover.
Q
Quleaf 已提交
2852 2853 2854

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
2855
        """
Q
Quleaf 已提交
2856
        assert theta.shape[1] == 4 and theta.shape[0] == (position[1] - position[0] + 1) / 2, \
Q
Quleaf 已提交
2857 2858 2859 2860 2861 2862
            '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"""
Q
Quleaf 已提交
2863 2864
        Add a complex layer on the circuit. theta is a two dimensional tensor.
        position is the qubit range the layer needs to cover.
Q
Quleaf 已提交
2865 2866 2867

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
2868
        """
Q
Quleaf 已提交
2869
        assert theta.shape[1] == 12 and theta.shape[0] == (position[1] - position[0] + 1) / 2, \
Q
Quleaf 已提交
2870 2871 2872
            '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 已提交
2873

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

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

Q
Quleaf 已提交
2880
        Attention:
Q
Quleaf 已提交
2881
            ``theta`` 的维度为 ``(depth, n-1, 4)`` 。
Q
Quleaf 已提交
2882

Q
Quleaf 已提交
2883
        Args:
Q
Quleaf 已提交
2884 2885
            theta (Tensor): Ry 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2886 2887 2888 2889

        代码示例:

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

Q
Quleaf 已提交
2891 2892
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2893 2894
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2895
            theta = paddle.ones([DEPTH, n - 1, 4], dtype='float64')
Q
Quleaf 已提交
2896 2897 2898 2899
            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 已提交
2900

Q
Quleaf 已提交
2901 2902 2903
        ::

            {'0': 0.9646724056906162, '1': 0.035327594309385896}
Q
Quleaf 已提交
2904
        """
Q
Quleaf 已提交
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
        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 已提交
2922 2923
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的弱纠缠层。

Q
Quleaf 已提交
2924 2925 2926 2927
        Note:
            这一层量子门的数学表示形式为复数酉矩阵。

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

Q
Quleaf 已提交
2930
        Args:
Q
Quleaf 已提交
2931
            theta (Tensor): U3 门的角度信息
Q
Quleaf 已提交
2932 2933 2934 2935 2936
            depth (int): 纠缠层的深度

        代码示例:

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

Q
Quleaf 已提交
2938 2939
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2940 2941
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2942
            theta = paddle.ones([DEPTH, n - 1, 12], dtype='float64')
Q
Quleaf 已提交
2943 2944 2945 2946
            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 已提交
2947

Q
Quleaf 已提交
2948
        ::
Q
Quleaf 已提交
2949

Q
Quleaf 已提交
2950
            {'0': 0.5271554811768046, '1': 0.4728445188231988}
Q
Quleaf 已提交
2951
        """
Q
Quleaf 已提交
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
        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 已提交
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
    def finite_difference_gradient(self, H, delta, shots=0):
        r"""用差分法估计电路中参数的梯度。损失函数默认为计算哈密顿量的期望值。

        Args:
            H (list or Hamiltonian): 记录哈密顿量信息的列表或 ``Hamiltonian`` 类的对象
            delta (float): 差分法中的 delta
            shots (int, optional): 测量次数;默认为 0,表示返回期望值的精确值,即测量无穷次后的期望值

        Returns:
            Tensor: 电路中所有可训练参数的梯度

        代码示例:

        .. code-block:: python

            import paddle
            import numpy as np
            from paddle_quantum.circuit import UAnsatz

            H = [[1.0, 'z0,z1']]
            theta = paddle.to_tensor(np.array([6.186, 5.387, 1.603, 1.998]), stop_gradient=False)

            cir = UAnsatz(2)
            cir.ry(theta[0], 0)
            cir.ry(theta[1], 1)
            cir.cnot([0, 1])
            cir.cnot([1, 0])
            cir.ry(theta[2], 0)
            cir.ry(theta[3], 1)
            cir.run_state_vector()

            gradients = cir.finite_difference_gradient(H, delta=0.01, shots=0)
            print(gradients)

        ::

            Tensor(shape=[4], dtype=float64, place=CPUPlace, stop_gradient=False,
                   [0.01951135, 0.56594233, 0.37991172, 0.35337436])
        """
        grad = []
        for i, theta_i in enumerate(self.__param):
            if theta_i.stop_gradient:
                continue
            self.__param[i] += delta / 2
            self.run_state_vector()
            expec_plu = self.expecval(H, shots)
            self.__param[i] -= delta
            self.run_state_vector()
            expec_min = self.expecval(H, shots)
            self.__param[i] += delta / 2
            self.run_state_vector()
            grad.append(paddle.to_tensor((expec_plu - expec_min) / delta, 'float64'))
            self.__param[i].stop_gradient = False
        grad = paddle.concat(grad)
        grad.stop_gradient = False

        return grad

    def param_shift_gradient(self, H, shots=0):
        r"""用 parameter-shift 方法计算电路中参数的梯度。损失函数默认为计算哈密顿量的期望值。

        Args:
            H (list or Hamiltonian): 记录哈密顿量信息的列表或 ``Hamiltonian`` 类的对象
            shots (int, optional): 测量次数;默认为 0,表示返回期望值的精确值,即测量无穷次后的期望值

        Returns:
            Tensor: 电路中所有可训练参数的梯度

        代码示例:

        .. code-block:: python

            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz

            H = [[1.0, 'z0,z1']]
            theta = paddle.to_tensor(np.array([6.186, 5.387, 1.603, 1.998]), stop_gradient=False)

            cir = UAnsatz(2)
            cir.ry(theta[0], 0)
            cir.ry(theta[1], 1)
            cir.cnot([0, 1])
            cir.cnot([1, 0])
            cir.ry(theta[2], 0)
            cir.ry(theta[3], 1)
            cir.run_state_vector()

            gradients = cir.param_shift_gradient(H, shots=0)
            print(gradients)

        ::

            Tensor(shape=[4], dtype=float64, place=CPUPlace, stop_gradient=False,
                   [0.01951143, 0.56594470, 0.37991331, 0.35337584])
        """
        r = 1 / 2
        grad = []
        for i, theta_i in enumerate(self.__param):
            if theta_i.stop_gradient:
                continue
            self.__param[i] += np.pi / (4 * r)
            self.run_state_vector()
            f_plu = self.expecval(H, shots)
            self.__param[i] -= 2 * np.pi / (4 * r)
            self.run_state_vector()
            f_min = self.expecval(H, shots)
            self.__param[i] += np.pi / (4 * r)
            self.run_state_vector()
            grad.append(paddle.to_tensor(r * (f_plu - f_min), 'float64'))
            self.__param[i].stop_gradient = False
        grad = paddle.concat(grad)
        grad.stop_gradient = False

        return grad

    def get_param(self):
        r"""得到电路参数列表中的可训练的参数。

        Returns:
            list: 电路中所有可训练的参数
        """
        param = []
        for theta in self.__param:
            if not theta.stop_gradient:
                param.append(theta)
        assert len(param) != 0, "circuit does not contain trainable parameters"
        param = paddle.concat(param)
        param.stop_gradient = False
        return param

    def update_param(self, new_param):
        r"""用得到的新参数列表更新电路参数列表中的可训练的参数。
        
        Args:
            new_param (list): 新的参数列表

        Returns:
            Tensor: 更新后电路中所有训练的参数
        """
        j = 0
        for i in range(len(self.__param)):
            if not self.__param[i].stop_gradient:
                self.__param[i] = paddle.to_tensor(new_param[j], 'float64')
                self.__param[i].stop_gradient = False
                j += 1
        self.run_state_vector()
        return self.__param

Q
Quleaf 已提交
3117 3118 3119 3120 3121 3122 3123 3124 3125
    """
    Channels
    """

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

        其 Kraus 算符为:
Q
Quleaf 已提交
3126

Q
Quleaf 已提交
3127 3128
        .. math::

Q
Quleaf 已提交
3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
            E_0 =
            \begin{bmatrix}
                1 & 0 \\
                0 & \sqrt{1-\gamma}
            \end{bmatrix},
            E_1 =
            \begin{bmatrix}
                0 & \sqrt{\gamma} \\
                0 & 0
            \end{bmatrix}.
Q
Quleaf 已提交
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152

        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 已提交
3153
            cir.cnot([0, 1])
Q
Quleaf 已提交
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
            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::

Q
Quleaf 已提交
3180 3181 3182 3183 3184
            E_0 = \sqrt{p}
            \begin{bmatrix}
                1 & 0 \\
                0 & \sqrt{1-\gamma}
            \end{bmatrix},
Q
Quleaf 已提交
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
            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 已提交
3204
            cir.cnot([0, 1])
Q
Quleaf 已提交
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
            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::

Q
Quleaf 已提交
3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
            E_0 =
            \begin{bmatrix}
                1 & 0 \\
                0 & \sqrt{1-\gamma}
            \end{bmatrix},
            E_1 =
            \begin{bmatrix}
                0 & 0 \\
                0 & \sqrt{\gamma}
            \end{bmatrix}.
Q
Quleaf 已提交
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257

        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 已提交
3258
            cir.cnot([0, 1])
Q
Quleaf 已提交
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
            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 已提交
3301
            cir.cnot([0, 1])
Q
Quleaf 已提交
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
            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]'

Q
Quleaf 已提交
3315
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
        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 已提交
3344
            cir.cnot([0, 1])
Q
Quleaf 已提交
3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
            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]'

Q
Quleaf 已提交
3358
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
        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 已提交
3387
            cir.cnot([0, 1])
Q
Quleaf 已提交
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
            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]'

Q
Quleaf 已提交
3401
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
        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 已提交
3432
            cir.cnot([0, 1])
Q
Quleaf 已提交
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
            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]'

Q
Quleaf 已提交
3446 3447 3448 3449
        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')
Q
Quleaf 已提交
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476

        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 已提交
3477
            cir.cnot([0, 1])
Q
Quleaf 已提交
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
            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 已提交
3504 3505 3506
    @apply_channel
    def reset(self, p, q, which_qubit):
        r"""添加重置信道。有 p 的概率将量子态重置为 :math:`|0\rangle` 并有 q 的概率重置为 :math:`|1\rangle`。
Q
Quleaf 已提交
3507

Q
Quleaf 已提交
3508
        其 Kraus 算符为:
Q
Quleaf 已提交
3509

Q
Quleaf 已提交
3510
        .. math::
Q
Quleaf 已提交
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531

            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},\\
Q
Quleaf 已提交
3532
            E_4 = \sqrt{1-p-q} I.
Q
Quleaf 已提交
3533

Q
Quleaf 已提交
3534 3535 3536 3537
        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` 为该量子电路的量子比特数
Q
Quleaf 已提交
3538

Q
Quleaf 已提交
3539 3540
        Note:
            两个输入的概率加起来需要小于等于 1。
Q
Quleaf 已提交
3541

Q
Quleaf 已提交
3542
        代码示例:
Q
Quleaf 已提交
3543

Q
Quleaf 已提交
3544
        .. code-block:: python
Q
Quleaf 已提交
3545

Q
Quleaf 已提交
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
            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())
Q
Quleaf 已提交
3556

Q
Quleaf 已提交
3557
        ::
Q
Quleaf 已提交
3558

Q
Quleaf 已提交
3559 3560 3561 3562 3563 3564
            [[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 '
Q
Quleaf 已提交
3565

Q
Quleaf 已提交
3566 3567 3568 3569 3570
        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')
Q
Quleaf 已提交
3571

Q
Quleaf 已提交
3572
        return [e0, e1, e2, e3, e4]
Q
Quleaf 已提交
3573

Q
Quleaf 已提交
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
    @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!'
Q
Quleaf 已提交
3614

Q
Quleaf 已提交
3615 3616 3617
        # Change time scale
        time = time / 1000
        # Probability of resetting the state to |0>
Q
Quleaf 已提交
3618
        p_reset = 1 - np.exp(-time / t1)
Q
Quleaf 已提交
3619
        # Probability of phase flip
Q
Quleaf 已提交
3620
        p_z = (1 - p_reset) * (1 - np.exp(-time / t2) * np.exp(time / t1)) / 2
Q
Quleaf 已提交
3621
        # Probability of identity
Q
Quleaf 已提交
3622 3623
        p_i = 1 - p_reset - p_z

Q
Quleaf 已提交
3624 3625 3626 3627
        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')
Q
Quleaf 已提交
3628

Q
Quleaf 已提交
3629
        return [e0, e1, e2, e3]
Q
Quleaf 已提交
3630

Q
Quleaf 已提交
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
    @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 已提交
3650
            cir.cnot([0, 1])
Q
Quleaf 已提交
3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667
            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)
Q
Quleaf 已提交
3668 3669
        assert np.allclose(completeness.numpy(),
                           np.eye(2, dtype='complex128')), 'Kraus operators should satisfy completeness.'
Q
Quleaf 已提交
3670 3671 3672

        return ops

Q
Quleaf 已提交
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
    def shadow_trace(self, hamiltonian, sample_shots, method='CS'):
        r"""估计可观测量 :math:`H` 的期望值 :math:`\text{trace}(H\rho)` 。

        Args:
            hamiltonian (Hamiltonian): 可观测量
            sample_shots (int): 采样次数
            method (str, optional): 使用 shadow 来进行估计的方法,可选 "CS"、"LBCS"、"APS" 三种方法,默认为 "CS"

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            from paddle_quantum.utils import Hamiltonian
            from paddle_quantum.state import vec_random

            n_qubit = 2
            sample_shots = 1000
            state = vec_random(n_qubit)
            ham = [[0.1, 'x1'], [0.2, 'y0']]
            ham = Hamiltonian(ham)

            cir = UAnsatz(n_qubit)
            input_state = cir.run_state_vector(paddle.to_tensor(state))
            trace_cs = cir.shadow_trace(ham, sample_shots, method="CS")
            trace_lbcs = cir.shadow_trace(ham, sample_shots, method="LBCS")
            trace_aps = cir.shadow_trace(ham, sample_shots, method="APS")

            print('trace CS = ', trace_cs)
            print('trace LBCS = ', trace_lbcs)
            print('trace APS = ', trace_aps)

        ::

            trace CS =  -0.09570000000000002
            trace LBCS =  -0.0946048044954126
            trace APS =  -0.08640438803809354
        """
        if not isinstance(hamiltonian, list):
            hamiltonian = hamiltonian.pauli_str
        state = self.__state
        num_qubits = self.n
        mode = self.__run_mode
        if method == "LBCS":
            result, beta = shadow.shadow_sample(state, num_qubits, sample_shots, mode, hamiltonian, method)
        else:
            result = shadow.shadow_sample(state, num_qubits, sample_shots, mode, hamiltonian, method)

        def prepare_hamiltonian(hamiltonian, num_qubits):
            r"""改写可观测量 ``[[0.3147,'y2'], [-0.5484158742278,'x2,z1'],...]`` 的形式

            Args:
                hamiltonian (list): 可观测量的相关信息
                num_qubits (int): 量子比特数目

            Returns:
                list: 可观测量的形式改写为[[0.3147,'iiy'], [-0.5484158742278,'izx'],...]

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            new_hamiltonian = list()
            for idx, (coeff, pauli_str) in enumerate(hamiltonian):
                pauli_str = re.split(r',\s*', pauli_str.lower())
                pauli_term = ['i'] * num_qubits
                for item in pauli_str:
                    if len(item) > 1:
                        pauli_term[int(item[1:])] = item[0]
                    elif item[0].lower() != 'i':
                        raise ValueError('Expecting I for ', item[0])
                new_term = [coeff, ''.join(pauli_term)]
                new_hamiltonian.append(new_term)
            return new_hamiltonian

        hamiltonian = prepare_hamiltonian(hamiltonian, num_qubits)

        sample_pauli_str = [item for item, _ in result]
        sample_measurement_result = [item for _, item in result]
        coeff_terms = list()
        pauli_terms = list()
        for coeff, pauli_term in hamiltonian:
            coeff_terms.append(coeff)
            pauli_terms.append(pauli_term)

        pauli2idx = {'x': 0, 'y': 1, 'z': 2}

        def estimated_weight_cs(sample_pauli_str, pauli_term):
            r"""定义 CS 算法中的对测量的权重估计函数

            Args:
                sample_pauli_str (str): 随机选择的 pauli 项
                pauli_term (str): 可观测量的 pauli 项

            Returns:
                int: 返回估计的权重值

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            result = 1
            for i in range(num_qubits):
                if sample_pauli_str[i] == 'i' or pauli_term[i] == 'i':
                    continue
                elif sample_pauli_str[i] == pauli_term[i]:
                    result *= 3
                else:
                    result = 0
            return result

        def estimated_weight_lbcs(sample_pauli_str, pauli_term, beta):
            r"""定义 LBCS 算法中的权重估计函数

            Args:
                sample_pauli_str (str): 随机选择的 pauli 项
                pauli_term (str): 可观测量的 pauli 项
                beta (list): 所有量子位上关于 pauli 的概率分布

            Returns:
                float: 返回函数数值

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            # beta is 2-d, and the shape looks like (len, 3)
            assert len(sample_pauli_str) == len(pauli_term)
            result = 1
            for i in range(num_qubits):
                # The probability distribution is different at each qubit
                score = 0
                idx = pauli2idx[sample_pauli_str[i]]
                if sample_pauli_str[i] == 'i' or pauli_term[i] == 'i':
                    score = 1
                elif sample_pauli_str[i] == pauli_term[i] and beta[i][idx] != 0:
                    score = 1 / beta[i][idx]
                result *= score
            return result

        def estimated_value(pauli_term, measurement_result):
            r"""满足条件的测量结果本征值的乘积

            Args:
                pauli_term (str): 可观测量的 pauli 项
                measurement_result (list): 测量结果

            Returns:
                int: 返回测量结果本征值的乘积

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            value = 1
            for idx in range(num_qubits):
                if pauli_term[idx] != 'i' and measurement_result[idx] == '1':
                    value *= -1
            return value

        # Define the functions required by APS
        def is_covered(pauli, pauli_str):
            r"""判断可观测量的 pauli 项是否被随机选择的 pauli 项所覆盖

            Args:
                pauli (str): 可观测量的 pauli 项
                pauli_str (str): 随机选择的 pauli 项

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            for qubit_idx in range(num_qubits):
                if not pauli[qubit_idx] in ('i', pauli_str[qubit_idx]):
                    return False
            return True

        def update_pauli_estimator(hamiltonian, pauli_estimator, pauli_str, measurement_result):
            r"""用于更新 APS 算法下当前可观测量 pauli 项 P 的最佳估计 tr( P \rho),及 P 被覆盖的次数

            Args:
                hamiltonian (list): 可观测量的相关信息
                pauli_estimator (dict): 用于记录最佳估计与被覆盖次数
                pauli_str (list): 随机选择的 pauli 项
                measurement_result (list): 对随机选择的 pauli 项测量得到的结果

            Note:
                这是内部函数,你并不需要直接调用到该函数。
            """
            for coeff, pauli_term in hamiltonian:
                last_estimator = pauli_estimator[pauli_term]['value'][-1]
                if is_covered(pauli_term, pauli_str):
                    value = estimated_value(pauli_term, measurement_result)  
                    chose_number = pauli_estimator[pauli_term]['times']
                    new_estimator = 1 / (chose_number + 1) * (chose_number * last_estimator + value)
                    pauli_estimator[pauli_term]['times'] += 1
                    pauli_estimator[pauli_term]['value'].append(new_estimator)
                else:
                    pauli_estimator[pauli_term]['value'].append(last_estimator)

        trace_estimation = 0
        if method == "CS":
            for sample_idx in range(sample_shots):
                estimation = 0
                for i in range(len(pauli_terms)):
                    value = estimated_value(pauli_terms[i], sample_measurement_result[sample_idx])
                    weight = estimated_weight_cs(sample_pauli_str[sample_idx], pauli_terms[i])
                    estimation += coeff_terms[i] * weight * value
                trace_estimation += estimation
            trace_estimation /= sample_shots
        elif method == "LBCS":
            for sample_idx in range(sample_shots):
                estimation = 0
                for i in range(len(pauli_terms)):
                    value = estimated_value(pauli_terms[i], sample_measurement_result[sample_idx])
                    weight = estimated_weight_lbcs(sample_pauli_str[sample_idx], pauli_terms[i], beta)
                    estimation += coeff_terms[i] * weight * value
                trace_estimation += estimation
            trace_estimation /= sample_shots
        elif method == "APS":
            # Create a search dictionary for easy storage
            pauli_estimator = dict()
            for coeff, pauli_term in hamiltonian:
                pauli_estimator[pauli_term] = {'times': 0, 'value': [0]}
            for sample_idx in range(sample_shots):
                update_pauli_estimator(
                    hamiltonian,
                    pauli_estimator,
                    sample_pauli_str[sample_idx],
                    sample_measurement_result[sample_idx]
                )
            for sample_idx in range(sample_shots):
                estimation = 0
                for coeff, pauli_term in hamiltonian:
                    estimation += coeff * pauli_estimator[pauli_term]['value'][sample_idx + 1]
                trace_estimation = estimation

        return trace_estimation

Q
Quleaf 已提交
3908

Q
Quleaf 已提交
3909
def _local_H_prob(cir, hamiltonian, shots=1024):
Q
Quleaf 已提交
3910
    r"""
Q
Quleaf 已提交
3911
    构造出 Pauli 测量电路并测量 ancilla,处理实验结果来得到 ``H`` (只有一项)期望值的实验测量值。
Q
Quleaf 已提交
3912 3913 3914 3915 3916 3917

    Note:
        这是内部函数,你并不需要直接调用到该函数。
    """
    # Add one ancilla, which we later measure and process the result
    new_cir = UAnsatz(cir.n + 1)
Q
Quleaf 已提交
3918
    input_state = paddle.kron(cir.run_state_vector(store_state=False), init_state_gen(1))
Q
Quleaf 已提交
3919
    # Used in fixed Rz gate
Q
Quleaf 已提交
3920
    _theta = paddle.to_tensor(np.array([-np.pi / 2]))
Q
Quleaf 已提交
3921 3922 3923 3924 3925

    op_list = hamiltonian.split(',')
    # Set up pauli measurement circuit
    for op in op_list:
        element = op[0]
Q
Quleaf 已提交
3926 3927 3928 3929 3930
        if len(op) > 1:
            index = int(op[1:])
        elif op[0].lower() != 'i':
            raise ValueError('Expecting {} to be {}'.format(op, 'I'))
        if element.lower() == 'x':
Q
Quleaf 已提交
3931 3932
            new_cir.h(index)
            new_cir.cnot([index, cir.n])
Q
Quleaf 已提交
3933
        elif element.lower() == 'z':
Q
Quleaf 已提交
3934
            new_cir.cnot([index, cir.n])
Q
Quleaf 已提交
3935
        elif element.lower() == 'y':
Q
Quleaf 已提交
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946
            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:
Q
Quleaf 已提交
3947
                result = -(prob_result['1']) / shots
Q
Quleaf 已提交
3948 3949 3950 3951 3952 3953 3954 3955
        else:
            result = (prob_result['0'] - prob_result['1']) / shots
    else:
        result = (prob_result['0'] - prob_result['1'])

    return result


Q
Quleaf 已提交
3956 3957
def swap_test(n):
    r"""构造用 Swap Test 测量两个量子态之间差异的电路。
Q
Quleaf 已提交
3958

Q
Quleaf 已提交
3959
    Args:
Q
Quleaf 已提交
3960
        n (int): 待比较的两个态的量子比特数
Q
Quleaf 已提交
3961

Q
Quleaf 已提交
3962
    Returns:
Q
Quleaf 已提交
3963 3964
        UAnsatz: Swap Test 的电路

Q
Quleaf 已提交
3965 3966 3967
    代码示例:

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

Q
Quleaf 已提交
3969
        import paddle
Q
Quleaf 已提交
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
        import numpy as np
        from paddle_quantum.state import vec
        from paddle_quantum.circuit import UAnsatz, swap_test
        from paddle_quantum.utils import NKron

        n = 2
        ancilla = vec(0, 1)
        psi = vec(1, n)
        phi = vec(0, n)
        input_state = NKron(ancilla, psi, phi)

        cir = swap_test(n)
        cir.run_state_vector(paddle.to_tensor(input_state))
        result = cir.measure(which_qubits=[0], shots=8192, plot=True)
        probability = result['0'] / 8192
        inner_product = (probability - 0.5) * 2
        print(f"The inner product is {inner_product}")
Q
Quleaf 已提交
3987 3988 3989

    ::

Q
Quleaf 已提交
3990
        The inner product is 0.006591796875
Q
Quleaf 已提交
3991
    """
Q
Quleaf 已提交
3992 3993 3994 3995 3996 3997 3998
    cir = UAnsatz(2 * n + 1)
    cir.h(0)
    for i in range(n):
        cir.cswap([0, i + 1, i + n + 1])
    cir.h(0)

    return cir