circuit.py 42.3 KB
Newer Older
Q
Quleaf 已提交
1
# Copyright (c) 2020 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 16 17 18 19
import gc
import math
from functools import reduce
from collections import defaultdict
import numpy as np
Q
Quleaf 已提交
20
from numpy import binary_repr, eye, identity
Q
Quleaf 已提交
21 22 23
import matplotlib.pyplot as plt

from Simulator.main import StateTranfer, init_state_gen, measure_state
Q
Quleaf 已提交
24

Q
Quleaf 已提交
25
import paddle
Q
Quleaf 已提交
26
from paddle.complex import kron as pp_kron
Q
Quleaf 已提交
27 28 29
from paddle.complex import reshape as complex_reshape
from paddle.complex import matmul, transpose, trace
from paddle.complex.tensor.math import elementwise_mul
Q
Quleaf 已提交
30

Q
Quleaf 已提交
31
import paddle.fluid as fluid
Q
Quleaf 已提交
32
from paddle.fluid import dygraph
Q
Quleaf 已提交
33 34
from paddle.fluid.layers import reshape, cast, eye, zeros
from paddle.fluid.framework import ComplexVariable
Q
Quleaf 已提交
35

Q
Quleaf 已提交
36
from paddle_quantum.utils import dagger, pauli_str_to_matrix
Q
Quleaf 已提交
37 38
from paddle_quantum.intrinsic import *
from paddle_quantum.state import density_op
Q
Quleaf 已提交
39 40 41

__all__ = [
    "UAnsatz",
Q
Quleaf 已提交
42
    "H_prob"
Q
Quleaf 已提交
43 44 45
]


Q
Quleaf 已提交
46 47 48 49
class UAnsatz:
    r"""基于Paddle的动态图机制实现量子线路的 ``class`` 。

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

Q
Quleaf 已提交
51 52
    Attributes:
        n (int): 该线路的量子比特数
Q
Quleaf 已提交
53 54
    """

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

Q
Quleaf 已提交
58 59
        Args:
            n (int): 该线路的量子比特数
Q
Quleaf 已提交
60

Q
Quleaf 已提交
61 62 63 64 65 66
        """
        self.n = n
        self.__state = None
        self.__run_state = ''
        # Record history of adding gates to the circuit
        self.__history = []
Q
Quleaf 已提交
67

Q
Quleaf 已提交
68 69 70 71 72 73 74 75 76 77 78
    def run_state_vector(self, input_state=None, store_state=True):
        r"""运行当前的量子线路,输入输出的形式为态矢量。
        
        Args:
            input_state (ComplexVariable, optional): 输入的态矢量,默认为 :math:`|00...0\rangle`
            store_state (Bool, optional): 是否存储输出的态矢量,默认为 ``True`` ,即存储
        
        Returns:
            ComplexVariable: 量子线路输出的态矢量
        
        代码示例:
Q
Quleaf 已提交
79

Q
Quleaf 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        .. code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 2
            theta = np.ones(3)
            input_state = np.ones(2**n)+0j
            input_state = input_state / np.linalg.norm(input_state)
            with fluid.dygraph.guard():
                
                input_state_var = fluid.dygraph.to_variable(input_state)
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.rx(theta[0], 0)
                cir.ry(theta[1], 1)
                cir.rz(theta[2], 1)
                vec = cir.run_state_vector(input_state_var).numpy()
                print(f"运行后的向量是 {vec}")
Q
Quleaf 已提交
99

Q
Quleaf 已提交
100
        ::
Q
Quleaf 已提交
101

