circuit.py 152.5 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 29
from paddle_quantum.intrinsic import *
from paddle_quantum.state import density_op
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 63 64 65 66 67 68 69 70
        
    def expand(self,new_n):
        """
        为原来的量子电路进行比特数扩展

        Args:
            new_n(int):扩展后的量子比特数
        """
        self.n = new_n
Q
Quleaf 已提交
71 72 73 74 75 76 77 78 79

    def __add__(self, cir):
        r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路

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

        .. 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 已提交
213 214
    def _count_history(self):
        r"""calculate how many blocks needed for printing
Q
Quleaf 已提交
215

Q
Quleaf 已提交
216
        Note:
Q
Quleaf 已提交
217
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
218 219 220 221 222 223 224 225 226 227 228
        """
        # 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 已提交
229

Q
Quleaf 已提交
230 231
        for current_gate in history:
            # Single-qubit gates with no params to print
Q
Quleaf 已提交
232 233
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u', 'sdg', 'tdg'}:
                curr_qubit = current_gate['which_qubits'][0]
Q
Quleaf 已提交
234 235 236 237 238 239 240
                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 已提交
241 242
            elif current_gate['gate'] in {'rx', 'ry', 'rz'}:
                curr_qubit = current_gate['which_qubits'][0]
Q
Quleaf 已提交
243 244 245 246 247 248 249
                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 已提交
250 251 252 253 254
            # 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 已提交
255 256
                ind = max(qubit[b: a + 1])
                gate.append(ind)
Q
Quleaf 已提交
257 258
                if length[ind] < 13 and current_gate['gate'] in {'RXX_gate', 'RYY_gate', 'RZZ_gate', 'crx', 'cry',
                                                                 'crz'}:
Q
Quleaf 已提交
259 260 261 262 263 264
                    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 已提交
265

Q
Quleaf 已提交
266
        return length, gate
Q
Quleaf 已提交
267

Q
Quleaf 已提交
268 269
    def __str__(self):
        r"""实现画电路的功能
Q
Quleaf 已提交
270

Q
Quleaf 已提交
271 272
        Returns:
            string: 用来print的字符串
Q
Quleaf 已提交
273

Q
Quleaf 已提交
274 275 276 277 278 279 280
        代码示例:

        .. code-block:: python

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

Q
Quleaf 已提交
282 283 284 285
            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 已提交
286

Q
Quleaf 已提交
287 288
            print(cir)
        ::
Q
Quleaf 已提交
289

Q
Quleaf 已提交
290
            The printed circuit is:
Q
Quleaf 已提交
291

Q
Quleaf 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304
            --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 已提交
305
        # Ignore the unused section
Q
Quleaf 已提交
306
        total_length = sum(length) - 5
Q
Quleaf 已提交
307

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

        for i, current_gate in enumerate(history):
Q
Quleaf 已提交
311
            if current_gate['gate'] in {'h', 's', 't', 'x', 'y', 'z', 'u'}:
Q
Quleaf 已提交
312 313 314
                # Calculate starting position ind of current gate
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
315 316 317 318 319 320 321 322 323 324 325 326
                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 已提交
327 328
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
329 330
                line = current_gate['which_qubits'][0] * 2
                param = self.__param[current_gate['theta'][2 if current_gate['gate'] == 'rz' else 0]]
Q
Quleaf 已提交
331
                print_list[line][ind + 2] = 'R'
Q
Quleaf 已提交
332
                print_list[line][ind + 3] = current_gate['gate'][1]
Q
Quleaf 已提交
333 334 335
                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 已提交
336 337 338
            # 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 已提交
339 340
                sec = gate[i]
                ind = sum(length[:sec])
Q
Quleaf 已提交
341 342 343 344 345 346 347 348
                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 已提交
349 350 351 352
                    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 已提交
353 354
                elif current_gate['gate'] in {'RXX_gate', 'RYY_gate', 'RZZ_gate'}:
                    param = self.__param[current_gate['theta'][0]]
Q
Quleaf 已提交
355 356
                    for line in {cqubit * 2, tqubit * 2}:
                        print_list[line][ind + 2] = 'R'
Q
Quleaf 已提交
357
                        print_list[line][ind + 3: ind + 5] = current_gate['gate'][1:3].lower()
Q
Quleaf 已提交
358 359 360
                        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 已提交
361 362 363 364 365 366 367 368
                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 已提交
369 370 371 372
                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 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
            # 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 已提交
402 403 404 405 406

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

        return return_str
Q
Quleaf 已提交
407

Q
Quleaf 已提交
408
    def run_state_vector(self, input_state=None, store_state=True):
Q
Quleaf 已提交
409 410 411 412
        r"""运行当前的量子电路,输入输出的形式为态矢量。

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

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

Q
Quleaf 已提交
418
        Returns:
Q
Quleaf 已提交
419
            Tensor: 量子电路输出的态矢量
Q
Quleaf 已提交
420

Q
Quleaf 已提交
421
        代码示例:
Q
Quleaf 已提交
422

Q
Quleaf 已提交
423
        .. code-block:: python
Q
Quleaf 已提交
424

Q
Quleaf 已提交
425
            import numpy as np
Q
Quleaf 已提交
426
            import paddle
Q
Quleaf 已提交
427
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
428
            from paddle_quantum.state import vec
Q
Quleaf 已提交
429 430
            n = 2
            theta = np.ones(3)
Q
Quleaf 已提交
431

Q
Quleaf 已提交
432
            input_state = paddle.to_tensor(vec(0, n))
