circuit.py 152.3 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

Q
Quleaf 已提交
63 64 65 66 67 68 69 70
    def __add__(self, cir):
        r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路

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

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

Q
Quleaf 已提交
207
        Note:
Q
Quleaf 已提交
208
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
209 210 211 212 213 214 215 216 217 218 219
        """
        # 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 已提交
220

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

Q
Quleaf 已提交
257
        return length, gate
Q
Quleaf 已提交
258

Q
Quleaf 已提交
259 260
    def __str__(self):
        r"""实现画电路的功能
Q
Quleaf 已提交
261

Q
Quleaf 已提交
262 263
        Returns:
            string: 用来print的字符串
Q
Quleaf 已提交
264

Q
Quleaf 已提交
265 266 267 268 269 270 271
        代码示例:

        .. code-block:: python

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

Q
Quleaf 已提交
273 274 275 276
            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 已提交
277

Q
Quleaf 已提交
278 279
            print(cir)
        ::
Q
Quleaf 已提交
280

Q
Quleaf 已提交
281
            The printed circuit is:
Q
Quleaf 已提交
282

Q
Quleaf 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295
            --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 已提交
296
        # Ignore the unused section
Q
Quleaf 已提交
297
        total_length = sum(length) - 5
Q
Quleaf 已提交
298

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

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

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

        return return_str
Q
Quleaf 已提交
398

Q
Quleaf 已提交
399
    def run_state_vector(self, input_state=None, store_state=True):
Q
Quleaf 已提交
400 401 402 403
        r"""运行当前的量子电路,输入输出的形式为态矢量。

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

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

Q
Quleaf 已提交
409
        Returns:
Q
Quleaf 已提交
410
            Tensor: 量子电路输出的态矢量
Q
Quleaf 已提交
411

Q
Quleaf 已提交
412
        代码示例:
Q
Quleaf 已提交
413

Q
Quleaf 已提交
414
        .. code-block:: python
Q
Quleaf 已提交
415

Q
Quleaf 已提交
416
            import numpy as np
Q
Quleaf 已提交
417
            import paddle
Q
Quleaf 已提交
418
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
419
            from paddle_quantum.state import vec
Q
Quleaf 已提交
420 421
            n = 2
            theta = np.ones(3)
Q
Quleaf 已提交
422

Q
Quleaf 已提交
423
            input_state = paddle.to_tensor(vec(0, n))
Q
Quleaf 已提交
424 425 426 427 428 429 430
            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 已提交
431

Q
Quleaf 已提交
432
        ::
Q
Quleaf 已提交
433

Q
Quleaf 已提交
434
            The output state vector is [[0.62054458+0.j 0.18316521+0.28526291j 0.62054458+0.j 0.18316521+0.28526291j]]
Q
Quleaf 已提交
435
        """
Q
Quleaf 已提交
436
        # Throw a warning when cir has channel
Q
Quleaf 已提交
437
        if self.__has_channel:
Q
Quleaf 已提交
438
            warnings.warn('The noiseless circuit will be run.', RuntimeWarning)
Q
Quleaf 已提交
439 440
        state = init_state_gen(self.n, 0) if input_state is None else input_state
        old_shape = state.shape
Q
Quleaf 已提交
441 442
        assert reduce(lambda x, y: x * y, old_shape) == 2 ** self.n, \
            'The length of the input vector is not right'
Q
Quleaf 已提交
443
        state = reshape(state, (2 ** self.n,))
Q
Quleaf 已提交
444

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

Q
Quleaf 已提交
449
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
450 451 452 453

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

Q
Quleaf 已提交
456
        return reshape(state, old_shape)
Q
Quleaf 已提交
457 458

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

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

Q
Quleaf 已提交
465
        Returns:
Q
Quleaf 已提交
466
            Tensor: 量子电路输出的密度矩阵
Q
Quleaf 已提交
467 468 469 470

        代码示例:

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

Q
Quleaf 已提交
472
            import numpy as np
Q
Quleaf 已提交
473
            import paddle
Q
Quleaf 已提交
474
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
475
            from paddle_quantum.state import density_op
Q
Quleaf 已提交
476 477
            n = 1
            theta = np.ones(3)
Q
Quleaf 已提交
478 479 480 481 482 483 484 485 486

            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 已提交
487 488 489

        ::