Q
Quleaf 已提交
102 103 104 105 106 107
            运行后的向量是 [0.17470783-0.09544332j 0.59544332+0.32529217j 0.17470783-0.09544332j 0.59544332+0.32529217j]
        """
        state = init_state_gen(self.n, 0) if input_state is None else input_state
        old_shape = state.shape
        assert reduce(lambda x, y: x * y, old_shape) == 2 ** self.n, 'The length of the input vector is not right'
        state = complex_reshape(state, (2 ** self.n,))
Q
Quleaf 已提交
108

Q
Quleaf 已提交
109 110 111
        state_conj = ComplexVariable(state.real, -state.imag)
        assert fluid.layers.abs(paddle.complex.sum(elementwise_mul(state_conj, state)).real - 1) < 1e-8, \
            'Input state is not a normalized vector'
Q
Quleaf 已提交
112

Q
Quleaf 已提交
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
        for history_ele in self.__history:
            if history_ele[0] == 'u':
                state = StateTranfer(state, 'u', history_ele[1], history_ele[2])
            elif history_ele[0] in {'x', 'y', 'z', 'h'}:
                state = StateTranfer(state, history_ele[0], history_ele[1], params=history_ele[2])
            elif history_ele[0] == 'CNOT':
                state = StateTranfer(state, 'CNOT', history_ele[1])

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

        return complex_reshape(state, old_shape)

    def run_density_matrix(self, input_state=None, store_state=True):
        r"""运行当前的量子线路,输入输出的形式为密度矩阵。
        
        Args:
            input_state (ComplexVariable, optional): 输入的密度矩阵,默认为 :math:`|00...0\rangle \langle00...0|`
            store_state (bool, optional): 是否存储输出的密度矩阵,默认为 ``True`` ,即存储
        
        Returns:
            ComplexVariable: 量子线路输出的密度矩阵

        代码示例:

        .. code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 1
            theta = np.ones(3)
            input_state = np.diag(np.arange(2**n))+0j
            input_state = input_state / np.trace(input_state)
            with fluid.dygraph.guard():
                
                input_state_var = fluid.dygraph.to_variable(input_state)
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.rx(theta[0], 0)
                cir.ry(theta[1], 0)
                cir.rz(theta[2], 0)
                density = cir.run_density_matrix(input_state_var).numpy()
                print(f"密度矩阵是\n{density}")

        ::

            密度矩阵是
            [[ 0.35403671+0.j         -0.47686058-0.03603751j]
            [-0.47686058+0.03603751j  0.64596329+0.j        ]]
        """
        state = dygraph.to_variable(density_op(self.n)) if input_state is None else input_state
Q
Quleaf 已提交
167

Q
Quleaf 已提交
168
        assert state.real.shape == [2 ** self.n, 2 ** self.n], "The dimension is not right"
Q
Quleaf 已提交
169
        state = matmul(self.U, matmul(state, dagger(self.U)))
Q
Quleaf 已提交
170

Q
Quleaf 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        if store_state:
            self.__state = state
            # Add info about which function user called
            self.__run_state = 'density_matrix'

        return state

    @property
    def U(self):
        r"""量子线路的酉矩阵形式。
        
        Returns:
            ComplexVariable: 当前线路的酉矩阵表示

        代码示例:

        .. code-block:: python
        
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 2
            with fluid.dygraph.guard():
                cir = UAnsatz(2)
                cir.h(0)
                cir.cnot([0, 1])
                matrix = cir.U
                print("生成贝尔态电路的酉矩阵表示为\n",matrix.numpy())

        ::

            生成贝尔态电路的酉矩阵表示为
            [[ 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 已提交
206
        """
Q
Quleaf 已提交
207 208 209 210
        state = ComplexVariable(eye(2 ** self.n, dtype='float64'), zeros([2 ** self.n, 2 ** self.n], dtype='float64'))
        shape = (2 ** self.n, 2 ** self.n)
        num_ele = reduce(lambda x, y: x * y, shape)
        state = ComplexVariable(reshape(state.real, [num_ele]), reshape(state.imag, [num_ele]))
Q
Quleaf 已提交
211

Q
Quleaf 已提交
212 213 214 215 216 217 218
        for history_ele in self.__history:
            if history_ele[0] == 'u':
                state = StateTranfer(state, 'u', history_ele[1], history_ele[2])
            elif history_ele[0] in {'x', 'y', 'z', 'h'}:
                state = StateTranfer(state, history_ele[0], history_ele[1], params=history_ele[2])
            elif history_ele[0] == 'CNOT':
                state = StateTranfer(state, 'CNOT', history_ele[1])
Q
Quleaf 已提交
219

Q
Quleaf 已提交
220
        return ComplexVariable(reshape(state.real, shape), reshape(state.imag, shape))
Q
Quleaf 已提交
221 222

    """
Q
Quleaf 已提交
223
    Common Gates
Q
Quleaf 已提交
224 225
    """

Q
Quleaf 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    def rx(self, theta, which_qubit):
        r"""添加关于x轴的单量子比特旋转门。
 
        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\ -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}
 
        Args:
            theta (Variable): 旋转角度
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
 
        ..  code-block:: python

            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.rx(theta[0], which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [theta,
                                                    dygraph.to_variable(np.array([-math.pi / 2])),
                                                    dygraph.to_variable(np.array([math.pi / 2]))]])

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

        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\ \sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}

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

        ..  code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.ry(theta[0], which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [theta,
                                                    dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([0.0]))]])

    def rz(self, theta, which_qubit):
        r"""添加关于y轴的单量子比特旋转门。
 
        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} e^{-\frac{i\theta}{2}} & 0 \\ 0 & e^{\frac{i\theta}{2}} \end{bmatrix}
 
        Args:
            theta (Variable): 旋转角度
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
 
        ..  code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            theta = np.array([np.pi], np.float64)
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.ry(theta[0], which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([0.0])),
                                                    theta]])

    def cnot(self, control):
        r"""添加一个CNOT门。
 
        对于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 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
            \end{align}
 
        Args:
            control (list): 作用在的qubit的编号,``control[0]`` 为控制位,``control[1]`` 为目标位,其值都应该在 :math:`[0, n)`范围内, :math:`n` 为该量子线路的量子比特数

        ..  code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            num_qubits = 2
            with fluid.dygraph.guard():
                cir = UAnsatz(num_qubits)
                cir.cnot([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(['CNOT', control])

    def x(self, which_qubit):
        r"""添加单量子比特X门。
 
        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}
 
        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
 
        .. code-block:: python
            
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            with fluid.dygraph.guard():
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.x(which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['x', [which_qubit], None])

    def y(self, which_qubit):
        r"""添加单量子比特Y门。
 
        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}
 
        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
 
        .. code-block:: python
            
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            with fluid.dygraph.guard():
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.y(which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['y', [which_qubit], None])

    def z(self, which_qubit):
        r"""添加单量子比特Z门。
 
        其矩阵形式为:
        
        .. math::
        
            \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}
 
        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
 
        .. code-block:: python
        
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            with fluid.dygraph.guard():
                num_qubits = 1
                cir = UAnsatz(num_qubits)
                which_qubit = 0
                cir.z(which_qubit)
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['z', [which_qubit], None])

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

        具体形式为

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

        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['h', [which_qubit], None])

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

        具体形式为

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

        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([math.pi / 2]))]])

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

        具体形式为

        .. math::

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

Q
Quleaf 已提交
465 466 467 468 469 470 471 472 473 474 475 476
        Args:
            which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([0.0])),
                                                    dygraph.to_variable(np.array([math.pi / 4]))]])

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

        具体形式为
Q
Quleaf 已提交
477

Q
Quleaf 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        .. math::
        
            \begin{align}
            U3(\theta, \phi, \lambda) =
            \begin{bmatrix}
                \cos\frac\theta2&-e^{i\lambda}\sin\frac\theta2\\
                e^{i\phi}\sin\frac\theta2&e^{i(\phi+\lambda)}\cos\frac\theta2
            \end{bmatrix}
            \end{align}

        Args:
              theta (Variable): 旋转角度 :math:`\theta` 。
              phi (Variable): 旋转角度 :math:`\phi` 。
              lam (Variable): 旋转角度 :math:`\lambda` 。
              which_qubit (int): 作用在的qubit的编号,其值应该在[0, n)范围内,n为该量子线路的量子比特数
        """
        assert 0 <= which_qubit < self.n, "the qubit should >= 0 and < n(the number of qubit)"
        self.__history.append(['u', [which_qubit], [theta, phi, lam]])
Q
Quleaf 已提交
496 497

    """
Q
Quleaf 已提交
498
    Measurements
Q
Quleaf 已提交
499 500
    """

Q
Quleaf 已提交
501 502 503 504
    def __process_string(self, s, which_qubits):
        r"""
        This functions return part of string s baesd on which_qubits
        If s = 'abcdefg', which_qubits = [0,2,5], then it returns 'acf'
Q
Quleaf 已提交
505

Q
Quleaf 已提交
506 507 508 509 510
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        new_s = ''.join(s[j] for j in which_qubits)
        return new_s
Q
Quleaf 已提交
511

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

Q
Quleaf 已提交
517 518 519 520 521 522
        Note:
            这是内部函数,你并不需要直接调用到该函数。
        """
        data = defaultdict(int)
        for idx, val in result:
            data[idx] += val
Q
Quleaf 已提交
523

Q
Quleaf 已提交
524
        return dict(data)
Q
Quleaf 已提交
525

Q
Quleaf 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    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):
        r"""对量子线路输出的量子态进行测量。

        Warning:
            当plot为True时,当前量子线路的量子比特数需要小于6,否则无法绘制图片,会抛出异常。

        Args:
            which_qubits (list, optional): 要测量的qubit的编号,默认全都测量
            shots (int, optional): 该量子线路输出的量子态的测量次数,默认为1024次;若为0,则输出测量期望值的精确值
            plot (bool, optional): 是否绘制测量结果图,默认为 ``False`` ,即不绘制
        
        Returns:
            dict: 测量的结果

        代码示例:

        .. code-block:: python
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
            with paddle.fluid.dygraph.guard():
                cir = UAnsatz(2)
                cir.h(0)
                cir.cnot([0,1])
                cir.run_state_vector()
                result = cir.measure(shots = 2048, which_qubits = [1])
                print(f"测量第1号量子比特2048次的结果是{result}")

        ::

            测量第1号量子比特2048次的结果是{'0': 964, '1': 1084}

        .. code-block:: python
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
            with paddle.fluid.dygraph.guard():
                cir = UAnsatz(2)
                cir.h(0)
                cir.cnot([0,1])
                cir.run_state_vector()
                result = cir.measure(shots = 0, which_qubits = [1])
                print(f"测量第1号量子比特的概率结果是{result}")

        ::

            测量第1号量子比特的概率结果是{'0': 0.4999999999999999, '1': 0.4999999999999999}
        """
        if self.__run_state == 'state_vector':
            state = self.__state
        elif self.__run_state == 'density_matrix':
            # Take the diagonal of the density matrix as a probability distribution
            diag = np.diag(self.__state.numpy())
            state = fluid.dygraph.to_variable(np.sqrt(diag))
        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):
                result[dic10to2[i]] = (state.real[i] ** 2 + state.imag[i] ** 2).numpy()[0]

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

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

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

    def expecval(self, H):
        r"""量子线路输出的量子态关于可观测量H的期望值。

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

        代码示例:
        
        .. code-block:: python
            
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 5
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
            theta = np.ones(3)
            input_state = np.ones(2**n)+0j
            input_state = input_state / np.linalg.norm(input_state)
            with fluid.dygraph.guard():
                input_state_var = fluid.dygraph.to_variable(input_state)
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.rx(theta[0], 0)
                cir.rz(theta[1], 1)
                cir.rx(theta[2], 2)
                cir.run_state_vector(input_state_var)
                expect_value = cir.expecval(H_info).numpy()
                print(f'计算得到的{H_info}期望值是{expect_value}')
        
        ::
        
            计算得到的[[0.1, 'x1'], [0.2, 'y0,z4']]期望值是[0.05403023]
        
        .. code-block:: python
            
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 5
            H_info = [[0.1, 'x1'], [0.2, 'y0,z4']]
            theta = np.ones(3)
            input_state = np.diag(np.arange(2**n))+0j
            input_state = input_state / np.trace(input_state)
            with fluid.dygraph.guard():
                input_state_var = fluid.dygraph.to_variable(input_state)
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.rx(theta[0], 0)
                cir.ry(theta[1], 1)
                cir.rz(theta[2], 2)
                cir.run_density_matrix(input_state_var)
                expect_value = cir.expecval(H_info).numpy()
                print(f'计算得到的{H_info}期望值是{expect_value}')
        
        ::

            计算得到的[[0.1, 'x1'], [0.2, 'y0,z4']]期望值是[-0.02171538]
        """
        if self.__run_state == 'state_vector':
            return vec_expecval(H, self.__state).real
        elif self.__run_state == 'density_matrix':
            state = self.__state
            H_mat = fluid.dygraph.to_variable(pauli_str_to_matrix(H, self.n))
            return trace(matmul(state, H_mat)).real
        else:
            # Raise error
            raise ValueError("no state for measurement; please run the circuit first")