Q
Quleaf 已提交
433 434 435 436 437 438 439
            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 已提交
440

Q
Quleaf 已提交
441
        ::
Q
Quleaf 已提交
442

Q
Quleaf 已提交
443
            The output state vector is [[0.62054458+0.j 0.18316521+0.28526291j 0.62054458+0.j 0.18316521+0.28526291j]]
Q
Quleaf 已提交
444
        """
Q
Quleaf 已提交
445
        # Throw a warning when cir has channel
Q
Quleaf 已提交
446
        if self.__has_channel:
Q
Quleaf 已提交
447
            warnings.warn('The noiseless circuit will be run.', RuntimeWarning)
Q
Quleaf 已提交
448 449
        state = init_state_gen(self.n, 0) if input_state is None else input_state
        old_shape = state.shape
Q
Quleaf 已提交
450 451
        assert reduce(lambda x, y: x * y, old_shape) == 2 ** self.n, \
            'The length of the input vector is not right'
Q
Quleaf 已提交
452
        state = reshape(state, (2 ** self.n,))
Q
Quleaf 已提交
453

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

Q
Quleaf 已提交
458
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
459 460 461 462

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

Q
Quleaf 已提交
465
        return reshape(state, old_shape)
Q
Quleaf 已提交
466 467

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

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

Q
Quleaf 已提交
474
        Returns:
Q
Quleaf 已提交
475
            Tensor: 量子电路输出的密度矩阵
Q
Quleaf 已提交
476 477 478 479

        代码示例:

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

Q
Quleaf 已提交
481
            import numpy as np
Q
Quleaf 已提交
482
            import paddle
Q
Quleaf 已提交
483
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
484
            from paddle_quantum.state import density_op
Q
Quleaf 已提交
485 486
            n = 1
            theta = np.ones(3)
Q
Quleaf 已提交
487 488 489 490 491 492 493 494 495

            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 已提交
496 497 498

        ::

Q
Quleaf 已提交
499
            The output density matrix is
Q
Quleaf 已提交
500 501
            [[0.64596329+0.j         0.47686058+0.03603751j]
            [0.47686058-0.03603751j 0.35403671+0.j        ]]
Q
Quleaf 已提交
502
        """
Q
Quleaf 已提交
503
        state = paddle.to_tensor(density_op(self.n)) if input_state is None else input_state
Q
Quleaf 已提交
504 505
        assert state.shape == [2 ** self.n, 2 ** self.n], \
            "The dimension is not right"
Q
Quleaf 已提交
506

Q
Quleaf 已提交
507
        if not self.__has_channel:
Q
Quleaf 已提交
508 509 510 511 512 513 514 515 516 517
            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 已提交
518
            i = 0
Q
Quleaf 已提交
519
            for i, history_ele in enumerate(self.__history):
Q
Quleaf 已提交
520
                if history_ele['gate'] == 'channel':
Q
Quleaf 已提交
521
                    # Combine preceding unitary operations
Q
Quleaf 已提交
522
                    unitary = transfer_by_history(identity, self.__history[u_start:i], self.__param)
Q
Quleaf 已提交
523
                    sub_state = paddle.zeros(shape, dtype='complex128')
Q
Quleaf 已提交
524
                    # Sum all the terms corresponding to different Kraus operators
Q
Quleaf 已提交
525 526 527
                    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 已提交
528 529 530
                    state = sub_state
                    u_start = i + 1
            # Apply unitary operations left
Q
Quleaf 已提交
531
            unitary = reshape(transfer_by_history(identity, self.__history[u_start:(i + 1)], self.__param), shape)
Q
Quleaf 已提交
532
            state = matmul(unitary, matmul(state, dagger(unitary)))
Q
Quleaf 已提交
533

Q
Quleaf 已提交
534 535 536
        if store_state:
            self.__state = state
            # Add info about which function user called
Q
Quleaf 已提交
537
            self.__run_mode = 'density_matrix'
Q
Quleaf 已提交
538 539 540

        return state

Q
Quleaf 已提交
541 542 543 544 545 546
    def reset_state(self, state, which_qubits):
        r"""对当前电路中的量子态的部分量子比特进行重置。

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

        Returns:
            paddle.Tensor: 重置后的量子态
Q
Quleaf 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
        """
        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 已提交
592
        return _state
Q
Quleaf 已提交
593

Q
Quleaf 已提交
594 595
    @property
    def U(self):
Q
Quleaf 已提交
596 597 598 599
        r"""量子电路的酉矩阵形式。

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

Q
Quleaf 已提交
601
        Returns:
Q
Quleaf 已提交
602
            Tensor: 当前电路的酉矩阵表示
Q
Quleaf 已提交
603 604 605 606

        代码示例:

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

Q
Quleaf 已提交
608
            import paddle
Q
Quleaf 已提交
609 610
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
611 612 613 614 615
            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 已提交
616 617 618

        ::

Q
Quleaf 已提交
619
            The unitary matrix of the circuit for Bell state preparation is
Q
Quleaf 已提交
620 621 622 623
            [[ 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 已提交
624
        """
Q
Quleaf 已提交
625
        # Throw a warning when cir has channel
Q
Quleaf 已提交
626
        if self.__has_channel:
Q
Quleaf 已提交
627 628 629 630 631
            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 已提交
632
        state = paddle.cast(state, 'complex128')
Q
Quleaf 已提交
633
        state = reshape(state, [num_ele])
Q
Quleaf 已提交
634
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
635

Q
Quleaf 已提交
636
        return reshape(state, shape)
Q
Quleaf 已提交
637

