Esempio n. 1
0
def test_sympy_cx_cz():
    assert Circuit().cx[1, 2].run(
        backend="sympy_unitary") == Circuit().h[2].cz[2, 1].h[2].run(
            backend="sympy_unitary")
    assert Circuit().cx[2, 1].run(
        backend="sympy_unitary") == Circuit().h[1].cz[2, 1].h[1].run(
            backend="sympy_unitary")
Esempio n. 2
0
def test_u2():
    phi, lambd = symbols("phi lambd")

    actual_1 = Circuit().u2(phi, lambd)[0].run(backend="sympy_unitary")
    expected_1 = Circuit().rz(lambd)[0].ry(
        pi / 2)[0].rz(phi)[0].run_with_sympy_unitary()
    assert simplify(actual_1 - expected_1) == zeros(2)
Esempio n. 3
0
def qft_with_3qbit_110():
    # |j0j1j2> = |000>
    c = Circuit(3)

    # |j0j1j2> = |110>
    c = c.x[0, 1]

    # j0ビットにアダマールゲートをかける。
    c = c.h[0]

    # j1ビットを制御ビットにしてj0ビットにR1をかける。
    c = c.cphase(math.pi / 2)[1, 0]

    # j2ビットを制御ビットにしてj0ビットにR2をかける。
    c = c.cphase(math.pi / 4)[2, 0]

    # j2ビットを制御ビットにしてj1ビットにR1をかける。
    c.h[1].cphase(math.pi / 2)[2, 1]

    # j2ビットにアダマールゲートをかける。
    c.h[2]

    r = c.run()
    r = list(2 * math.sqrt(2) * r)
    print("> 3qbit")
    for i, v in enumerate(r):
        b = "{:03b}".format(i)
        print("[{}]{}".format(b, v))
Esempio n. 4
0
def mcx_with_ancilla(c: Circuit, ctrl: Sequence[int], target: int,
                     ancilla: int) -> Circuit:
    """A macro of multi controlled X gate with ancilla.

    Refer https://arxiv.org/pdf/quant-ph/9503016.pdf Lem. 7.3, Cor. 7.4."""
    n_ctrl = len(ctrl)
    if n_ctrl == 0:
        return c.x[target]
    if n_ctrl == 1:
        return c.cx[ctrl[0], target]
    if n_ctrl == 2:
        return c.ccx[ctrl[0], ctrl[1], target]
    if n_ctrl == 3:
        return c.c3x(ctrl[0], ctrl[1], ctrl[2], target)
    if n_ctrl == 4:
        return c.c4x(ctrl[0], ctrl[1], ctrl[2], ctrl[3], target)
    sep = (n_ctrl + 1) // 2 + 1
    c1 = ctrl[:sep]
    a1 = ctrl[-1]
    c2 = list(ctrl[sep:]) + [ancilla]
    a2 = ctrl[sep - 1]
    c.mcx_with_ancilla(c1, ancilla, a1)
    c.mcx_with_ancilla(c2, target, a2)
    c.mcx_with_ancilla(c1, ancilla, a1)
    c.mcx_with_ancilla(c2, target, a2)
    return c
Esempio n. 5
0
def test_sympy_backend_for_one_qubit_gate():
    E = eye(2)
    X = Matrix([[0, 1], [1, 0]])
    Y = Matrix([[0, -I], [I, 0]])
    Z = Matrix([[1, 0], [0, -1]])
    H = Matrix([[1, 1], [1, -1]]) / sqrt(2)
    T = Matrix([[1, 0], [0, exp(I*pi/4)]])
    S = Matrix([[1, 0], [0, exp(I*pi/2)]])

    x, y, z = symbols('x, y, z')
    RX = Matrix([[cos(x / 2), -I * sin(x / 2)], [-I * sin(x / 2), cos(x / 2)]])
    RY = Matrix([[cos(y / 2), -sin(y / 2)], [sin(y / 2), cos(y / 2)]])
    RZ = Matrix([[cos(z / 2) - I * sin(z / 2), 0], [0, cos(z / 2) + I * sin(z / 2)]])

    actual_1 = Circuit().x[0, 1].y[1].z[2].run(backend="sympy_unitary")
    expected_1 = reduce(TensorProduct, [Z, Y * X, X])
    assert actual_1 == expected_1

    actual_2 = Circuit().y[0].z[3].run(backend="sympy_unitary")
    expected_2 = reduce(TensorProduct, [Z, E, E, Y])
    assert actual_2 == expected_2

    actual_3 = Circuit().x[0].z[3].h[:].t[1].s[2].run(backend="sympy_unitary")
    expected_3 = reduce(TensorProduct, [H * Z, S * H, T * H, H * X])
    assert actual_3 == expected_3

    actual_4 = Circuit().rx(-np.pi / 2)[0].rz(np.pi / 2)[1].ry(np.pi)[2].run(backend="sympy_unitary")
    expected_4 = reduce(TensorProduct, [RY, RZ, RX]).subs([[x, -pi / 2], [y, pi], [z, pi / 2]])
    assert actual_4 == expected_4