Q
Quleaf 已提交
715 716

    """
Q
Quleaf 已提交
717
    Circuit Templates
Q
Quleaf 已提交
718 719
    """

Q
Quleaf 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    def superposition_layer(self):
        r"""添加一层Hadamard门。

        代码示例:

        .. code-block:: python
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
            with paddle.fluid.dygraph.guard():
                cir = UAnsatz(2)
                cir.superposition_layer()
                cir.run_state_vector()
                result = cir.measure(shots = 0)
                print(f"测量全部量子比特的结果是{result}")

        ::

            测量全部量子比特结果是{'00': 0.2499999999999999, '01': 0.2499999999999999, '10': 0.2499999999999999, '11': 0.2499999999999999}
Q
Quleaf 已提交
739
        """
Q
Quleaf 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
        for i in range(self.n):
            self.h(i)

    def weak_superposition_layer(self):
        r"""添加一层Hadamard的平方根门,即 :math:`\sqrt{H}` 门。

        代码示例:

        .. code-block:: python
        
            import paddle
            from paddle_quantum.circuit import UAnsatz
            with paddle.fluid.dygraph.guard():
                cir = UAnsatz(2)
                cir.weak_superposition_layer()
                cir.run_state_vector()
                result = cir.measure(shots = 0)
                print(f"测量全部量子比特的结果是{result}")

        ::

            测量全部量子比特的结果是{'00': 0.7285533905932737, '01': 0.12500000000000003, '10': 0.12500000000000003, '11': 0.021446609406726238}
Q
Quleaf 已提交
762
        """