Q
Quleaf 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    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 已提交
662 663 664 665 666 667 668
        r"""将输入的经典数据使用基态编码的方式编码成量子态。

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

        Args:
            x (Tensor): 待编码的向量
Q
Quleaf 已提交
669
            which_qubits (list): 用于编码的量子比特
Q
Quleaf 已提交
670 671 672 673
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
        x = paddle.flatten(x)
        x = paddle.cast(x, dtype="int32")
Q
Quleaf 已提交
674 675 676 677 678 679 680 681 682
        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 已提交
683 684
        for idx, element in enumerate(x):
            if element:
Q
Quleaf 已提交
685
                self.x(which_qubits[idx])
Q
Quleaf 已提交
686

Q
Quleaf 已提交
687
    def amplitude_encoding(self, x, mode, which_qubits=None):
Q
Quleaf 已提交
688 689 690 691 692
        r"""将输入的经典数据使用振幅编码的方式编码成量子态。

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

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

Q
Quleaf 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        代码示例:

        .. 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 已提交
716
        """
Q
Quleaf 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
        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 已提交
774 775
        x = paddle.flatten(x)
        length = paddle.norm(x, p=2)
Q
Quleaf 已提交
776
        # Normalization
Q
Quleaf 已提交
777
        x = paddle.divide(x, length)
Q
Quleaf 已提交
778 779 780 781 782 783 784
        # 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 已提交
785
        if mode == "state_vector":
Q
Quleaf 已提交
786
            result_tensor = paddle.cast(result_tensor, dtype="complex128")
Q
Quleaf 已提交
787
        elif mode == "density_matrix":
Q
Quleaf 已提交
788 789
            result_tensor = paddle.reshape(result_tensor, (2 ** self.n, 1))
            result_tensor = matmul(result_tensor, dagger(result_tensor))
Q
Quleaf 已提交
790 791 792
        else:
            raise ValueError("the mode should be state_vector or density_matrix")

Q
Quleaf 已提交
793 794 795
        return result_tensor

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

        Args:
            x (Tensor): 待编码的向量
            encoding_gate (str): 编码要用的量子门,可以是 ``"rx"`` 、 ``"ry"`` 和 ``"rz"``
Q
Quleaf 已提交
801
            which_qubits (list): 用于编码的量子比特
Q
Quleaf 已提交
802 803
            invert (bool): 添加的是否为编码电路的逆电路,默认为 ``False`` ,即添加正常的编码电路
        """
Q
Quleaf 已提交
804 805 806 807 808 809 810 811 812
        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 已提交
813 814 815 816
        x = paddle.flatten(x)
        if invert:
            x = -x

Q
Quleaf 已提交
817
        def add_encoding_gate(theta, which, gate):
Q
Quleaf 已提交
818
            if gate == "rx":
Q
Quleaf 已提交
819
                self.rx(theta, which)
Q
Quleaf 已提交
820
            elif gate == "ry":
Q
Quleaf 已提交
821
                self.ry(theta, which)
Q
Quleaf 已提交
822
            elif gate == "rz":
Q
Quleaf 已提交
823
                self.rz(theta, which)
Q
Quleaf 已提交
824 825 826 827
            else:
                raise ValueError("the encoding_gate should be rx, ry, or rz")

        for idx, element in enumerate(x):
Q
Quleaf 已提交
828
            add_encoding_gate(element[0], which_qubits[idx], encoding_gate)
Q
Quleaf 已提交
829 830 831 832 833 834 835 836 837 838

    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 已提交
839 840
        assert x.size <= self.n, \
            "the number of classical data should be equal to the number of qubits"
Q
Quleaf 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853
        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 已提交