Esempio n. 6
0
def test_rz1(backend):
    assert np.allclose(
        ignore_global_phase(Circuit().h[0].rz(
            math.pi)[0].run(backend=backend)),
        Circuit().x[0].h[0].run(backend=backend))
    assert np.allclose(Circuit().h[0].r(math.pi)[0].run(backend=backend),
                       Circuit().x[0].h[0].run(backend=backend))
Esempio n. 7
0
def test_crotation(backend):
    assert np.allclose(
        Circuit().cu3(1.23, 4.56, -5.43)[3, 1].run(backend=backend),
        Circuit().crz(-5.43)[3,
                             1].cry(1.23)[3,
                                          1].crz(4.56)[3,
                                                       1].run(backend=backend))
Esempio n. 8
0
def test_sympy_backend_for_one_qubit_gate():
    E = eye(2)
    X = gate.X(0).get_target_matrix()
    Y = gate.Y(0).get_target_matrix()
    Z = gate.Z(0).get_target_matrix()
    H = gate.H(0).get_target_matrix()
    T = gate.T(0).get_target_matrix()
    S = gate.S(0).get_target_matrix()

    x, y, z = symbols('x, y, z')
    RX = Matrix([[cos(x / 2), -I * sin(x / 2)], [-I * sin(x / 2), cos(x / 2)]])
    RY = Matrix([[cos(y / 2), -sin(y / 2)], [sin(y / 2), cos(y / 2)]])
    RZ = Matrix([[exp(-I * z / 2), 0], [0, exp(I * z / 2)]])

    actual_1 = Circuit().x[0, 1].y[1].z[2].run(backend="sympy_unitary")
    expected_1 = reduce(TensorProduct, [Z, Y * X, X])
    assert actual_1 == expected_1

    actual_2 = Circuit().y[0].z[3].run(backend="sympy_unitary")
    expected_2 = reduce(TensorProduct, [Z, E, E, Y])
    assert actual_2 == expected_2

    actual_3 = Circuit().x[0].z[3].h[:].t[1].s[2].run(backend="sympy_unitary")
    expected_3 = reduce(TensorProduct, [H * Z, S * H, T * H, H * X])
    assert actual_3 == expected_3

    actual_4 = Circuit().rx(-pi / 2)[0].rz(
        pi / 2)[1].ry(pi)[2].run(backend="sympy_unitary")
    expected_4 = reduce(TensorProduct, [RY, RZ, RX]).subs([[x,
                                                            -pi / 2], [y, pi],
                                                           [z, pi / 2]])
    assert actual_4 == expected_4
Esempio n. 9
0
def test_crotation(backend):
    assert is_vec_same(
        Circuit().cu3(1.23, 4.56, -5.43)[3, 1].run(backend=backend),
        Circuit().crz(-5.43)[3,
                             1].cry(1.23)[3,
                                          1].crz(4.56)[3,
                                                       1].run(backend=backend))
Esempio n. 10
0
def test_measurement_entangled_state():
    # 1/sqrt(2) (|0> + |1>)
    c = Circuit().h[0].cx[0, 1]
    for _ in range(10000):
        cnt = c.run(shots=1)
        result = cnt.most_common()
        assert result == [("00", 1)] or result == [("11", 1)]