Q
Quleaf 已提交
763 764 765
        _theta = fluid.dygraph.to_variable(np.array([np.pi / 4]))  # Used in fixed Ry gate
        for i in range(self.n):
            self.ry(_theta, i)
Q
Quleaf 已提交
766

Q
Quleaf 已提交
767 768
    def real_entangled_layer(self, theta, depth):
        r"""添加一层包含Ry门的强纠缠层。
Q
Quleaf 已提交
769

Q
Quleaf 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        Note:
            这一层量子门的数学表示形式为实数酉矩阵。
        
        Attention:
            ``theta`` 的维度为 ``(depth, n, 1)``
        
        Args:
            theta (Variable): Ry门的旋转角度
            depth (int): 纠缠层的深度

        代码示例:

        .. code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
            theta = np.ones([DEPTH, n, 1])
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.real_entangled_layer(fluid.dygraph.to_variable(theta), DEPTH)
                cir.run_state_vector()
                print(cir.measure(shots = 0))
        
        ::

            {'00': 2.52129874867343e-05, '01': 0.295456784923382, '10': 0.7045028818254718, '11': 1.5120263659845063e-05}
Q
Quleaf 已提交
800
        """
Q
Quleaf 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        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'
        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'

        for repeat in range(depth):
            for i in range(self.n):
                self.ry(theta=theta[repeat][i][0], which_qubit=i)
            for i in range(self.n - 1):
                self.cnot(control=[i, i + 1])
            self.cnot([self.n - 1, 0])

    def complex_entangled_layer(self, theta, depth):
        r"""添加一层包含U3门的强纠缠层。

        Note:
            这一层量子门的数学表示形式为复数酉矩阵。
        
        Attention:
            ``theta`` 的维度为 ``(depth, n, 3)`` ,最低维内容为对应的 ``u3`` 的参数 ``(theta, phi, lam)``
        
        Args:
            theta (Variable): U3门的旋转角度
            depth (int): 纠缠层的深度

        代码示例:

        .. code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 2
            DEPTH = 3
            theta = np.ones([DEPTH, n, 1])
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.complex_entangled_layer(fluid.dygraph.to_variable(theta), DEPTH)
                cir.run_state_vector()
                print(cir.measure(shots = 0))
        
        ::

            {'00': 0.15032627279218896, '01': 0.564191201239618, '10': 0.03285998070292556, '11': 0.25262254526526823}
Q
Quleaf 已提交
847
        """
