simulator.py 31.4 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 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
"""
This simulator uses statevector(Tensor) to simulate quantum behaviors.
Basically, the core of the algorithm is tensor contraction with one-way calculation that each gate is
contracted to the init vector when imported by the program. All the states including the gate and init
are converted to TENSOR and the calculating is also around tensor.

:DEBUG INFO:
Sim2
-Sim2Main.py: this file, main entry of sim2
-InitProcess.py: Initial the state.
-StateTransfer.py: Decide the gate matrix by gate name and real state process.
-TransferProcess.py: Real transfer state process
-MeasureProcess.py: Measure process
Ancilla
-Random Circuit: Generate random circuit by requiring qubits and circuit depth
-DEFINE_GATE: Gate matrix.
Two measure types are provided: Meas_MED = MEAS_METHOD.PROB and Meas_MED = MEAS_METHOD.SINGLE. PROB is the sample with
probability and SINGLE is by the state collapse method. Former is significant faster than the later.
"""

import numpy as np
import paddle
import gc
from collections import Counter
import copy
from interval import Interval
from enum import Enum
import random


Q
Quleaf 已提交
45
# InitProcess
Q
Quleaf 已提交
46 47 48 49 50 51
def init_state_10(n):
    """
    Generate state with n qubits
    :param n: number of qubits
    :return: tensor of state
    """
Q
Quleaf 已提交
52 53 54 55
    state1 = paddle.ones([1], 'float64')
    state0 = paddle.zeros([2 ** n - 1], 'float64')
    state = paddle.concat([state1, state0])
    del state1, state0
Q
Quleaf 已提交
56
    gc.collect()  # free the intermediate big data immediately
Q
Quleaf 已提交
57
    state = paddle.cast(state, 'complex128')
Q
Quleaf 已提交
58 59 60 61 62
    gc.collect()  # free the intermediate big data immediately

    return state


Q
Quleaf 已提交
63
def init_state_gen(n, i=0):
Q
Quleaf 已提交
64 65 66 67 68 69
    """
    Generate state with n qubits
    :param n: number of qubits
    :param i: the ith vector in computational basis
    :return: tensor of state
    """
Q
Quleaf 已提交
70
    assert 0 <= i < 2 ** n, 'Invalid index'
Q
Quleaf 已提交
71

Q
Quleaf 已提交
72 73 74
    state = np.zeros([2 ** n], dtype=np.complex128)
    state[i] = 1
    state = paddle.to_tensor(state)
Q
Quleaf 已提交
75 76

    return state
Q
Quleaf 已提交
77 78


Q
Quleaf 已提交
79
# Define gate
Q
Quleaf 已提交
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
def x_gate_matrix():
    """
    Pauli x
    :return:
    """
    return np.array([[0, 1],
                     [1, 0]], dtype=complex)


def y_gate_matrix():
    """
    Pauli y
    :return:
    """
    return np.array([[0, -1j],
                     [1j, 0]], dtype=complex)


def z_gate_matrix():
    """
    Pauli y
    :return:
    """
    return np.array([[1, 0],
                     [0, -1]], dtype=complex)


def h_gate_matrix():
    """
    Hgate
    :return:
    """
    isqrt_2 = 1.0 / np.sqrt(2.0)
    return np.array([[isqrt_2, isqrt_2],
                     [isqrt_2, -isqrt_2]], dtype=complex)


def u_gate_matrix(params):
    """
    U3
    :param params:
    :return:
    """
    theta, phi, lam = params

Q
Quleaf 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    if (type(theta) is paddle.Tensor and
            type(phi) is paddle.Tensor and
            type(lam) is paddle.Tensor):
        re_a = paddle.cos(theta / 2)
        re_b = - paddle.cos(lam) * paddle.sin(theta / 2)
        re_c = paddle.cos(phi) * paddle.sin(theta / 2)
        re_d = paddle.cos(phi + lam) * paddle.cos(theta / 2)
        im_a = paddle.zeros([1], 'float64')
        im_b = - paddle.sin(lam) * paddle.sin(theta / 2)
        im_c = paddle.sin(phi) * paddle.sin(theta / 2)
        im_d = paddle.sin(phi + lam) * paddle.cos(theta / 2)

        re = paddle.reshape(paddle.concat([re_a, re_b, re_c, re_d]), [2, 2])
        im = paddle.reshape(paddle.concat([im_a, im_b, im_c, im_d]), [2, 2])

        return re + im * paddle.to_tensor([1j], 'complex128')