Esempio n. 11
0
def test_u3():
    theta, phi, lambd = symbols("theta phi lambd")

    actual_1 = Circuit().u3(theta, phi, lambd)[0].run(backend="sympy_unitary")
    assert actual_1[0, 0] != 0
    expected_1 = Circuit().rz(lambd)[0].ry(theta)[0].rz(phi)[0].run_with_sympy_unitary()
    assert expected_1[0, 0] != 0
    assert simplify(actual_1 - expected_1) == zeros(2)
Esempio n. 12
0
def test_macro():
    def macro(c, i):
        return c.h[i]
    BlueqatGlobalSetting.register_macro('foo', macro)
    try:
        assert is_vec_same(Circuit().foo(1).run(), Circuit().h[1].run())
    finally:
        BlueqatGlobalSetting.unregister_macro('foo')
Esempio n. 13
0
def test_copy_empty(backend):
    c = Circuit()
    c.run(backend=backend)
    cc = c.copy(copy_backends=True)
    assert c.ops == cc.ops and c.ops is not cc.ops
    if backend in ['numpy', 'numba']:
        assert c._backends[backend].cache is None and cc._backends[backend].cache is None
        assert c._backends[backend].cache_idx == cc._backends[backend].cache_idx == -1
Esempio n. 14
0
def test_u():
    theta, phi, lambd = symbols("theta phi lambd")

    actual_1 = simplify(Circuit().u(theta, phi, lambd, -(phi + lambd) / 2)[0].run(backend="sympy_unitary"))
    assert actual_1[0, 0] != 0
    expected_1 = simplify(Circuit().rz(lambd)[0].ry(theta)[0].rz(phi)[0].run_with_sympy_unitary())
    assert expected_1[0, 0] != 0
    assert simplify(nfloat(actual_1)) == simplify(nfloat(expected_1))
Esempio n. 15
0
def test_mat1_2(backend):
    if backend == 'qgate':
        pytest.xfail('mat1 gate for qgate is unimplemented.')
    t = random.random() * math.pi
    a = np.array([[math.cos(t), -math.sin(t)], [math.sin(t), math.cos(t)]])
    v1 = Circuit().mat1(a)[1:3].run(backend=backend)
    v2 = Circuit().ry(t * 2)[1:3].run(backend=backend)
    assert np.allclose(v1, v2)
Esempio n. 16
0
def test_macro9():
    with pytest.raises(ValueError):

        @circuitmacro(allow_overwrite=False)
        def xh(c):
            return c

    assert np.allclose(Circuit().x[0].h[1].run(), Circuit().xh().run())
Esempio n. 17
0
def test_measurement_after_qubits1():
    for _ in range(50):
        c = Circuit().h[0].m[0]
        a, cnt = c.run(shots=1, returns="statevector_and_shots")
        if cnt.most_common(1)[0] == ('0', 1):
            assert is_vec_same(a, np.array([1, 0]))
        else:
            assert is_vec_same(a, np.array([0, 1]))
Esempio n. 18
0
def test_globalphase_u_with_gamma(backend):
    theta = 1.2
    phi = 1.6
    lambd = 2.3
    gamma = -1.4
    c = Circuit().u(theta, phi, lambd, gamma)[0]
    assert abs(
        c.run(backend=backend)[0] -
        cmath.exp(1j * gamma) * math.cos(theta / 2)) < 1e-8
Esempio n. 19
0
def test_toffoli_gate(bits, backend):
    c = Circuit()
    if bits[0]:
        c.x[0]
    if bits[1]:
        c.x[1]
    c.ccx[0, 1, 2].m[2]
    expected_meas = "001" if bits[0] and bits[1] else "000"
    assert c.run(backend=backend, shots=1) == Counter([expected_meas])
Esempio n. 20
0
def test_json_dump_load():
    """A Circuit and deserialize(serialize())ed circuit returns same result.
    (However, it doesn't means they're same Circuit.)"""
    c = Circuit().h[:3].x[4].u(1.2, 3.4, 2.3, 1.0)[0].h[:].u(1.2, 3.4, 2.3)[1]
    d = serialize(c)
    j = json.dumps(d)
    d2 = json.loads(j)
    c2 = deserialize(d2)
    np.allclose(c.run(), c2.run())