Q
Quleaf 已提交
848 849 850 851 852
        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'
        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'
Q
Quleaf 已提交
853

Q
Quleaf 已提交
854 855 856 857 858 859
        for repeat in range(depth):
            for i in range(self.n):
                self.u3(theta[repeat][i][0], theta[repeat][i][1], theta[repeat][i][2], i)
            for i in range(self.n - 1):
                self.cnot([i, i + 1])
            self.cnot([self.n - 1, 0])
Q
Quleaf 已提交
860

Q
Quleaf 已提交
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    def universal_2_qubit_gate(self, theta):
        r"""添加2-qubit通用门,这个通用门需要15个参数。

        Attention:
            只适用于量子比特数为2的量子线路。
        
        Args:
            theta (Variable): 2-qubit通用门的参数,其维度为 ``(15, )``

        代码示例:

        .. code-block:: python
        
            import numpy as np
            from paddle import fluid
            from paddle_quantum.circuit import UAnsatz
            n = 2
            theta = np.ones(15)
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.universal_2_qubit_gate(fluid.dygraph.to_variable(theta))
                cir.run_state_vector()
                print(cir.measure(shots = 0))
        
        ::

            {'00': 0.4306256106527819, '01': 0.07994547866706268, '10': 0.07994547866706264, '11': 0.40948343201309334}
Q
Quleaf 已提交
889
        """