Q
Quleaf 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    elif (type(theta) is float and
          type(phi) is float and
          type(lam) is float):
        return np.array([[np.cos(theta / 2),
                          -np.exp(1j * lam) * np.sin(theta / 2)],
                         [np.exp(1j * phi) * np.sin(theta / 2),
                          np.exp(1j * phi + 1j * lam) * np.cos(theta / 2)]])
    else:
        assert False


# compare the paddle and np version, they should be equal
# a = u_gate_matrix([1.0, 2.0, 3.0])
# print(a)
Q
Quleaf 已提交
155 156 157 158
# a = u_gate_matrix([paddle.to_tensor(np.array([1.0])),
#                    paddle.to_tensor(np.array([2.0])),
#                    paddle.to_tensor(np.array([3.0]))])
# print(a.numpy())
Q
Quleaf 已提交
159

Q
Quleaf 已提交
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
def cu_gate_matrix(params):
    """
    Control U3
    :return:
    """
    theta, phi, lam = params

    if (type(theta) is paddle.Tensor and
            type(phi) is paddle.Tensor and
            type(lam) is paddle.Tensor):
        re_a = paddle.cos(theta / 2)
        re_b = - paddle.cos(lam) * paddle.sin(theta / 2)
        re_c = paddle.cos(phi) * paddle.sin(theta / 2)
        re_d = paddle.cos(phi + lam) * paddle.cos(theta / 2)
        im_a = paddle.zeros([1], 'float64')
        im_b = - paddle.sin(lam) * paddle.sin(theta / 2)
        im_c = paddle.sin(phi) * paddle.sin(theta / 2)
        im_d = paddle.sin(phi + lam) * paddle.cos(theta / 2)

        re = paddle.reshape(paddle.concat([re_a, re_b, re_c, re_d]), [2, 2])
        im = paddle.reshape(paddle.concat([im_a, im_b, im_c, im_d]), [2, 2])

        id = paddle.eye(2, dtype='float64')
        z2 = paddle.zeros(shape=[2,2], dtype='float64')

        re = paddle.concat([paddle.concat([id, z2], -1), paddle.concat([z2, re], -1)])
        im = paddle.concat([paddle.concat([z2, z2], -1), paddle.concat([z2, im], -1)])

        return re + im * paddle.to_tensor([1j], 'complex128')

    elif (type(theta) is float and
          type(phi) is float and
          type(lam) is float):
        u3 = np.array([[np.cos(theta / 2),
                    -np.exp(1j * lam) * np.sin(theta / 2)],
                   [np.exp(1j * phi) * np.sin(theta / 2),
                    np.exp(1j * phi + 1j * lam) * np.cos(theta / 2)]])
        return np.block([
            [np.eye(2, dtype=float), np.zeros((2, 2), dtype=float)], [np.zeros((2, 2), dtype=float), u3]
        ]).reshape((2,2,2,2))

    else:
        assert False

Q
Quleaf 已提交
204 205 206 207 208 209 210 211 212

def cx_gate_matrix():
    """
    Control Not
    :return:
    """
    return np.array([[1, 0, 0, 0],
                     [0, 1, 0, 0],
                     [0, 0, 0, 1],
Q
Quleaf 已提交
213 214
                     [0, 0, 1, 0]], dtype=complex).reshape((2, 2, 2, 2))

Q
Quleaf 已提交
215

Q
Quleaf 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
def cy_gate_matrix():
    """
    Control Y
    :return:
    """
    return np.array([[1, 0, 0, 0],
                     [0, 1, 0, 0],
                     [0, 0, 0, -1j],
                     [0, 0, 1j, 0]], dtype=complex).reshape((2, 2, 2, 2))


def cz_gate_matrix():
    """
    Control Z
    :return:
    """
    return np.array([[1, 0, 0, 0],
                     [0, 1, 0, 0],
                     [0, 0, 1, 0],
                     [0, 0, 0, -1]], dtype=complex).reshape((2, 2, 2, 2))


Q
Quleaf 已提交
238 239
def swap_gate_matrix():
    """
Q
Quleaf 已提交
240
    Swap gate
Q
Quleaf 已提交
241 242 243 244 245 246 247
    :return:
    """
    return np.array([[1, 0, 0, 0],
                     [0, 0, 1, 0],
                     [0, 1, 0, 0],
                     [0, 0, 0, 1]], dtype=complex).reshape(2, 2, 2, 2)

Q
Quleaf 已提交
248

Q
Quleaf 已提交
249 250 251 252 253
def rxx_gate_matrix(params):
    """
    RXX gate
    :return:
    """
Q
Quleaf 已提交
254
    theta = params[0]