Esempio n. 21
0
def test_concat_circuit1(backend):
    c1 = Circuit()
    c1.h[0]
    c1.run()
    c2 = Circuit()
    c2.h[1]
    c2.run()
    c1 += c2
    assert is_vec_same(c1.run(backend=backend), Circuit().h[0].h[1].run(backend=backend))
Esempio n. 22
0
def test_concat_circuit2():
    c1 = Circuit()
    c1.h[1]
    c1.run()
    c2 = Circuit()
    c2.h[0]
    c2.run()
    c1 += c2
    assert is_vec_same(c1.run(), Circuit().h[1].h[0].run())
Esempio n. 23
0
def test_macro10():
    @circuitmacro
    def xh(c):
        return Circuit().x[1].h[0]

    assert np.allclose(Circuit().x[1].h[0].run(), Circuit().xh().run())

    @circuitmacro
    def xh(c):
        return Circuit().x[0].h[1]
Esempio n. 24
0
def test_concat_circuit2(backend):
    c1 = Circuit()
    c1.h[1]
    c1.run()
    c2 = Circuit()
    c2.h[0]
    c2.run()
    c1 += c2
    assert np.allclose(c1.run(backend=backend),
                       Circuit().h[1].h[0].run(backend=backend))
Esempio n. 25
0
def test_measurement_hadamard1(backend):
    n = 1000
    c = Circuit().h[0].m[0]
    cnt = c.run(backend=backend, shots=n)
    a, b = cnt.most_common(2)
    assert a[1] + b[1] == n
    # variance of binomial distribution (n -> ∞) is np(1-p)
    # therefore, 3σ = 3 * sqrt(np(1-p))
    three_sigma = 3 * np.sqrt(n * 0.5 * 0.5)
    assert abs(a[1] - n / 2) < three_sigma
def test_copy_empty_numba():
    c = Circuit()
    c.run(backend='numba')
    # copy_history: deprecated.
    cc = c.copy(copy_backends=True)
    assert c.ops == cc.ops and c.ops is not cc.ops
    assert c._backends['numba'].cache is None and cc._backends[
        'numba'].cache is None
    assert c._backends['numba'].cache_idx == cc._backends[
        'numba'].cache_idx == -1
Esempio n. 27
0
def test_mcry_gray_n(theta, n):
    u = circuit_to_unitary(Circuit().ry(theta)[0])
    expected = np.eye(2**(n + 1), dtype=complex)
    expected[2**n - 1, 2**n - 1] = u[0, 0]
    expected[2**(n + 1) - 1, 2**n - 1] = u[1, 0]
    expected[2**n - 1, 2**(n + 1) - 1] = u[0, 1]
    expected[2**(n + 1) - 1, 2**(n + 1) - 1] = u[1, 1]
    assert np.allclose(
        circuit_to_unitary(Circuit().mcry_gray(theta, list(range(n)), n)),
        expected)
Esempio n. 28
0
def margolus(c: Circuit, c0: int, c1: int) -> Circuit:
    """Simplified Toffoli gate implementation by Margolus.

    This gate is also as know as relative Toffoli gate.
    It's almost as same as Toffoli gate, but only relative phases are different.
    Refer https://arxiv.org/abs/quant-ph/0312225v1 for details.
    (Remarks: It's also described in Nielsen & Chuang, Exercise 4.26.)"""
    c.ry(math.pi * 0.25)[t].cx[c1, t].ry(math.pi * 0.25)[t].cx[c0, t]
    c.ry(math.pi * -0.25)[t].cx[c1, t].ry(math.pi * -0.25)[t]
    return c
Esempio n. 29
0
def test_initial_vec3(backend):
    if backend == 'qgate':
        import qgate
        try:
            qgate.__version__
        except AttributeError:
            pytest.xfail("This version of qgate doesn't support initial vec.")

    v = Circuit(4).h[3].run(backend=backend)
    v2 = Circuit(4).run(backend=backend, initial=v)
    assert np.allclose(v, v2)
Esempio n. 30
0
def test_initial_vec2(backend):
    if backend == 'qgate':
        import qgate
        try:
            qgate.__version__
        except AttributeError:
            pytest.xfail("This version of qgate doesn't support initial vec.")

    v = Circuit().x[1].run(backend=backend)
    cnt = Circuit().x[0].m[0, 1].run(backend=backend, initial=v, shots=100)
    assert cnt == Counter({'11': 100})