Q
Quleaf 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
        assert self.n == 2, 'It only works on 2-qubit circuit'
        assert len(theta.shape) == 1, 'The shape of theta is not right'
        assert len(theta) == 15, 'This Ansatz accepts 15 parameters'

        self.u3(theta[0], theta[1], theta[2], 0)
        self.u3(theta[3], theta[4], theta[5], 1)

        self.cnot([1, 0])

        self.rz(theta[6], 0)
        self.ry(theta[7], 1)

        self.cnot([0, 1])

        self.ry(theta[8], 1)

        self.cnot([1, 0])

        self.u3(theta[9], theta[10], theta[11], 0)
        self.u3(theta[12], theta[13], theta[14], 1)

    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 已提交
917
        """
Q
Quleaf 已提交
918 919 920 921
        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 已提交
922

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

Q
Quleaf 已提交
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
        self.ry(theta[2], position[0])
        self.ry(theta[3], position[1])

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

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

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

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

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

        Note:
            这是内部函数,你并不需要直接调用到该函数。
Q
Quleaf 已提交
951
        """
Q
Quleaf 已提交
952 953 954 955 956 957 958 959 960 961 962
        assert theta.shape[1] == 4 and theta.shape[0] == (position[1] - position[0] + 1) / 2,\
            'the shape of theta is not right'
        for i in range(position[0], position[1], 2):
            self.__add_real_block(theta[int((i - position[0]) / 2)], [i, i + 1])

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

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