Q
Quleaf 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    re_a = paddle.cos(theta / 2)
    re_b = paddle.zeros([1], 'float64')
    im_a = paddle.sin(theta / 2)
    im_b = paddle.zeros([1], 'float64')
    re = paddle.reshape(paddle.concat([re_a, re_b, re_b, re_b, 
                                       re_b, re_a, re_b, re_b, 
                                       re_b, re_b, re_a, re_b, 
                                       re_b, re_b, re_b, re_a]), [4, 4])
    im = paddle.reshape(paddle.concat([im_b, im_b, im_b, im_a, 
                                       im_b, im_b, im_a, im_b, 
                                       im_b, im_a, im_b, im_b, 
                                       im_a, im_b, im_b, im_b]), [4, 4])

    return re - im * paddle.to_tensor([1j], 'complex128')


def ryy_gate_matrix(params):
    """
    RYY gate
    :return:
    """
Q
Quleaf 已提交
276
    theta = params[0]
Q
Quleaf 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    re_a = paddle.cos(theta / 2)
    re_b = paddle.zeros([1], 'float64')
    im_a = paddle.sin(theta / 2)
    im_b = paddle.zeros([1], 'float64')
    re = paddle.reshape(paddle.concat([re_a, re_b, re_b, re_b, 
                                       re_b, re_a, re_b, re_b, 
                                       re_b, re_b, re_a, re_b, 
                                       re_b, re_b, re_b, re_a]), [4, 4])
    im = paddle.reshape(paddle.concat([im_b, im_b, im_b, im_a, 
                                       im_b, im_b, -im_a, im_b, 
                                       im_b, -im_a, im_b, im_b, 
                                       im_a, im_b, im_b, im_b]), [4, 4])

    return re + im * paddle.to_tensor([1j], 'complex128')


def rzz_gate_matrix(params):
    """
    RZZ gate
    :return:
    """
Q
Quleaf 已提交
298
    theta = params[0]
Q
Quleaf 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    re_a = paddle.cos(theta / 2)
    re_b = paddle.zeros([1], 'float64')
    im_a = paddle.sin(theta / 2)
    im_b = paddle.zeros([1], 'float64')
    re = paddle.reshape(paddle.concat([re_a, re_b, re_b, re_b, 
                                       re_b, re_a, re_b, re_b, 
                                       re_b, re_b, re_a, re_b, 
                                       re_b, re_b, re_b, re_a]), [4, 4])
    im = paddle.reshape(paddle.concat([-im_a, im_b, im_b, im_b, 
                                       im_b, im_a, im_b, im_b, 
                                       im_b, im_b, im_a, im_b, 
                                       im_b, im_b, im_b, -im_a]), [4, 4])
                                       
    return re + im * paddle.to_tensor([1j], 'complex128')

Q
Quleaf 已提交
314

Q
Quleaf 已提交
315
# PaddleE
Q
Quleaf 已提交
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
def normalize_axis(axis, ndim):
    if axis < 0:
        axis += ndim

    if axis >= ndim or axis < 0:
        raise ValueError("Invalid axis index %d for ndim=%d" % (axis, ndim))

    return axis


def _operator_index(a):
    return a.__index__()


def _normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
    # Optimization to speed-up the most common cases.
    if type(axis) not in (tuple, list):
        try:
            axis = [_operator_index(axis)]
        except TypeError:
            pass
    # Going via an iterator directly is slower than via list comprehension.
    axis = tuple([normalize_axis(ax, ndim) for ax in axis])
    if not allow_duplicate and len(set(axis)) != len(axis):
        if argname:
            raise ValueError('repeated axis in `{}` argument'.format(argname))
        else:
            raise ValueError('repeated axis')
    return axis


def moveaxis(m, source, destination):
    """
    extend paddle
    :param m:
    :param source:
    :param destination:
    :return:
    """
    source = _normalize_axis_tuple(source, len(m.shape), 'source')
    destination = _normalize_axis_tuple(destination, len(m.shape), 'destination')
    if len(source) != len(destination):
        raise ValueError('`source` and `destination` arguments must have '
                         'the same number of elements')

    order = [n for n in range(len(m.shape)) if n not in source]

    for dest, src in sorted(zip(destination, source)):
        order.insert(dest, src)

Q
Quleaf 已提交
366
    result = paddle.transpose(m, order)
Q
Quleaf 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    return result


def complex_moveaxis(m, source, destination):
    """
    extend paddle
    :param m:
    :param source:
    :param destination:
    :return:
    """
    source = _normalize_axis_tuple(source, len(m.shape), 'source')
    destination = _normalize_axis_tuple(destination, len(m.shape), 'destination')
    if len(source) != len(destination):
        raise ValueError('`source` and `destination` arguments must have '
                         'the same number of elements')

    order = [n for n in range(len(m.shape)) if n not in source]

    for dest, src in sorted(zip(destination, source)):
        order.insert(dest, src)