854
                    self.rz(-x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
855 856 857 858 859 860 861 862 863 864 865 866
                    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 已提交
867
                    self.rz(x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
868 869
                    self.cnot(list(item))

Q
Quleaf 已提交
870
    """
Q
Quleaf 已提交
871
    Common Gates
Q
Quleaf 已提交
872 873
    """

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

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

Q
Quleaf 已提交
879
        .. math::
Q
Quleaf 已提交
880 881 882 883 884

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

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

Q
Quleaf 已提交
890 891 892
        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
893
            import paddle
Q
Quleaf 已提交
894 895
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
896 897 898 899 900 901
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rx(theta[0], which_qubit)

Q
Quleaf 已提交
902
        """
Q
Quleaf 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
        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 已提交
951 952

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

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

Q
Quleaf 已提交
957
        .. math::
Q
Quleaf 已提交
958 959 960 961 962

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

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

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

Q
Quleaf 已提交
970
            import numpy as np
Q
Quleaf 已提交
971
            import paddle
Q
Quleaf 已提交
972 973
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
974 975 976 977 978
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.ry(theta[0], which_qubit)
Q
Quleaf 已提交
979
        """
Q
Quleaf 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        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 已提交
1027 1028

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

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

Q
Quleaf 已提交
1033
        .. math::
Q
Quleaf 已提交
1034

Q
Quleaf 已提交
1035 1036 1037 1038
            \begin{bmatrix}
                1 & 0 \\
                0 & e^{i\theta}
            \end{bmatrix}
Q
Quleaf 已提交
1039

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

Q
Quleaf 已提交
1044
        ..  code-block:: python
Q
Quleaf 已提交
1045

Q
Quleaf 已提交
1046
            import numpy as np
Q
Quleaf 已提交
1047
            import paddle
Q
Quleaf 已提交
1048 1049
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
1050 1051 1052 1053 1054
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rz(theta[0], which_qubit)
Q
Quleaf 已提交
1055
        """
Q
Quleaf 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        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 已提交
1103 1104

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

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

Q
Quleaf 已提交
1109
        .. math::
Q
Quleaf 已提交
1110

Q
Quleaf 已提交
1111
            \begin{align}
Q
Quleaf 已提交
1112 1113 1114 1115 1116 1117 1118 1119
                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 已提交
1120
            \end{align}
Q
Quleaf 已提交
1121

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

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

Q
Quleaf 已提交
1128
            import numpy as np
Q
Quleaf 已提交
1129
            import paddle
Q
Quleaf 已提交
1130 1131
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
1132 1133
            cir = UAnsatz(num_qubits)
            cir.cnot([0, 1])
Q
Quleaf 已提交
1134
        """
Q
Quleaf 已提交
1135
        assert 0 <= control[0] < self.n and 0 <= control[1] < self.n, \
Q
Quleaf 已提交
1136
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        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 已提交
1256

Q
Quleaf 已提交
1257 1258 1259 1260 1261 1262 1263 1264
    def swap(self, control):
        r"""添加一个 SWAP 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1265 1266 1267 1268 1269 1270 1271
                SWAP =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 1
                \end{bmatrix}
Q
Quleaf 已提交
1272 1273 1274
            \end{align}

        Args:
Q
Quleaf 已提交
1275 1276
            control (list): 作用在的量子比特的编号,``control[0]`` 和 ``control[1]`` 是想要交换的位,
                其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1277 1278 1279 1280

        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
1281
            import paddle
Q
Quleaf 已提交
1282 1283
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
Q
Quleaf 已提交
1284 1285
            cir = UAnsatz(num_qubits)
            cir.swap([0, 1])
Q
Quleaf 已提交
1286
        """
Q
Quleaf 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        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 已提交
1369
            "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1370 1371 1372 1373 1374
        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 已提交
1375

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

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

Q
Quleaf 已提交
1381
        .. math::
Q
Quleaf 已提交
1382 1383 1384 1385 1386

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

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

Q
Quleaf 已提交
1391
        .. code-block:: python
Q
Quleaf 已提交
1392

Q
Quleaf 已提交
1393
            import paddle
Q
Quleaf 已提交
1394
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
            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 已提交
1405
        """
Q
Quleaf 已提交
1406
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1407
        self.__history.append({'gate': 'x', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1408 1409

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

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

Q
Quleaf 已提交
1414
        .. math::
Q
Quleaf 已提交
1415 1416 1417 1418 1419

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

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

Q
Quleaf 已提交
1424
        .. code-block:: python
Q
Quleaf 已提交
1425

Q
Quleaf 已提交
1426
            import paddle
Q
Quleaf 已提交
1427
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
            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 已提交
1438
        """
Q
Quleaf 已提交
1439
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1440
        self.__history.append({'gate': 'y', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1441 1442

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

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

Q
Quleaf 已提交
1447
        .. math::
Q
Quleaf 已提交
1448 1449 1450 1451 1452

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

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

Q
Quleaf 已提交
1457
        .. code-block:: python
Q
Quleaf 已提交
1458

Q
Quleaf 已提交
1459
            import paddle
Q
Quleaf 已提交
1460
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
            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 已提交
1471
        """
Q
Quleaf 已提交
1472
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1473
        self.__history.append({'gate': 'z', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1474 1475

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

Q
Quleaf 已提交
1478
        其矩阵形式为:
Q
Quleaf 已提交
1479 1480

        .. math::
Q
Quleaf 已提交
1481 1482 1483 1484 1485 1486

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

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

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

Q
Quleaf 已提交
1497
        其矩阵形式为:
Q
Quleaf 已提交
1498 1499

        .. math::
Q
Quleaf 已提交
1500 1501 1502 1503 1504 1505

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

        Args:
Q
Quleaf 已提交
1508
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1509
        """
Q
Quleaf 已提交
1510
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
        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 已提交
1531 1532

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

Q
Quleaf 已提交
1535
        其矩阵形式为:
Q
Quleaf 已提交
1536 1537 1538

        .. math::

Q
Quleaf 已提交
1539 1540 1541 1542 1543
            T =
                \begin{bmatrix}
                    1&0\\
                    0&e^\frac{i\pi}{4}
                \end{bmatrix}
Q
Quleaf 已提交
1544

Q
Quleaf 已提交
1545
        Args:
Q
Quleaf 已提交
1546
            which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1547
        """
Q
Quleaf 已提交
1548
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
        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 已提交
1569 1570 1571 1572

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

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

Q
Quleaf 已提交
1575
        .. math::
Q
Quleaf 已提交
1576

Q
Quleaf 已提交
1577
            \begin{align}
Q
Quleaf 已提交
1578 1579 1580 1581 1582
                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 已提交
1583 1584 1585
            \end{align}

        Args:
Q
Quleaf 已提交
1586 1587 1588
              theta (Tensor): 旋转角度 :math:`\theta` 。
              phi (Tensor): 旋转角度 :math:`\phi` 。
              lam (Tensor): 旋转角度 :math:`\lambda` 。
Q
Quleaf 已提交
1589
              which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1590
        """
Q
Quleaf 已提交
1591
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1592 1593 1594 1595
        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 已提交
1596

Q
Quleaf 已提交
1597 1598 1599 1600 1601 1602 1603 1604
    def rxx(self, theta, which_qubits):
        r"""添加一个 RXX 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1605 1606 1607 1608 1609 1610 1611
                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 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
            \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 已提交
1630 1631 1632
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RXX_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1633 1634 1635 1636 1637 1638 1639 1640 1641

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1642 1643 1644 1645 1646 1647 1648
                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 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
            \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 已提交
1667 1668 1669
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RYY_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1670 1671 1672 1673 1674 1675 1676 1677 1678

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1679 1680 1681 1682 1683 1684 1685
                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 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
            \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 已提交
1704 1705 1706
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RZZ_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1716 1717 1718 1719 1720 1721 1722
                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 已提交
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
            \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 已提交
1743
        self.__history.append({'gate': 'MS_gate', 'which_qubits': which_qubits, 'theta': [2]})
Q
Quleaf 已提交
1744

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

        Args:
Q
Quleaf 已提交
1749
            theta (Tensor): 2-qubit 通用门的参数,其维度为 ``(15, )``
Q
Quleaf 已提交
1750 1751 1752 1753 1754 1755 1756
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
1757
            import paddle
Q
Quleaf 已提交
1758 1759
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
1760 1761 1762 1763 1764
            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 已提交
1765 1766 1767 1768 1769

        ::

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

Q
Quleaf 已提交
1771 1772 1773 1774 1775
        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 已提交
1776

Q
Quleaf 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
        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 已提交
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 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
    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 已提交
2008

Q
Quleaf 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
        代码示例:

        .. 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 已提交
2066 2067

        Args:
Q
Quleaf 已提交
2068 2069 2070 2071 2072
            ind_history (int): 该门在本电路中的序号
            ind_gate (int): cu 门参数的 index,可以是 0 或 1 或 2

        Return:
            UAnsatz: 用电路表示的该门的一个参数的偏导
Q
Quleaf 已提交
2073 2074 2075 2076 2077 2078

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
2079
            import paddle
Q
Quleaf 已提交
2080
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2081 2082 2083 2084 2085
            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 已提交
2086 2087 2088

        ::

Q
Quleaf 已提交
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
            -----------------x--
                             |  
            ------------z----U--
                        |       
            --H---SDG---*----H--

            ------------z---------x--
                        |         |  
            ------------|----z----U--
                        |    |       
            --H----S----*----*----H--
Q
Quleaf 已提交
2100
        """
Q
Quleaf 已提交
2101 2102 2103 2104
        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 已提交
2105

Q
Quleaf 已提交
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 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
        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 已提交
2146

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

Q
Quleaf 已提交
2151 2152
        Return:
            Tensor: 该电路中所有需要训练的参数的梯度
Q
Quleaf 已提交
2153

Q
Quleaf 已提交
2154
        代码示例:
Q
Quleaf 已提交
2155

Q
Quleaf 已提交
2156
        .. code-block:: python
Q
Quleaf 已提交
2157

Q
Quleaf 已提交
2158 2159 2160
            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2161

Q
Quleaf 已提交
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 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
            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 已提交
2314

Q
Quleaf 已提交
2315
    """
Q
Quleaf 已提交
2316
    Measurements
Q
Quleaf 已提交
2317 2318
    """

Q
Quleaf 已提交
2319
    def __process_string(self, s, which_qubits):
Q
Quleaf 已提交
2320
        r"""该函数基于 which_qubits 返回 s 的一部分
Q
Quleaf 已提交
2321 2322
        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 已提交
2323

Q
Quleaf 已提交
2324 2325 2326 2327 2328
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        new_s = ''.join(s[j] for j in which_qubits)
        return new_s
Q
Quleaf 已提交
2329

Q
Quleaf 已提交
2330
    def __process_similiar(self, result):
Q
Quleaf 已提交
2331
        r"""该函数基于相同的键合并值。
Q
Quleaf 已提交
2332
        This functions merges values based on identical keys.
Q
Quleaf 已提交
2333 2334
        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 已提交
2335

Q
Quleaf 已提交
2336 2337 2338 2339 2340 2341
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        data = defaultdict(int)
        for idx, val in result:
            data[idx] += val
Q
Quleaf 已提交
2342

Q
Quleaf 已提交
2343
        return dict(data)
Q
Quleaf 已提交
2344

Q
Quleaf 已提交
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    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 已提交
2383
        r"""对量子电路输出的量子态进行测量。
Q
Quleaf 已提交
2384 2385

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

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

Q
Quleaf 已提交
2393 2394 2395 2396 2397 2398
        Returns:
            dict: 测量的结果

        代码示例:

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

Q
Quleaf 已提交
2400 2401
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2402 2403 2404 2405 2406 2407
            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 已提交
2408 2409 2410

        ::

Q
Quleaf 已提交
2411
            The results of measuring qubit 1 2048 times are {'0': 964, '1': 1084}
Q
Quleaf 已提交
2412 2413

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

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

        ::

Q
Quleaf 已提交
2426
            The probability distribution of measurement results on qubit 1 is {'0': 0.4999999999999999, '1': 0.4999999999999999}
Q
Quleaf 已提交
2427
        """
Q
Quleaf 已提交
2428
        if self.__run_mode == 'state_vector':
Q
Quleaf 已提交
2429
            state = self.__state
Q
Quleaf 已提交
2430
        elif self.__run_mode == 'density_matrix':
Q
Quleaf 已提交
2431 2432
            # Take the diagonal of the density matrix as a probability distribution
            diag = np.diag(self.__state.numpy())
Q
Quleaf 已提交
2433
            state = paddle.to_tensor(np.sqrt(diag))
Q
Quleaf 已提交
2434 2435 2436 2437 2438 2439 2440 2441
        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 已提交
2442
                result[dic10to2[i]] = (real(state)[i] ** 2 + imag(state)[i] ** 2).numpy()[0]
Q
Quleaf 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460

            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 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 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
    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 已提交
2513
        r"""量子电路输出的量子态关于可观测量 H 的期望值。
Q
Quleaf 已提交
2514 2515

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

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

Q
Quleaf 已提交
2523
        Returns:
Q
Quleaf 已提交
2524
            Tensor: 量子电路输出的量子态关于 ``H`` 的期望值
Q
Quleaf 已提交
2525 2526

        代码示例:
Q
Quleaf 已提交
2527

Q
Quleaf 已提交
2528
        .. code-block:: python
Q
Quleaf 已提交
2529 2530

            import numpy as np
Q
Quleaf 已提交
2531
            import paddle
Q
Quleaf 已提交
2532
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2533

Q
Quleaf 已提交
2534
            n = 5
Q
Quleaf 已提交
2535
            experiment_shots = 2**10
Q
Quleaf 已提交
2536
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
Q
Quleaf 已提交
2537
            theta = paddle.ones([3], dtype='float64')
Q
Quleaf 已提交
2538

Q
Quleaf 已提交
2539 2540 2541 2542 2543
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.rz(theta[1], 1)
            cir.rx(theta[2], 2)
            cir.run_state_vector()
Q
Quleaf 已提交
2544

Q
Quleaf 已提交
2545 2546 2547 2548 2549
            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 已提交
2550

Q
Quleaf 已提交
2551
        ::
Q
Quleaf 已提交
2552

Q
Quleaf 已提交
2553 2554
            The expectation value obtained by 1024 measurements is [-0.16328125]
            The accurate expectation value of H is [-0.1682942]
Q
Quleaf 已提交
2555
        """
Q
Quleaf 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
        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 已提交
2569
        else:
Q
Quleaf 已提交
2570 2571 2572 2573 2574
            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 已提交
2575 2576

    """
Q
Quleaf 已提交
2577
    Circuit Templates
Q
Quleaf 已提交
2578 2579
    """

Q
Quleaf 已提交
2580
    def superposition_layer(self):
Q
Quleaf 已提交
2581
        r"""添加一层 Hadamard 门。
Q
Quleaf 已提交
2582 2583 2584 2585

        代码示例:

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

Q
Quleaf 已提交
2587 2588
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2589 2590 2591 2592 2593
            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 已提交
2594 2595 2596

        ::

Q
Quleaf 已提交
2597 2598 2599
            The probability distribution of measurement results on both qubits is
                {'00': 0.2499999999999999, '01': 0.2499999999999999,
                '10': 0.2499999999999999, '11': 0.2499999999999999}
Q
Quleaf 已提交
2600
        """
Q
Quleaf 已提交
2601 2602 2603 2604
        for i in range(self.n):
            self.h(i)

    def weak_superposition_layer(self):
Q
Quleaf 已提交
2605
        r"""添加一层旋转角度为 :math:`\pi/4` 的 Ry 门。
Q
Quleaf 已提交
2606 2607 2608 2609

        代码示例:

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

Q
Quleaf 已提交
2611 2612
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2613 2614 2615 2616 2617
            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 已提交
2618 2619 2620

        ::

Q
Quleaf 已提交
2621 2622 2623
            The probability distribution of measurement results on both qubits is
                {'00': 0.7285533905932737, '01': 0.12500000000000003,
                '10': 0.12500000000000003, '11': 0.021446609406726238}
Q
Quleaf 已提交
2624
        """
Q
Quleaf 已提交
2625
        _theta = paddle.to_tensor(np.array([np.pi / 4]))  # Used in fixed Ry gate
Q
Quleaf 已提交
2626 2627
        for i in range(self.n):
            self.ry(_theta, i)
Q
Quleaf 已提交
2628

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

        Attention:
Q
Quleaf 已提交
2633
            ``theta`` 的维度为 ``(depth, n, 2)`` ,最低维内容为对应的 ``ry`` 和 ``rz`` 的参数, ``n`` 为作用的量子比特数量。
Q
Quleaf 已提交
2634 2635 2636 2637

        Args:
            theta (Tensor): Ry 门和 Rz 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2638
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2639 2640 2641 2642 2643 2644 2645 2646 2647

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2648
            theta = paddle.ones([DEPTH, 2, 2], dtype='float64')
Q
Quleaf 已提交
2649 2650 2651
            cir = UAnsatz(n)
            cir.linear_entangled_layer(theta, DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2652 2653
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")
Q
Quleaf 已提交
2654 2655 2656

        ::

Q
Quleaf 已提交
2657 2658 2659
            The probability distribution of measurement results on both qubits is
                {'00': 0.646611169077063, '01': 0.06790630495474384,
                '10': 0.19073671025717626, '11': 0.09474581571101756}
Q
Quleaf 已提交
2660
        """
Q
Quleaf 已提交
2661 2662 2663 2664 2665 2666
        # 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 已提交
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
        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 已提交
2686 2687
    def real_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 Ry 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
2688

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

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

Q
Quleaf 已提交
2695
        Args:
Q
Quleaf 已提交
2696
            theta (Tensor): Ry 门的旋转角度
Q
Quleaf 已提交
2697
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2698
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2699 2700 2701 2702

        代码示例:

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

Q
Quleaf 已提交
2704
            import paddle
Q
Quleaf 已提交
2705 2706 2707
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2708
            theta = paddle.ones([DEPTH, 2, 1], dtype='float64')
Q
Quleaf 已提交
2709 2710 2711
            cir = UAnsatz(n)
            cir.real_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2712 2713 2714
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2715 2716
        ::

Q
Quleaf 已提交
2717 2718 2719
            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 已提交
2720
        """
Q
Quleaf 已提交
2721 2722 2723 2724 2725 2726
        # 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 已提交
2727 2728 2729
        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 已提交
2730
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2731 2732
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'

Q
Quleaf 已提交
2733 2734 2735
        if which_qubits is None:
            which_qubits = np.arange(self.n)

Q
Quleaf 已提交
2736
        for repeat in range(depth):
Q
Quleaf 已提交
2737
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2738
                self.ry(theta[repeat][i][0], q)
Q
Quleaf 已提交
2739 2740 2741
            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 已提交
2742

Q
Quleaf 已提交
2743 2744
    def complex_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
2745 2746 2747

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

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

Q
Quleaf 已提交
2752
        Args:
Q
Quleaf 已提交
2753
            theta (Tensor): U3 门的旋转角度
Q
Quleaf 已提交
2754
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2755
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2756 2757 2758 2759

        代码示例:

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

Q
Quleaf 已提交
2761
            import paddle
Q
Quleaf 已提交
2762 2763 2764
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2765
            theta = paddle.ones([DEPTH, 2, 3], dtype='float64')
Q
Quleaf 已提交
2766 2767 2768
            cir = UAnsatz(n)
            cir.complex_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2769 2770 2771
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2772 2773
        ::

Q
Quleaf 已提交
2774 2775 2776
            The probability distribution of measurement results on both qubits is
                {'00': 0.15032627279218896, '01': 0.564191201239618,
                '10': 0.03285998070292556, '11': 0.25262254526526823}
Q
Quleaf 已提交
2777
        """
Q
Quleaf 已提交
2778 2779 2780 2781 2782 2783
        # 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 已提交
2784 2785 2786
        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 已提交
2787
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2788
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'
Q
Quleaf 已提交
2789

Q
Quleaf 已提交
2790 2791
        if which_qubits is None:
            which_qubits = np.arange(self.n)
Q
Quleaf 已提交
2792

Q
Quleaf 已提交
2793 2794
        for repeat in range(depth):
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2795
                self.u3(theta[repeat][i][0], theta[repeat][i][1], theta[repeat][i][2], q)
Q
Quleaf 已提交
2796 2797 2798
            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 已提交
2799 2800 2801 2802 2803 2804 2805

    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 已提交
2806
        """
Q
Quleaf 已提交
2807 2808 2809 2810
        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 已提交
2811

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

Q
Quleaf 已提交
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
        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 已提交
2836 2837
        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 已提交
2838 2839 2840

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
2841
        """
Q
Quleaf 已提交
2842
        assert theta.shape[1] == 4 and theta.shape[0] == (position[1] - position[0] + 1) / 2, \
Q
Quleaf 已提交
2843 2844 2845 2846 2847 2848
            '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 已提交
2849 2850
        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 已提交
2851 2852 2853

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

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

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

Q
Quleaf 已提交
2866
        Attention:
Q
Quleaf 已提交
2867
            ``theta`` 的维度为 ``(depth, n-1, 4)`` 。
Q
Quleaf 已提交
2868

Q
Quleaf 已提交
2869
        Args:
Q
Quleaf 已提交
2870 2871
            theta (Tensor): Ry 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2872 2873 2874 2875

        代码示例:

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

Q
Quleaf 已提交
2877 2878
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2879 2880
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2881
            theta = paddle.ones([DEPTH, n - 1, 4], dtype='float64')
Q
Quleaf 已提交
2882 2883 2884 2885
            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 已提交
2886

Q
Quleaf 已提交
2887 2888 2889
        ::

            {'0': 0.9646724056906162, '1': 0.035327594309385896}
Q
Quleaf 已提交
2890
        """
Q
Quleaf 已提交
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
        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 已提交
2908 2909
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的弱纠缠层。

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

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

Q
Quleaf 已提交
2916
        Args:
Q
Quleaf 已提交
2917
            theta (Tensor): U3 门的角度信息
Q
Quleaf 已提交
2918 2919 2920 2921 2922
            depth (int): 纠缠层的深度

        代码示例:

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

Q
Quleaf 已提交
2924 2925
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2926 2927
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2928
            theta = paddle.ones([DEPTH, n - 1, 12], dtype='float64')
Q
Quleaf 已提交
2929 2930 2931 2932
            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 已提交
2933

Q
Quleaf 已提交
2934
        ::
Q
Quleaf 已提交
2935

Q
Quleaf 已提交
2936
            {'0': 0.5271554811768046, '1': 0.4728445188231988}
Q
Quleaf 已提交
2937
        """
Q
Quleaf 已提交
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
        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 已提交
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 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
    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 已提交
3103 3104 3105 3106 3107 3108 3109 3110 3111
    """
    Channels
    """

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

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

Q
Quleaf 已提交
3113 3114
        .. math::

Q
Quleaf 已提交
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
            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 已提交
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138

        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 已提交
3139
            cir.cnot([0, 1])
Q
Quleaf 已提交
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
            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 已提交
3166 3167 3168 3169 3170
            E_0 = \sqrt{p}
            \begin{bmatrix}
                1 & 0 \\
                0 & \sqrt{1-\gamma}
            \end{bmatrix},
Q
Quleaf 已提交
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
            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 已提交
3190
            cir.cnot([0, 1])
Q
Quleaf 已提交
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
            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 已提交
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
            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 已提交
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243

        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 已提交
3244
            cir.cnot([0, 1])
Q
Quleaf 已提交
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 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
            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 已提交
3287
            cir.cnot([0, 1])
Q
Quleaf 已提交
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
            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 已提交
3301
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
        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 已提交
3330
            cir.cnot([0, 1])
Q
Quleaf 已提交
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
            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 已提交
3344
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
        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 已提交
3373
            cir.cnot([0, 1])
Q
Quleaf 已提交
3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
            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 已提交
3387
        e0 = paddle.to_tensor([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype='complex128')
Q
Quleaf 已提交
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
        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 已提交
3418
            cir.cnot([0, 1])
Q
Quleaf 已提交
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
            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 已提交
3432 3433 3434 3435
        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 已提交
3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462

        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 已提交
3463
            cir.cnot([0, 1])
Q
Quleaf 已提交
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
            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 已提交
3490 3491 3492
    @apply_channel
    def reset(self, p, q, which_qubit):
        r"""添加重置信道。有 p 的概率将量子态重置为 :math:`|0\rangle` 并有 q 的概率重置为 :math:`|1\rangle`。
Q
Quleaf 已提交
3493

Q
Quleaf 已提交
3494
        其 Kraus 算符为:
Q
Quleaf 已提交
3495

Q
Quleaf 已提交
3496
        .. math::
Q
Quleaf 已提交
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517

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

Q
Quleaf 已提交
3520 3521 3522 3523
        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 已提交
3524

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

Q
Quleaf 已提交
3528
        代码示例:
Q
Quleaf 已提交
3529

Q
Quleaf 已提交
3530
        .. code-block:: python
Q
Quleaf 已提交
3531

Q
Quleaf 已提交
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541
            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 已提交
3542

Q
Quleaf 已提交
3543
        ::
Q
Quleaf 已提交
3544

Q
Quleaf 已提交
3545 3546 3547 3548 3549 3550
            [[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 已提交
3551

Q
Quleaf 已提交
3552 3553 3554 3555 3556
        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 已提交
3557

Q
Quleaf 已提交
3558
        return [e0, e1, e2, e3, e4]
Q
Quleaf 已提交
3559

Q
Quleaf 已提交
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 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
    @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 已提交
3600

Q
Quleaf 已提交
3601 3602 3603
        # Change time scale
        time = time / 1000
        # Probability of resetting the state to |0>
Q
Quleaf 已提交
3604
        p_reset = 1 - np.exp(-time / t1)
Q
Quleaf 已提交
3605
        # Probability of phase flip
Q
Quleaf 已提交
3606
        p_z = (1 - p_reset) * (1 - np.exp(-time / t2) * np.exp(time / t1)) / 2
Q
Quleaf 已提交
3607
        # Probability of identity
Q
Quleaf 已提交
3608 3609
        p_i = 1 - p_reset - p_z

Q
Quleaf 已提交
3610 3611 3612 3613
        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 已提交
3614

Q
Quleaf 已提交
3615
        return [e0, e1, e2, e3]
Q
Quleaf 已提交
3616

Q
Quleaf 已提交
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
    @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 已提交
3636
            cir.cnot([0, 1])
Q
Quleaf 已提交
3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
            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 已提交
3654 3655
        assert np.allclose(completeness.numpy(),
                           np.eye(2, dtype='complex128')), 'Kraus operators should satisfy completeness.'
Q
Quleaf 已提交
3656 3657 3658

        return ops

Q
Quleaf 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 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
    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 已提交
3894

Q
Quleaf 已提交
3895
def _local_H_prob(cir, hamiltonian, shots=1024):
Q
Quleaf 已提交
3896
    r"""
Q
Quleaf 已提交
3897
    构造出 Pauli 测量电路并测量 ancilla,处理实验结果来得到 ``H`` (只有一项)期望值的实验测量值。
Q
Quleaf 已提交
3898 3899 3900 3901 3902 3903

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

    op_list = hamiltonian.split(',')
    # Set up pauli measurement circuit
    for op in op_list:
        element = op[0]
Q
Quleaf 已提交
3912 3913 3914 3915 3916
        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 已提交
3917 3918
            new_cir.h(index)
            new_cir.cnot([index, cir.n])
Q
Quleaf 已提交
3919
        elif element.lower() == 'z':
Q
Quleaf 已提交
3920
            new_cir.cnot([index, cir.n])
Q
Quleaf 已提交
3921
        elif element.lower() == 'y':
Q
Quleaf 已提交
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
            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 已提交
3933
                result = -(prob_result['1']) / shots
Q
Quleaf 已提交
3934 3935 3936 3937 3938 3939 3940 3941
        else:
            result = (prob_result['0'] - prob_result['1']) / shots
    else:
        result = (prob_result['0'] - prob_result['1'])

    return result


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

Q
Quleaf 已提交
3945
    Args:
Q
Quleaf 已提交
3946
        n (int): 待比较的两个态的量子比特数
Q
Quleaf 已提交
3947

Q
Quleaf 已提交
3948
    Returns:
Q
Quleaf 已提交
3949 3950
        UAnsatz: Swap Test 的电路

Q
Quleaf 已提交
3951 3952 3953
    代码示例:

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

Q
Quleaf 已提交
3955
        import paddle
Q
Quleaf 已提交
3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972
        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 已提交
3973 3974 3975

    ::

Q
Quleaf 已提交
3976
        The inner product is 0.006591796875
Q
Quleaf 已提交
3977
    """
Q
Quleaf 已提交
3978 3979 3980 3981 3982 3983 3984
    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