Q
Quleaf 已提交
969 970
    def real_block_layer(self, theta, depth):
        r"""添加一层包含Ry门的弱纠缠层。
Q
Quleaf 已提交
971

Q
Quleaf 已提交
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
        Note:
            这一层量子门的数学表示形式为实数酉矩阵。
        
        Attention:
            ``theta`` 的维度为 ``(depth, n-1, 4)``
        
        Args:
            theta(Variable): Ry门的旋转角度
            depth(int): 纠缠层的深度

        代码示例:

        .. code-block:: python
        
            n = 4
            DEPTH = 3
            theta = np.ones([DEPTH, n-1, 4])  
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.real_block_layer(fluid.dygraph.to_variable(theta), DEPTH)
                cir.run_density_matrix()
                print(cir.measure(shots = 0, which_qubits = [0]))
        
        ::

            {'0': 0.9646724056906162, '1': 0.035327594309385896}
Q
Quleaf 已提交
999
        """
Q
Quleaf 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
        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):
        r"""添加一层包含U3门的弱纠缠层。
        
        Note:
            这一层量子门的数学表示形式为复数酉矩阵。

        Attention:
            ``theta`` 的维度为 ``(depth, n-1, 12)``
        
        Args:
            theta (Variable): U3门的角度信息
            depth (int): 纠缠层的深度

        代码示例:

        .. code-block:: python
        
            n = 4
            DEPTH = 3
            theta = np.ones([DEPTH, n-1, 12])  
            with fluid.dygraph.guard():
                theta = fluid.dygraph.to_variable(theta)
                cir = UAnsatz(n)
                cir.complex_block_layer(fluid.dygraph.to_variable(theta), DEPTH)
                cir.run_density_matrix()
                print(cir.measure(shots = 0, which_qubits = [0]))
        
        ::
    
            {'0': 0.5271554811768046, '1': 0.4728445188231988}
Q
Quleaf 已提交
1046
        """
Q
Quleaf 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        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 已提交
1063

Q
Quleaf 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
def local_H_prob(cir, hamiltonian, shots=1024):
    r"""
    构造出Pauli测量电路并测量ancilla,处理实验结果来得到 ``H`` (只有一项)期望值的实验测量值。

    Note:
        这是内部函数,你并不需要直接调用到该函数。
    """
    # Add one ancilla, which we later measure and process the result
    new_cir = UAnsatz(cir.n + 1)
    input_state = pp_kron(cir.run_state_vector(store_state=False), init_state_gen(1))
    # Used in fixed Rz gate
    _theta = fluid.dygraph.to_variable(np.array([-np.pi / 2]))

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

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

    return result


def H_prob(cir, H, shots=1024):
    r"""构造Pauli测量电路并测量关于H的期望值。
    
    Args:
        cir (UAnsatz): UAnsatz的一个实例化对象
        H (list): 记录哈密顿量信息的列表
        shots (int, optional): 默认为1024,表示测量次数;若为0,则表示返回测量期望值的精确值,即测量无穷次后的期望值
    
    Returns:
        float: 测量得到的H的期望值
    
    代码示例:

    .. code-block:: python
        
        import numpy as np
        from paddle import fluid
        from paddle_quantum.circuit import UAnsatz, H_prob
        n = 4
        theta = np.ones(3)
        experiment_shots = 2**10
        H_info = [[0.1, 'x2'], [0.3, 'y1,z3']]
        input_state = np.ones(2**n)+0j
        input_state = input_state / np.linalg.norm(input_state)
        with fluid.dygraph.guard():
            theta = fluid.dygraph.to_variable(theta)
            cir = UAnsatz(n)
            cir.rx(theta[0], 0)
            cir.ry(theta[1], 1)
            cir.rz(theta[2], 1)
            result_1 = H_prob(cir, H_info, shots = experiment_shots)
            result_2 = H_prob(cir, H_info, shots = 0)
            print(f'消耗 {experiment_shots} 次测量后的期望值实验值是 {result_1}')
            print(f'H期望值精确值是 {result_2}')

    ::

        消耗 1024 次测量后的期望值实验值是 0.2326171875
        H期望值精确值是 0.21242202548207134
    """
    expval = 0
    for term in H:
        expval += term[0] * local_H_prob(cir, term[1], shots=shots)
    return expval