Q
Quleaf 已提交
389
    result = paddle.transpose(m, order)
Q
Quleaf 已提交
390 391 392
    return result


Q
Quleaf 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405
# def complex_abs(m):
#     # check1 = np.abs(m.numpy())
#
#     re = paddle.multiply(paddle.real(m), paddle.real(m))
#     im = paddle.multiply(paddle.imag(m), paddle.imag(m))
#     m = paddle.add(re, im)
#     m = paddle.sqrt(m)
#     # m = paddle.pow(m, paddle.ones_like(m) * 0.5)
#
#     # check2 = m.numpy()
#     # assert (check1 == check2).all()
#
#     return m
Q
Quleaf 已提交
406

Q
Quleaf 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
def get_cswap_state(state, bits):
    """
    Transfer to the next state after applying CSWAP gate
    :param state:
    :param bits:
    :return:
    """
    q0 = bits[0]
    q1 = bits[1]
    q2 = bits[2]

    # helper angles
    theta0 = paddle.to_tensor(np.array([0.0]))
    thetan2 = paddle.to_tensor(np.array([-np.pi / 2], np.float64))
    theta2 = paddle.to_tensor(np.array([np.pi / 2], np.float64))
    thetan4 = paddle.to_tensor(np.array([-np.pi / 4], np.float64))
    theta4 = paddle.to_tensor(np.array([np.pi / 4], np.float64))

    # implements cswap gate using cnot and Single-qubit gates
    state = transfer_state(state, cx_gate_matrix(), [q2, q1])
    state = transfer_state(state, u_gate_matrix([thetan2, theta0, theta0]), [q2]) # ry
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q0]) # rz
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q1]) # rz
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q2]) # rz
    state = transfer_state(state, cx_gate_matrix(), [q0, q1])
    state = transfer_state(state, cx_gate_matrix(), [q1, q2])
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q1]) # rz
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q2]) # rz
    state = transfer_state(state, cx_gate_matrix(), [q0, q1])
    state = transfer_state(state, cx_gate_matrix(), [q1, q2])
    state = transfer_state(state, cx_gate_matrix(), [q0, q1])
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q2]) # rz
    state = transfer_state(state, cx_gate_matrix(), [q1, q2])
    state = transfer_state(state, u_gate_matrix([theta2, thetan2, theta2]), [q1]) # rx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q2]) # rz
    state = transfer_state(state, cx_gate_matrix(), [q0, q1])
    state = transfer_state(state, cx_gate_matrix(), [q1, q2])
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta2]), [q2]) # rz
    state = transfer_state(state, u_gate_matrix([theta2, thetan2, theta2]), [q1]) # rx
    state = transfer_state(state, u_gate_matrix([thetan2, thetan2, theta2]), [q2]) # rx
    
    return state


def get_ccx_state(state, bits):
    """
    Transfer to the next state after applying CCX gate
    :param state:
    :param bits:
    :return:
    """
    q0 = bits[0]
    q1 = bits[1]
    q2 = bits[2]

    # helper angles
    theta0 = paddle.to_tensor(np.array([0.0]))
    theta2 = paddle.to_tensor(np.array([np.pi / 2], np.float64))
    thetan4 = paddle.to_tensor(np.array([-np.pi / 4], np.float64))
    theta4 = paddle.to_tensor(np.array([np.pi / 4], np.float64))

    # implements ccx gate using cnot and Single-qubit gates
    state = transfer_state(state, h_gate_matrix(), [q2])  #h
    state = transfer_state(state, cx_gate_matrix(), [q1, q2])  # cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q2])  # tdagger
    state = transfer_state(state, cx_gate_matrix(), [q0, q2])  #cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q2])  # t
    state = transfer_state(state, cx_gate_matrix(), [q1, q2]) #cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q2])  # tdagger
    state = transfer_state(state, cx_gate_matrix(), [q0, q2])  # cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q1])  # tdagger
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q2])  # t
    state = transfer_state(state, h_gate_matrix(), [q2])  # h
    state = transfer_state(state, cx_gate_matrix(), [q0, q1]) #cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, thetan4]), [q1])  # tdagger
    state = transfer_state(state, cx_gate_matrix(), [q0, q1]) #cx
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta4]), [q0])  # t
    state = transfer_state(state, u_gate_matrix([theta0, theta0, theta2]), [q1])  # s
    return state

Q
Quleaf 已提交
487

Q
Quleaf 已提交
488
# TransferProcess
Q
Quleaf 已提交
489 490 491 492 493 494 495 496 497
def transfer_state(state, gate_matrix, bits):
    """
    Transfer to the next state
    :param state:
    :param gate_matrix:
    :param bits:
    :return:
    """