Q
Quleaf 已提交
490
            The output density matrix is
Q
Quleaf 已提交
491 492
            [[0.64596329+0.j         0.47686058+0.03603751j]
            [0.47686058-0.03603751j 0.35403671+0.j        ]]
Q
Quleaf 已提交
493
        """
Q
Quleaf 已提交
494
        state = paddle.to_tensor(density_op(self.n)) if input_state is None else input_state
Q
Quleaf 已提交
495 496
        assert state.shape == [2 ** self.n, 2 ** self.n], \
            "The dimension is not right"
Q
Quleaf 已提交
497

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

Q
Quleaf 已提交
525 526 527
        if store_state:
            self.__state = state
            # Add info about which function user called
Q
Quleaf 已提交
528
            self.__run_mode = 'density_matrix'
Q
Quleaf 已提交
529 530 531

        return state

Q
Quleaf 已提交
532 533 534 535 536 537
    def reset_state(self, state, which_qubits):
        r"""对当前电路中的量子态的部分量子比特进行重置。

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

        Returns:
            paddle.Tensor: 重置后的量子态
Q
Quleaf 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        """
        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 已提交
583
        return _state
Q
Quleaf 已提交
584

Q
Quleaf 已提交
585 586
    @property
    def U(self):
Q
Quleaf 已提交
587 588 589 590
        r"""量子电路的酉矩阵形式。

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

Q
Quleaf 已提交
592
        Returns:
Q
Quleaf 已提交
593
            Tensor: 当前电路的酉矩阵表示
Q
Quleaf 已提交
594 595 596 597

        代码示例:

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

Q
Quleaf 已提交
599
            import paddle
Q
Quleaf 已提交
600 601
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
602 603 604 605 606
            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 已提交
607 608 609

        ::

Q
Quleaf 已提交
610
            The unitary matrix of the circuit for Bell state preparation is