Q
Quleaf 已提交
498 499
    assert (type(gate_matrix) is np.ndarray) or \
           (type(gate_matrix) is paddle.Tensor and gate_matrix.dtype.name == "COMPLEX128")
Q
Quleaf 已提交
500

Q
Quleaf 已提交
501
    assert type(state) is paddle.Tensor and state.dtype.name == "COMPLEX128" and len(state.shape) == 1
Q
Quleaf 已提交
502 503 504 505 506 507 508 509
    # calc source_pos target_pos
    n = int(np.log2(state.shape[0]))
    source_pos = copy.deepcopy(bits)  # copy bits, it should NOT change the order of bits
    # source_pos = [n - 1 - idex for idex in source_pos]  # qubit index
    # source_pos = list(reversed(source_pos))  # reverse qubit index
    target_pos = list(range(len(bits)))

    # ### check
Q
Quleaf 已提交
510 511
    # state_check = transfer_state(paddle.reshape(state, [2] * n), gate_matrix, bits)
    # state_check = paddle.reshape(state_check, [2 ** n])
Q
Quleaf 已提交
512 513 514

    # compressed moveaxis
    # compress the continuous dim before moveaxis
Q
Quleaf 已提交
515 516 517 518
    # e.g. single operand: before moveaxis 2*2*[2]*2*2 -compress-> 4*[2]*4,
    #   after moveaxis [2]*2*2*2*2 -compress-> [2]*4*4
    # double operands: before moveaxis 2*2*[2]*2*2*[2]*2*2 -compress-> 4*[2]*4*[2]*4,
    #   after moveaxis [2]*[2]*2*2*2*2*2*2 -compress-> [2]*[2]*4*4*4
Q
Quleaf 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    # the peak rank is 5 when the number of operands is 2
    assert len(source_pos) == 1 or len(source_pos) == 2
    compressed_shape_before_moveaxis = [1]
    compressed_source_pos = [-1] * len(source_pos)
    for i in range(n):
        if i in source_pos:
            compressed_source_pos[source_pos.index(i)] = len(compressed_shape_before_moveaxis)
            compressed_shape_before_moveaxis.append(2)
            compressed_shape_before_moveaxis.append(1)
        else:
            compressed_shape_before_moveaxis[-1] = compressed_shape_before_moveaxis[-1] * 2
    # print([2] * n)
    # print(source_pos)
    # print('->')
    # print(compressed_shape)
    # print(compressed_source_pos)  # always [1], [1, 3], or [3, 1]
Q
Quleaf 已提交
535
    state = paddle.reshape(state, compressed_shape_before_moveaxis)
Q
Quleaf 已提交
536 537 538 539 540
    state = complex_moveaxis(state, compressed_source_pos, target_pos)
    compressed_shape_after_moveaxis = state.shape

    # reshape
    state_new_shape = [2 ** len(bits), 2 ** (n - len(bits))]
Q
Quleaf 已提交
541
    state = paddle.reshape(state, state_new_shape)
Q
Quleaf 已提交
542 543 544 545 546

    # gate_matrix
    if type(gate_matrix) is np.ndarray:
        gate_new_shape = [2 ** (len(gate_matrix.shape) - len(bits)), 2 ** len(bits)]
        gate_matrix = gate_matrix.reshape(gate_new_shape)
Q
Quleaf 已提交
547 548
        gate_matrix = paddle.to_tensor(gate_matrix)
    elif type(gate_matrix) is paddle.Tensor and gate_matrix.dtype.name == "COMPLEX128":
Q
Quleaf 已提交
549 550 551 552 553
        pass
    else:
        assert False

    # matmul
Q
Quleaf 已提交
554
    state = paddle.matmul(gate_matrix, state)
Q
Quleaf 已提交
555 556

    # restore compressed moveaxis reshape
Q
Quleaf 已提交
557
    state = paddle.reshape(state, compressed_shape_after_moveaxis)
Q
Quleaf 已提交
558
    state = complex_moveaxis(state, target_pos, compressed_source_pos)
Q
Quleaf 已提交
559
    state = paddle.reshape(state, [2 ** n])
Q
Quleaf 已提交
560 561 562 563 564 565 566

    # ### check
    # assert (np.all(state.numpy() == state_check.numpy()))

    return state


Q
Quleaf 已提交
567 568
# StateTransfer
def StateTransfer(state, gate_name, bits, params=None):
Q
Quleaf 已提交
569 570 571
    """
    To transfer state by only gate name and bits
    :param state: the last step state, can be init vector or  the last step vector.
Q
Quleaf 已提交
572
    :param gate_name:x,y,z,h,CNOT, SWAP
Q
Quleaf 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    :param bits: the gate working on the bits.
    :param params: params for u gate.
    :return: the updated state
    """
    if gate_name == 'h':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = h_gate_matrix()
    elif gate_name == 'x':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = x_gate_matrix()
    elif gate_name == 'y':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = y_gate_matrix()
    elif gate_name == 'z':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = z_gate_matrix()
    elif gate_name == 'CNOT':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = cx_gate_matrix()
Q
Quleaf 已提交
592 593 594 595 596 597 598 599 600
    elif gate_name == 'CU':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = cu_gate_matrix(params)
    elif gate_name == 'cy':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = cy_gate_matrix()
    elif gate_name == 'cz':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = cz_gate_matrix()
Q
Quleaf 已提交
601 602 603
    elif gate_name == 'SWAP':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = swap_gate_matrix()
Q
Quleaf 已提交
604 605 606
    elif gate_name == 'u':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = u_gate_matrix(params)
Q
Quleaf 已提交
607 608 609 610 611 612 613 614 615
    elif gate_name == 'RXX_gate':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = rxx_gate_matrix(params)
    elif gate_name == 'RYY_gate':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = ryy_gate_matrix(params)
    elif gate_name == 'RZZ_gate':
        # print('----------', gate_name, bits, '----------')
        gate_matrix = rzz_gate_matrix(params)
Q
Quleaf 已提交
616 617 618 619 620 621 622 623
    elif gate_name == 'CSWAP':
        # print('----------', gate_name, bits, '----------')
        state = get_cswap_state(state, bits)
        return state
    elif gate_name == 'CCX':
        # print('----------', gate_name, bits, '----------')
        state = get_ccx_state(state, bits)
        return state
Q
Quleaf 已提交
624 625 626 627 628 629 630
    else:
        raise Exception("Gate name error")

    state = transfer_state(state, gate_matrix, bits)
    return state


Q
Quleaf 已提交
631
# MeasureProcess
Q
Quleaf 已提交
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
class MEAS_METHOD(Enum):
    """
    To control the measure method
    """
    SINGLE = 1
    PROB = 2


Meas_MED = MEAS_METHOD.PROB


def oct_to_bin_str(oct_number, n):
    """
    Oct to bin by real order
    :param oct_number:
    :param n:
    :return:
    """
    bin_string = bin(oct_number)[2:].zfill(n)
    # return (''.join(reversed(bin_string)))
    return bin_string


def measure_single(state, bit):
    """
    Method one qubit one time
    :param state:
    :param bit:
    :return:
    """
    n = len(state.shape)
    axis = list(range(n))
    axis.remove(n - 1 - bit)
    probs = np.sum(np.abs(state) ** 2, axis=tuple(axis))
    rnd = np.random.rand()

    # measure single bit
    if rnd < probs[0]:
        out = 0
        prob = probs[0]
    else:
        out = 1
        prob = probs[1]

    # collapse single bit
    if out == 0:
        matrix = np.array([[1.0 / np.sqrt(prob), 0.0],
                           [0.0, 0.0]], complex)
    else:
        matrix = np.array([[0.0, 0.0],
                           [0.0, 1.0 / np.sqrt(prob)]], complex)
    state = transfer_state(state, matrix, [bit])

    return out, state


def measure_all(state):
    """
    Method all by single qubits
    :param state:
    :return:
    """
    n = len(state.shape)
    outs = ''
    for i in range(n):
        out, state = measure_single(state, i)  # measure qubit0 will collapse it
Q
Quleaf 已提交
698
        outs = str(out) + outs  # from low to high position
Q
Quleaf 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    return outs


def measure_by_single_accumulation(state, shots):
    """
    Method by accumulation, one shot one time
    :param state:
    :param shots:
    :return:
    """
    print("Measure method Single Accu")
    result = {}
    for i in range(shots):
        outs = measure_all(state)
        if outs not in result:
            result[outs] = 0
        result[outs] += 1
    return result


def measure_by_probability(state, times):
    """
    Measure by probability method
    :param state:
    :param times:
    :return:
    """
    # print("Measure method Probability")

Q
Quleaf 已提交
728
    assert type(state) is paddle.Tensor and state.dtype.name == "COMPLEX128" and len(state.shape) == 1
Q
Quleaf 已提交
729
    n = int(np.log2(state.shape[0]))
Q
Quleaf 已提交
730 731
    prob_array = paddle.abs(state)  # complex -> real
    prob_array = paddle.multiply(prob_array, prob_array)