Q
Quleaf 已提交
611 612 613 614
            [[ 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 已提交
615
        """
Q
Quleaf 已提交
616
        # Throw a warning when cir has channel
Q
Quleaf 已提交
617
        if self.__has_channel:
Q
Quleaf 已提交
618 619 620 621 622
            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 已提交
623
        state = paddle.cast(state, 'complex128')
Q
Quleaf 已提交
624
        state = reshape(state, [num_ele])
Q
Quleaf 已提交
625
        state = transfer_by_history(state, self.__history, self.__param)
Q
Quleaf 已提交
626

Q
Quleaf 已提交
627
        return reshape(state, shape)
Q
Quleaf 已提交
628

Q
Quleaf 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    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 已提交
653 654 655 656 657 658 659
        r"""将输入的经典数据使用基态编码的方式编码成量子态。

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

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

Q
Quleaf 已提交
678
    def amplitude_encoding(self, x, mode, which_qubits=None):
Q
Quleaf 已提交
679 680 681 682 683
        r"""将输入的经典数据使用振幅编码的方式编码成量子态。

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

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

Q
Quleaf 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
        代码示例:

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

Q
Quleaf 已提交
784 785 786
        return result_tensor

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

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

Q
Quleaf 已提交
808
        def add_encoding_gate(theta, which, gate):
Q
Quleaf 已提交
809
            if gate == "rx":
Q
Quleaf 已提交
810
                self.rx(theta, which)
Q
Quleaf 已提交
811
            elif gate == "ry":
Q
Quleaf 已提交
812
                self.ry(theta, which)
Q
Quleaf 已提交
813
            elif gate == "rz":
Q
Quleaf 已提交
814
                self.rz(theta, which)
Q
Quleaf 已提交
815 816 817 818
            else:
                raise ValueError("the encoding_gate should be rx, ry, or rz")

        for idx, element in enumerate(x):
Q
Quleaf 已提交
819
            add_encoding_gate(element[0], which_qubits[idx], encoding_gate)
Q
Quleaf 已提交
820 821 822 823 824 825 826 827 828 829

    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 已提交
830 831
        assert x.size <= self.n, \
            "the number of classical data should be equal to the number of qubits"
Q
Quleaf 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844
        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 已提交
845
                    self.rz(-x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
846 847 848 849 850 851 852 853 854 855 856 857
                    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 已提交
858
                    self.rz(x[item[0]] * x[item[1]], item[1])
Q
Quleaf 已提交
859 860
                    self.cnot(list(item))

Q
Quleaf 已提交
861
    """
Q
Quleaf 已提交
862
    Common Gates
Q
Quleaf 已提交
863 864
    """

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

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

Q
Quleaf 已提交
870
        .. math::
Q
Quleaf 已提交
871 872 873 874 875

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

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

Q
Quleaf 已提交
881 882 883
        ..  code-block:: python

            import numpy as np
Q
Quleaf 已提交
884
            import paddle
Q
Quleaf 已提交
885 886
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
Q
Quleaf 已提交
887 888 889 890 891 892
            theta = paddle.to_tensor(theta)
            num_qubits = 1
            cir = UAnsatz(num_qubits)
            which_qubit = 0
            cir.rx(theta[0], which_qubit)

Q
Quleaf 已提交
893
        """
Q
Quleaf 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
        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 已提交
942 943

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

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

Q
Quleaf 已提交
948
        .. math::
Q
Quleaf 已提交
949 950 951 952 953

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

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

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

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

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

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

Q
Quleaf 已提交
1024
        .. math::
Q
Quleaf 已提交
1025

Q
Quleaf 已提交
1026 1027 1028 1029
            \begin{bmatrix}
                1 & 0 \\
                0 & e^{i\theta}
            \end{bmatrix}
Q
Quleaf 已提交
1030

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

Q
Quleaf 已提交
1035
        ..  code-block:: python
Q
Quleaf 已提交
1036

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

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

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

Q
Quleaf 已提交
1100
        .. math::
Q
Quleaf 已提交
1101

Q
Quleaf 已提交
1102
            \begin{align}
Q
Quleaf 已提交
1103 1104 1105 1106 1107 1108 1109 1110
                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 已提交
1111
            \end{align}
Q
Quleaf 已提交
1112

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

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

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

Q
Quleaf 已提交
1248 1249 1250 1251 1252 1253 1254 1255
    def swap(self, control):
        r"""添加一个 SWAP 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1256 1257 1258 1259 1260 1261 1262
                SWAP =
                \begin{bmatrix}
                    1 & 0 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 0 & 1
                \end{bmatrix}
Q
Quleaf 已提交
1263 1264 1265
            \end{align}

        Args:
Q
Quleaf 已提交
1266 1267
            control (list): 作用在的量子比特的编号,``control[0]`` 和 ``control[1]`` 是想要交换的位,
                其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1268 1269 1270 1271

        ..  code-block:: python

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

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

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

Q
Quleaf 已提交
1372
        .. math::
Q
Quleaf 已提交
1373 1374 1375 1376 1377

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

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

Q
Quleaf 已提交
1382
        .. code-block:: python
Q
Quleaf 已提交
1383

Q
Quleaf 已提交
1384
            import paddle
Q
Quleaf 已提交
1385
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
            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 已提交
1396
        """
Q
Quleaf 已提交
1397
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1398
        self.__history.append({'gate': 'x', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1399 1400

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

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

Q
Quleaf 已提交
1405
        .. math::
Q
Quleaf 已提交
1406 1407 1408 1409 1410

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

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

Q
Quleaf 已提交
1415
        .. code-block:: python
Q
Quleaf 已提交
1416

Q
Quleaf 已提交
1417
            import paddle
Q
Quleaf 已提交
1418
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
            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 已提交
1429
        """
Q
Quleaf 已提交
1430
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1431
        self.__history.append({'gate': 'y', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1432 1433

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

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

Q
Quleaf 已提交
1438
        .. math::
Q
Quleaf 已提交
1439 1440 1441 1442 1443

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

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

Q
Quleaf 已提交
1448
        .. code-block:: python
Q
Quleaf 已提交
1449

Q
Quleaf 已提交
1450
            import paddle
Q
Quleaf 已提交
1451
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
            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 已提交
1462
        """
Q
Quleaf 已提交
1463
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1464
        self.__history.append({'gate': 'z', 'which_qubits': [which_qubit], 'theta': None})
Q
Quleaf 已提交
1465 1466

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

Q
Quleaf 已提交
1469
        其矩阵形式为:
Q
Quleaf 已提交
1470 1471

        .. math::
Q
Quleaf 已提交
1472 1473 1474 1475 1476 1477

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

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

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

Q
Quleaf 已提交
1488
        其矩阵形式为:
Q
Quleaf 已提交
1489 1490

        .. math::
Q
Quleaf 已提交
1491 1492 1493 1494 1495 1496

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

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

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

Q
Quleaf 已提交
1526
        其矩阵形式为:
Q
Quleaf 已提交
1527 1528 1529

        .. math::

Q
Quleaf 已提交
1530 1531 1532 1533 1534
            T =
                \begin{bmatrix}
                    1&0\\
                    0&e^\frac{i\pi}{4}
                \end{bmatrix}
Q
Quleaf 已提交
1535

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

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

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

Q
Quleaf 已提交
1566
        .. math::
Q
Quleaf 已提交
1567

Q
Quleaf 已提交
1568
            \begin{align}
Q
Quleaf 已提交
1569 1570 1571 1572 1573
                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 已提交
1574 1575 1576
            \end{align}

        Args:
Q
Quleaf 已提交
1577 1578 1579
              theta (Tensor): 旋转角度 :math:`\theta` 。
              phi (Tensor): 旋转角度 :math:`\phi` 。
              lam (Tensor): 旋转角度 :math:`\lambda` 。
Q
Quleaf 已提交
1580
              which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, n)` 范围内, :math:`n` 为该量子电路的量子比特数
Q
Quleaf 已提交
1581
        """
Q
Quleaf 已提交
1582
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n (the number of qubit)"
Q
Quleaf 已提交
1583 1584 1585 1586
        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 已提交
1587

Q
Quleaf 已提交
1588 1589 1590 1591 1592 1593 1594 1595
    def rxx(self, theta, which_qubits):
        r"""添加一个 RXX 门。

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1596 1597 1598 1599 1600 1601 1602
                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 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
            \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 已提交
1621 1622 1623
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RXX_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1633 1634 1635 1636 1637 1638 1639
                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 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
            \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 已提交
1658 1659 1660
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RYY_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1670 1671 1672 1673 1674 1675 1676
                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 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
            \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 已提交
1695 1696 1697
        curr_idx = len(self.__param)
        self.__history.append({'gate': 'RZZ_gate', 'which_qubits': which_qubits, 'theta': [curr_idx]})
        self.__param.append(theta)
Q
Quleaf 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706

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

        其矩阵形式为:

        .. math::

            \begin{align}
Q
Quleaf 已提交
1707 1708 1709 1710 1711 1712 1713
                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 已提交
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
            \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 已提交
1734
        self.__history.append({'gate': 'MS_gate', 'which_qubits': which_qubits, 'theta': [2]})
Q
Quleaf 已提交
1735

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

        Args:
Q
Quleaf 已提交
1740
            theta (Tensor): 2-qubit 通用门的参数,其维度为 ``(15, )``
Q
Quleaf 已提交
1741 1742 1743 1744 1745 1746 1747
            which_qubits(list): 作用的量子比特编号

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
1748
            import paddle
Q
Quleaf 已提交
1749 1750
            from paddle_quantum.circuit import UAnsatz
            n = 2
Q
Quleaf 已提交
1751 1752 1753 1754 1755
            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 已提交
1756 1757 1758 1759 1760

        ::

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

Q
Quleaf 已提交
1762 1763 1764 1765 1766
        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 已提交
1767

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

Q
Quleaf 已提交
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
        代码示例:

        .. 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 已提交
2057 2058

        Args:
Q
Quleaf 已提交
2059 2060 2061 2062 2063
            ind_history (int): 该门在本电路中的序号
            ind_gate (int): cu 门参数的 index,可以是 0 或 1 或 2

        Return:
            UAnsatz: 用电路表示的该门的一个参数的偏导
Q
Quleaf 已提交
2064 2065 2066 2067 2068 2069

        代码示例:

        .. code-block:: python

            import numpy as np
Q
Quleaf 已提交
2070
            import paddle
Q
Quleaf 已提交
2071
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2072 2073 2074 2075 2076
            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 已提交
2077 2078 2079

        ::

Q
Quleaf 已提交
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
            -----------------x--
                             |  
            ------------z----U--
                        |       
            --H---SDG---*----H--

            ------------z---------x--
                        |         |  
            ------------|----z----U--
                        |    |       
            --H----S----*----*----H--
Q
Quleaf 已提交
2091
        """
Q
Quleaf 已提交
2092 2093 2094 2095
        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 已提交
2096

Q
Quleaf 已提交
2097 2098 2099 2100 2101 2102 2103 2104 2105 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
        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 已提交
2137

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

Q
Quleaf 已提交
2142 2143
        Return:
            Tensor: 该电路中所有需要训练的参数的梯度
Q
Quleaf 已提交
2144

Q
Quleaf 已提交
2145
        代码示例:
Q
Quleaf 已提交
2146

Q
Quleaf 已提交
2147
        .. code-block:: python
Q
Quleaf 已提交
2148

Q
Quleaf 已提交
2149 2150 2151
            import numpy as np
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2152

Q
Quleaf 已提交
2153 2154 2155 2156 2157 2158 2159 2160 2161 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
            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 已提交
2305

Q
Quleaf 已提交
2306
    """
Q
Quleaf 已提交
2307
    Measurements
Q
Quleaf 已提交
2308 2309
    """

Q
Quleaf 已提交
2310
    def __process_string(self, s, which_qubits):
Q
Quleaf 已提交
2311
        r"""该函数基于 which_qubits 返回 s 的一部分
Q
Quleaf 已提交
2312 2313
        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 已提交
2314

Q
Quleaf 已提交
2315 2316 2317 2318 2319
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        new_s = ''.join(s[j] for j in which_qubits)
        return new_s
Q
Quleaf 已提交
2320

Q
Quleaf 已提交
2321
    def __process_similiar(self, result):
Q
Quleaf 已提交
2322
        r"""该函数基于相同的键合并值。
Q
Quleaf 已提交
2323
        This functions merges values based on identical keys.
Q
Quleaf 已提交
2324 2325
        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 已提交
2326

Q
Quleaf 已提交
2327 2328 2329 2330 2331 2332
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        data = defaultdict(int)
        for idx, val in result:
            data[idx] += val
Q
Quleaf 已提交
2333

Q
Quleaf 已提交
2334
        return dict(data)
Q
Quleaf 已提交
2335

Q
Quleaf 已提交
2336 2337 2338 2339 2340 2341 2342 2343 2344 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
    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 已提交
2374
        r"""对量子电路输出的量子态进行测量。
Q
Quleaf 已提交
2375 2376

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

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

Q
Quleaf 已提交
2384 2385 2386 2387 2388 2389
        Returns:
            dict: 测量的结果

        代码示例:

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

Q
Quleaf 已提交
2391 2392
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2393 2394 2395 2396 2397 2398
            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 已提交
2399 2400 2401

        ::

Q
Quleaf 已提交
2402
            The results of measuring qubit 1 2048 times are {'0': 964, '1': 1084}
Q
Quleaf 已提交
2403 2404

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

Q
Quleaf 已提交
2406 2407
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2408 2409 2410 2411 2412 2413
            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 已提交
2414 2415 2416

        ::

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

            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 已提交
2452 2453 2454 2455 2456 2457 2458 2459 2460 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
    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 已提交
2504
        r"""量子电路输出的量子态关于可观测量 H 的期望值。
Q
Quleaf 已提交
2505 2506

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

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

Q
Quleaf 已提交
2514
        Returns:
Q
Quleaf 已提交
2515
            Tensor: 量子电路输出的量子态关于 ``H`` 的期望值
Q
Quleaf 已提交
2516 2517

        代码示例:
Q
Quleaf 已提交
2518

Q
Quleaf 已提交
2519
        .. code-block:: python
Q
Quleaf 已提交
2520 2521

            import numpy as np
Q
Quleaf 已提交
2522
            import paddle
Q
Quleaf 已提交
2523
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2524

Q
Quleaf 已提交
2525
            n = 5
Q
Quleaf 已提交
2526
            experiment_shots = 2**10
Q
Quleaf 已提交
2527
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
Q
Quleaf 已提交
2528
            theta = paddle.ones([3], dtype='float64')
Q
Quleaf 已提交
2529

Q
Quleaf 已提交
2530 2531 2532 2533 2534
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.rz(theta[1], 1)
            cir.rx(theta[2], 2)
            cir.run_state_vector()
Q
Quleaf 已提交
2535

Q
Quleaf 已提交
2536 2537 2538 2539 2540
            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 已提交
2541

Q
Quleaf 已提交
2542
        ::
Q
Quleaf 已提交
2543

Q
Quleaf 已提交
2544 2545
            The expectation value obtained by 1024 measurements is [-0.16328125]
            The accurate expectation value of H is [-0.1682942]
Q
Quleaf 已提交
2546
        """
Q
Quleaf 已提交
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
        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 已提交
2560
        else:
Q
Quleaf 已提交
2561 2562 2563 2564 2565
            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 已提交
2566 2567

    """
Q
Quleaf 已提交
2568
    Circuit Templates
Q
Quleaf 已提交
2569 2570
    """

Q
Quleaf 已提交
2571
    def superposition_layer(self):
Q
Quleaf 已提交
2572
        r"""添加一层 Hadamard 门。
Q
Quleaf 已提交
2573 2574 2575 2576

        代码示例:

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

Q
Quleaf 已提交
2578 2579
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2580 2581 2582 2583 2584
            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 已提交
2585 2586 2587

        ::

Q
Quleaf 已提交
2588 2589 2590
            The probability distribution of measurement results on both qubits is
                {'00': 0.2499999999999999, '01': 0.2499999999999999,
                '10': 0.2499999999999999, '11': 0.2499999999999999}
Q
Quleaf 已提交
2591
        """
Q
Quleaf 已提交
2592 2593 2594 2595
        for i in range(self.n):
            self.h(i)

    def weak_superposition_layer(self):
Q
Quleaf 已提交
2596
        r"""添加一层旋转角度为 :math:`\pi/4` 的 Ry 门。
Q
Quleaf 已提交
2597 2598 2599 2600

        代码示例:

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

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

        ::

Q
Quleaf 已提交
2612 2613 2614
            The probability distribution of measurement results on both qubits is
                {'00': 0.7285533905932737, '01': 0.12500000000000003,
                '10': 0.12500000000000003, '11': 0.021446609406726238}
Q
Quleaf 已提交
2615
        """
Q
Quleaf 已提交
2616
        _theta = paddle.to_tensor(np.array([np.pi / 4]))  # Used in fixed Ry gate
Q
Quleaf 已提交
2617 2618
        for i in range(self.n):
            self.ry(_theta, i)
Q
Quleaf 已提交
2619

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

        Attention:
Q
Quleaf 已提交
2624
            ``theta`` 的维度为 ``(depth, n, 2)`` ,最低维内容为对应的 ``ry`` 和 ``rz`` 的参数, ``n`` 为作用的量子比特数量。
Q
Quleaf 已提交
2625 2626 2627 2628

        Args:
            theta (Tensor): Ry 门和 Rz 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2629
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2630 2631 2632 2633 2634 2635 2636 2637 2638

        代码示例:

        .. code-block:: python

            import paddle
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2639
            theta = paddle.ones([DEPTH, 2, 2], dtype='float64')
Q
Quleaf 已提交
2640 2641 2642
            cir = UAnsatz(n)
            cir.linear_entangled_layer(theta, DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2643 2644
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")
Q
Quleaf 已提交
2645 2646 2647

        ::

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

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

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

Q
Quleaf 已提交
2686
        Args:
Q
Quleaf 已提交
2687
            theta (Tensor): Ry 门的旋转角度
Q
Quleaf 已提交
2688
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2689
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2690 2691 2692 2693

        代码示例:

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

Q
Quleaf 已提交
2695
            import paddle
Q
Quleaf 已提交
2696 2697 2698
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2699
            theta = paddle.ones([DEPTH, 2, 1], dtype='float64')
Q
Quleaf 已提交
2700 2701 2702
            cir = UAnsatz(n)
            cir.real_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2703 2704 2705
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2706 2707
        ::

Q
Quleaf 已提交
2708 2709 2710
            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 已提交
2711
        """
Q
Quleaf 已提交
2712 2713 2714 2715 2716 2717
        # 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 已提交
2718 2719 2720
        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 已提交
2721
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2722 2723
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'

Q
Quleaf 已提交
2724 2725 2726
        if which_qubits is None:
            which_qubits = np.arange(self.n)

Q
Quleaf 已提交
2727
        for repeat in range(depth):
Q
Quleaf 已提交
2728
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2729
                self.ry(theta[repeat][i][0], q)
Q
Quleaf 已提交
2730 2731 2732
            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 已提交
2733

Q
Quleaf 已提交
2734 2735
    def complex_entangled_layer(self, theta, depth, which_qubits=None):
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的强纠缠层。
Q
Quleaf 已提交
2736 2737 2738

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

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

Q
Quleaf 已提交
2743
        Args:
Q
Quleaf 已提交
2744
            theta (Tensor): U3 门的旋转角度
Q
Quleaf 已提交
2745
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2746
            which_qubits (list): 作用的量子比特编号
Q
Quleaf 已提交
2747 2748 2749 2750

        代码示例:

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

Q
Quleaf 已提交
2752
            import paddle
Q
Quleaf 已提交
2753 2754 2755
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
Q
Quleaf 已提交
2756
            theta = paddle.ones([DEPTH, 2, 3], dtype='float64')
Q
Quleaf 已提交
2757 2758 2759
            cir = UAnsatz(n)
            cir.complex_entangled_layer(paddle.to_tensor(theta), DEPTH, [0, 1])
            cir.run_state_vector()
Q
Quleaf 已提交
2760 2761 2762
            result = cir.measure(shots = 0)
            print(f"The probability distribution of measurement results on both qubits is {result}")

Q
Quleaf 已提交
2763 2764
        ::

Q
Quleaf 已提交
2765 2766 2767
            The probability distribution of measurement results on both qubits is
                {'00': 0.15032627279218896, '01': 0.564191201239618,
                '10': 0.03285998070292556, '11': 0.25262254526526823}
Q
Quleaf 已提交
2768
        """
Q
Quleaf 已提交
2769 2770 2771 2772 2773 2774
        # 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 已提交
2775 2776 2777
        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 已提交
2778
        # assert theta.shape[1] == self.n, 'the shape of theta is not right'
Q
Quleaf 已提交
2779
        assert theta.shape[0] == depth, 'the depth of theta has a mismatch'
Q
Quleaf 已提交
2780

Q
Quleaf 已提交
2781 2782
        if which_qubits is None:
            which_qubits = np.arange(self.n)
Q
Quleaf 已提交
2783

Q
Quleaf 已提交
2784 2785
        for repeat in range(depth):
            for i, q in enumerate(which_qubits):
Q
Quleaf 已提交
2786
                self.u3(theta[repeat][i][0], theta[repeat][i][1], theta[repeat][i][2], q)
Q
Quleaf 已提交
2787 2788 2789
            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 已提交
2790 2791 2792 2793 2794 2795 2796

    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 已提交
2797
        """
Q
Quleaf 已提交
2798 2799 2800 2801
        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 已提交
2802

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

Q
Quleaf 已提交
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
        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 已提交
2827 2828
        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 已提交
2829 2830 2831

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
2832
        """
Q
Quleaf 已提交
2833
        assert theta.shape[1] == 4 and theta.shape[0] == (position[1] - position[0] + 1) / 2, \
Q
Quleaf 已提交
2834 2835 2836 2837 2838 2839
            '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 已提交
2840 2841
        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 已提交
2842 2843 2844

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

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

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

Q
Quleaf 已提交
2857
        Attention:
Q
Quleaf 已提交
2858
            ``theta`` 的维度为 ``(depth, n-1, 4)`` 。
Q
Quleaf 已提交
2859

Q
Quleaf 已提交
2860
        Args:
Q
Quleaf 已提交
2861 2862
            theta (Tensor): Ry 门的旋转角度
            depth (int): 纠缠层的深度
Q
Quleaf 已提交
2863 2864 2865 2866

        代码示例:

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

Q
Quleaf 已提交
2868 2869
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2870 2871
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2872
            theta = paddle.ones([DEPTH, n - 1, 4], dtype='float64')
Q
Quleaf 已提交
2873 2874 2875 2876
            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 已提交
2877

Q
Quleaf 已提交
2878 2879 2880
        ::

            {'0': 0.9646724056906162, '1': 0.035327594309385896}
Q
Quleaf 已提交
2881
        """
Q
Quleaf 已提交
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
        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 已提交
2899 2900
        r"""添加 ``depth`` 层包含 U3 门和 CNOT 门的弱纠缠层。

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

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

Q
Quleaf 已提交
2907
        Args:
Q
Quleaf 已提交
2908
            theta (Tensor): U3 门的角度信息
Q
Quleaf 已提交
2909 2910 2911 2912 2913
            depth (int): 纠缠层的深度

        代码示例:

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

Q
Quleaf 已提交
2915 2916
            import paddle
            from paddle_quantum.circuit import UAnsatz
Q
Quleaf 已提交
2917 2918
            n = 4
            DEPTH = 3
Q
Quleaf 已提交
2919
            theta = paddle.ones([DEPTH, n - 1, 12], dtype='float64')
Q
Quleaf 已提交
2920 2921 2922 2923
            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 已提交
2924

Q
Quleaf 已提交
2925
        ::
Q
Quleaf 已提交
2926

Q
Quleaf 已提交
2927
            {'0': 0.5271554811768046, '1': 0.4728445188231988}
Q
Quleaf 已提交
2928
        """
Q
Quleaf 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
        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 已提交
2945 2946 2947 2948 2949 2950 2951 2952 2953 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
    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 已提交
3094 3095 3096 3097 3098 3099 3100 3101 3102
    """
    Channels
    """

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

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

Q
Quleaf 已提交
3104 3105
        .. math::

Q
Quleaf 已提交
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
            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 已提交
3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129

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

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

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

Q
Quleaf 已提交
3485
        其 Kraus 算符为:
Q
Quleaf 已提交
3486

Q
Quleaf 已提交
3487
        .. math::
Q
Quleaf 已提交
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508

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

Q
Quleaf 已提交
3511 3512 3513 3514
        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 已提交
3515

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

Q
Quleaf 已提交
3519
        代码示例:
Q
Quleaf 已提交
3520

Q
Quleaf 已提交
3521
        .. code-block:: python
Q
Quleaf 已提交
3522

Q
Quleaf 已提交
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532
            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 已提交
3533

Q
Quleaf 已提交
3534
        ::
Q
Quleaf 已提交
3535

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

Q
Quleaf 已提交
3543 3544 3545 3546 3547
        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 已提交
3548

Q
Quleaf 已提交
3549
        return [e0, e1, e2, e3, e4]
Q
Quleaf 已提交
3550

Q
Quleaf 已提交
3551 3552 3553 3554 3555 3556 3557 3558 3559 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
    @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 已提交
3591

Q
Quleaf 已提交
3592 3593 3594
        # Change time scale
        time = time / 1000
        # Probability of resetting the state to |0>
Q
Quleaf 已提交
3595
        p_reset = 1 - np.exp(-time / t1)
Q
Quleaf 已提交
3596
        # Probability of phase flip
Q
Quleaf 已提交
3597
        p_z = (1 - p_reset) * (1 - np.exp(-time / t2) * np.exp(time / t1)) / 2
Q
Quleaf 已提交
3598
        # Probability of identity
Q
Quleaf 已提交
3599 3600
        p_i = 1 - p_reset - p_z

Q
Quleaf 已提交
3601 3602 3603 3604
        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 已提交
3605

Q
Quleaf 已提交
3606
        return [e0, e1, e2, e3]
Q
Quleaf 已提交
3607

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

        return ops

Q
Quleaf 已提交
3650 3651 3652 3653 3654 3655 3656 3657 3658 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
    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 已提交
3885

Q
Quleaf 已提交
3886
def _local_H_prob(cir, hamiltonian, shots=1024):
Q
Quleaf 已提交
3887
    r"""
Q
Quleaf 已提交
3888
    构造出 Pauli 测量电路并测量 ancilla,处理实验结果来得到 ``H`` (只有一项)期望值的实验测量值。
Q
Quleaf 已提交
3889 3890 3891 3892 3893 3894

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

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

    return result


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

Q
Quleaf 已提交
3936
    Args:
Q
Quleaf 已提交
3937
        n (int): 待比较的两个态的量子比特数
Q
Quleaf 已提交
3938

Q
Quleaf 已提交
3939
    Returns:
Q
Quleaf 已提交
3940 3941
        UAnsatz: Swap Test 的电路

Q
Quleaf 已提交
3942 3943 3944
    代码示例:

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

Q
Quleaf 已提交
3946
        import paddle
Q
Quleaf 已提交
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
        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 已提交
3964 3965 3966

    ::

Q
Quleaf 已提交
3967
        The inner product is 0.006591796875
Q
Quleaf 已提交
3968
    """
Q
Quleaf 已提交
3969 3970 3971 3972 3973 3974 3975
    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