Q
Quleaf 已提交
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    prob_array = prob_array.numpy()
    gc.collect()

    """
    prob_key = []
    prob_values = []
    pos_list = list(np.nonzero(prob_array)[0])
    for index in pos_list:
        string = oct_to_bin_str(index, n)
        prob_key.append(string)
        prob_values.append(prob_array[index])

    # print("The sum prob is ", sum(prob_values))

    samples = np.random.choice(len(prob_key), times, p=prob_values)
    """
    samples = np.random.choice(range(2 ** n), times, p=prob_array)
    count_samples = Counter(samples)
    result = {}
Q
Quleaf 已提交
751
    for idx in count_samples:
Q
Quleaf 已提交
752
        """
Q
Quleaf 已提交
753
        result[prob_key[idx]] = count_samples[idx]
Q
Quleaf 已提交
754
        """
Q
Quleaf 已提交
755
        result[oct_to_bin_str(idx, n)] = count_samples[idx]
Q
Quleaf 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    return result


def measure_state(state, shots):
    """
    Measure main entry
    :param state:
    :param shots:
    :return:
    """
    if Meas_MED == MEAS_METHOD.SINGLE:
        return measure_by_single_accumulation(state, shots)
    elif Meas_MED == MEAS_METHOD.PROB:
        return measure_by_probability(state, shots)
    else:
        raise Exception("Measure Error")


Q
Quleaf 已提交
774
# RandomCircuit
Q
Quleaf 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
def GenerateRandomCirc(state, circ_depth, n):
    """
    Generate random circ
    :param state: The whole state
    :param circ_depth: number of circuit
    :param n: number of qubits
    :return: state
    """
    gate_string = ['x', 'y', 'z', 'h', 'CNOT']
    internal_state = state
    for index in range(circ_depth):
        rand_gate_pos = random.randint(0, len(gate_string) - 1)
        if rand_gate_pos == (len(gate_string) - 1):
            rand_gate_bits = random.sample(range(n), 2)
        else:
            rand_gate_bits = random.sample(range(n), 1)
Q
Quleaf 已提交
791
        internal_state = StateTransfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
Q
Quleaf 已提交
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    state = internal_state
    return state


def GenerateRandomCircAndRev(state, circ_depth, n):
    """
    Generate random circ
    :param state: The whole state
    :param circ_depth: number of circuit
    :param n: number of qubits
    :return: state
    """
    rand_gate_pos_all = []
    rand_gate_bits_all = []
    gate_string = ['x', 'y', 'z', 'h', 'CNOT']
    internal_state = state
    for index in range(circ_depth):
        rand_gate_pos = random.randint(0, len(gate_string) - 1)
        if rand_gate_pos == (len(gate_string) - 1):
            rand_gate_bits = random.sample(range(n), 2)
        else:
            rand_gate_bits = random.sample(range(n), 1)

        rand_gate_pos_all.append(rand_gate_pos)
        rand_gate_bits_all.append(rand_gate_bits)

Q
Quleaf 已提交
818
        internal_state = StateTransfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
Q
Quleaf 已提交
819 820 821 822 823

    rand_gate_pos_all = list(reversed(rand_gate_pos_all))
    rand_gate_bits_all = list(reversed(rand_gate_bits_all))

    for idex, item in enumerate(rand_gate_pos_all):
Q
Quleaf 已提交
824
        internal_state = StateTransfer(internal_state, gate_string[item], rand_gate_bits_all[idex])
Q
Quleaf 已提交
825 826 827 828 829

    state = internal_state
    return state


Q
Quleaf 已提交
830
# Tester
Q
Quleaf 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
def RandomTestIt(bits_num, circ_num):
    """
    Random Check
    :param bits_num:
    :param circ_num:
    :return:
    """
    n = bits_num
    repeat_num = 1  # 2 ** 5
    state = init_state_10(n)

    for _ in range(repeat_num):
        # state = copy.deepcopy(state_origin)
        state = GenerateRandomCircAndRev(state, circ_num, n)
        re = measure_state(state, 2 ** 10)
        # print(re)
        assert (str('0' * n) in list(re.keys()))
        assert (2 ** 10 in list(re.values()))

    return True


def Test_x_h_CNOT():  # 3 bits coverage test
    """
    The smallest tester program
    :return:
    """
    state = init_state_10(3)

Q
Quleaf 已提交
860 861 862
    state = StateTransfer(state, 'x', [0])
    state = StateTransfer(state, 'h', [1])
    state = StateTransfer(state, 'CNOT', [1, 2])
Q
Quleaf 已提交
863 864 865 866 867 868 869 870 871 872 873 874 875 876
    re = measure_state(state, 2 ** 10)
    # print(re)
    assert ('001' in list(re.keys()) and '111' in list(re.keys()))
    assert (list(re.values())[0] / list(re.values())[1] in Interval(0.9, 1.1))
    return True


def Test_cnot_1():
    """
    Check CNOT using reverse circ
    :return:
    """
    state = init_state_10(3)

Q
Quleaf 已提交
877 878 879 880 881 882 883 884
    state = StateTransfer(state, 'h', [0])
    state = StateTransfer(state, 'CNOT', [0, 1])
    state = StateTransfer(state, 'CNOT', [0, 2])
    state = StateTransfer(state, 'CNOT', [1, 2])
    state = StateTransfer(state, 'CNOT', [1, 2])
    state = StateTransfer(state, 'CNOT', [0, 2])
    state = StateTransfer(state, 'CNOT', [0, 1])
    state = StateTransfer(state, 'h', [0])
Q
Quleaf 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897
    re = measure_state(state, 2 ** 10)
    assert ('000' in list(re.keys()))
    assert (2 ** 10 in list(re.values()))
    return True


def Test_cnot_2():
    """
    Check retation of CNOTS
    :return:
    """
    state = init_state_10(3)

Q
Quleaf 已提交
898 899 900 901 902 903 904 905
    state = StateTransfer(state, 'h', [2])
    state = StateTransfer(state, 'CNOT', [2, 1])
    state = StateTransfer(state, 'CNOT', [2, 0])
    state = StateTransfer(state, 'CNOT', [1, 0])
    state = StateTransfer(state, 'CNOT', [1, 0])
    state = StateTransfer(state, 'CNOT', [2, 0])
    state = StateTransfer(state, 'CNOT', [2, 1])
    state = StateTransfer(state, 'h', [2])
Q
Quleaf 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919
    re = measure_state(state, 2 ** 10)
    assert ('000' in list(re.keys()))
    assert (2 ** 10 in list(re.values()))
    return True


def Test3All():
    """
    Check all 3 qubits cases
    :return:
    """
    return Test_x_h_CNOT() and Test_cnot_1() and Test_cnot_2()


Q
Quleaf 已提交
920
# Sim2Main
Q
Quleaf 已提交
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
def main(bits_num=None, circ_num=None):
    """
    :param bits_num:  the number of qubits
    :param circ_num: the circuit depth to be expected
    These two args can be None type and the default behavior is bits_num =5 and circ_num=50.
     Two args must be given together.
    :return:
    :DEBUG INFO:
    1) np.random.seed(0) can be uncomment to guarantee the random sequence can be tracked.
    2) re is the return result: vector string: counter
    """

    # init seed
    # np.random.seed(0)

    print('----------', 'init', bits_num, 'bits', '----------')
    print('----------', 'init', circ_num, 'circ depth', '----------')

    state = init_state_10(bits_num)

    # ------------------tik-------
Q
Quleaf 已提交
942 943 944 945 946 947
    # state = StateTransfer(state, 'h', [0])
    # state = StateTransfer(state, 'x', [1])
    # state = StateTransfer(state, 'x', [2])
    # state = StateTransfer(state, 'u', [3], [0.3, 0.5, 0.7])
    # state = StateTransfer(state, 'CNOT', [0, 1])
    # state = StateTransfer(state, 'CNOT', [2, 1])
Q
Quleaf 已提交
948 949 950
    # -----------------tok---------

    # ------------------tik-------
Q
Quleaf 已提交
951 952 953
    state = StateTransfer(state, 'x', [0])
    state = StateTransfer(state, 'h', [1])
    # state = StateTransfer(state, 'CNOT', [0, 1])
Q
Quleaf 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    # -----------------tok---------

    # ------------------tik-------
    # state = GenerateRandomCirc(state, circ_num, n)
    # -----------------tok---------

    # ------------------tik-------
    re = measure_state(state, 2 ** 10)
    # -----------------tok---------

    print(re)


def Tester(bits_num=None, circ_num=None):
    """
    This part is to guarantee the behaviors of the simualtor2. Every Modification MUST ensure this function can be executed correctly.
    :return: True: Pass or False: NO Pass
    """
    # random tester

    check_value_rand = RandomTestIt(bits_num, circ_num)
    check_value_3 = Test3All()
    check_all = check_value_rand and check_value_3
    print(check_all)
    return check_all


if __name__ == '__main__':
Q
Quleaf 已提交
982 983 984 985 986 987 988 989
    paddle.set_device('cpu')
    # main(bits_num=5, circ_num=50)
    main(bits_num=5)
    # RandomTestIt(bits_num=5, circ_num=50)
    # print(Test3All())

    # print(Tester(bits_num=5, circ_num=50))
    # Tester(bits_num=6, circ_num=100)