Beispiel #1
0
def run():
    # build compilation engine list
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    compilerengines = [
        AutoReplacer(rule_set),
        InstructionFilter(high_level_gates),
        TagRemover(),
        LocalOptimizer(3),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3), resource_counter
    ]

    # make the compiler and run the circuit on the simulator backend
    #eng = MainEngine(Simulator(), compilerengines)
    eng = MainEngine(resource_counter)
    # print welcome message and ask the user for the number to factor
    print(
        "\n\t\033[37mprojectq\033[0m\n\t--------\n\tImplementation of Shor"
        "\'s algorithm.",
        end="")
    N = int(input('\n\tNumber to factor: '))
    print("\n\tFactoring N = {}: \033[0m".format(N), end="")

    # choose a base at random:
    a = N
    while not gcd(a, N) == 1:
        a = random.randint(2, N)

    print("\na is " + str(a))
    if not gcd(a, N) == 1:
        print("\n\n\t\033[92mOoops, we were lucky: Chose non relative prime"
              " by accident :)")
        print("\tFactor: {}\033[0m".format(gcd(a, N)))
    else:
        # run the quantum subroutine
        r = run_shor(eng, N, a, True)
        print("\n\nr found : " + str(r))
        # try to determine the factors

        if r % 2 != 0:
            r *= 2
        apowrhalf = pow(a, r >> 1, N)
        f1 = gcd(apowrhalf + 1, N)
        f2 = gcd(apowrhalf - 1, N)
        print("f1 = {}, f2 = {}".format(f1, f2))
        if ((not f1 * f2 == N) and f1 * f2 > 1
                and int(1. * N / (f1 * f2)) * f1 * f2 == N):
            f1, f2 = f1 * f2, int(N / (f1 * f2))
        if f1 * f2 == N and f1 > 1 and f2 > 1:
            print(
                "\n\n\t\033[92mFactors found :-) : {} * {} = {}\033[0m".format(
                    f1, f2, N))
        else:
            print("\n\n\t\033[91mBad luck: Found {} and {}\033[0m".format(
                f1, f2))

        return resource_counter  # print resource usage
def run_adder(a=11, b=1, param="simulation"):
    # build compilation engine list
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    compilerengines = [
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3), resource_counter
    ]
    # create a main compiler engine
    if param == "latex":
        drawing_engine = CircuitDrawer()
        eng2 = MainEngine(drawing_engine)
        [xa, xb] = initialisation(eng2, a, b)
        adder(eng2, xa, xb)
        measure(eng2, xa, xb)
        print(drawing_engine.get_latex())
    else:
        eng = MainEngine(Simulator(), compilerengines)
        [xa, xb] = initialisation(eng, a, b)
        adder(eng, xa, xb)
        print(measure(eng, xa, xb))
Beispiel #3
0
def run(x=4, N=7, param="run"):
    """

    :param a: a<N and must be invertible mod[N]
    :param N:
    :param x:
    :param param:
    :return: |1> --> |(a**x) mod N>
    """
    # build compilation engine list
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(modules=[projectq.libs.math,
                                             projectq.setups.decompositions])
    compilerengines = [AutoReplacer(rule_set),
                       TagRemover(),
                       LocalOptimizer(3),
                       AutoReplacer(rule_set),
                       TagRemover(),
                       LocalOptimizer(3),
                       resource_counter]

    # create a main compiler engine

    if param == "latex":
        drawing_engine = CircuitDrawer()
        eng = MainEngine(drawing_engine)
        arcsinQ(eng, x, N)
        return drawing_engine
    if param == "count":
        eng = MainEngine(resource_counter)
        arcsinQ(eng, x, N)
        return resource_counter
    else:
        eng = MainEngine(Simulator(), compilerengines)
        return arcsinQ(eng, x, N)
def run_inv(a=11, b=1, param="simulation"):
    # build compilation engine list
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(modules=[projectq.libs.math,
                                             projectq.setups.decompositions])
    compilerengines = [AutoReplacer(rule_set),
                       TagRemover(),
                       LocalOptimizer(3),
                       AutoReplacer(rule_set),
                       TagRemover(),
                       LocalOptimizer(3),
                       resource_counter]

    # create a main compiler engine
    a1 = a
    b1 = b
    if a == 0:
        a1 = 1
    if b == 0:
        b1 = 1
    n = max(int(math.log(a1, 2)), int(math.log(b1, 2))) + 1

    if param == "latex":
        drawing_engine = CircuitDrawer()
        eng2 = MainEngine(drawing_engine)
        xa = initialisation_n(eng2, a, n + 1)
        xb = initialisation_n(eng2, b, n + 1)
        # b --> phi(b)
        QFT | xb
        phi_adder(eng2, xa, xb)
        with Dagger(eng2):
            QFT | xb
        All(Measure) | xa
        All(Measure) | xb
        eng2.flush()
        print(drawing_engine.get_latex())
    else:
        eng = MainEngine(Simulator(), compilerengines)
        xa = initialisation_n(eng, a, n + 1)
        xb = initialisation_n(eng, b, n + 1)
        # b --> phi(b)
        QFT | xb
        with Dagger(eng):
            phi_adder(eng, xa, xb)
        with Dagger(eng):
            QFT | xb
        All(Measure) | xa
        All(Measure) | xb
        eng.flush()
        n = n+1
        measurements_a = [0] * n
        measurements_b = [0] * n
        for k in range(n):
            measurements_a[k] = int(xa[k])
            measurements_b[k] = int(xb[k])

        return [measurements_a, meas2int(measurements_b), measurements_b]
def get_main_engine(sim):
    engine_list = [AutoReplacer(rule_set),
                   InstructionFilter(high_level_gates),
                   TagRemover(),
                   LocalOptimizer(3),
                   AutoReplacer(rule_set),
                   TagRemover(),
                   LocalOptimizer(3)]
    return MainEngine(sim, engine_list)
Beispiel #6
0
def test_decomposition(angle):
    for basis_state in ([1, 0], [0, 1]):
        correct_dummy_eng = DummyEngine(save_commands=True)
        correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])

        rule_set = DecompositionRuleSet(modules=[rx2rz])
        test_dummy_eng = DummyEngine(save_commands=True)
        test_eng = MainEngine(
            backend=Simulator(),
            engine_list=[
                AutoReplacer(rule_set),
                InstructionFilter(rx_decomp_gates),
                test_dummy_eng,
            ],
        )

        correct_qb = correct_eng.allocate_qubit()
        Rx(angle) | correct_qb
        correct_eng.flush()

        test_qb = test_eng.allocate_qubit()
        Rx(angle) | test_qb
        test_eng.flush()

        assert correct_dummy_eng.received_commands[1].gate == Rx(angle)
        assert test_dummy_eng.received_commands[1].gate != Rx(angle)

        for fstate in ['0', '1']:
            test = test_eng.backend.get_amplitude(fstate, test_qb)
            correct = correct_eng.backend.get_amplitude(fstate, correct_qb)
            assert correct == pytest.approx(test, rel=1e-12, abs=1e-12)

        Measure | test_qb
        Measure | correct_qb
Beispiel #7
0
def test_Ph_eigenvectors():
    rule_set = DecompositionRuleSet(modules=[pe, dqft])
    eng = MainEngine(backend=Simulator(),
                     engine_list=[
                         AutoReplacer(rule_set),
                     ])
    results = np.array([])
    for i in range(100):
        autovector = eng.allocate_qureg(1)
        theta = cmath.pi * 2. * 0.125
        unit = Ph(theta)
        ancillas = eng.allocate_qureg(3)
        QPE(unit) | (ancillas, autovector)
        All(Measure) | ancillas
        fasebinlist = [int(q) for q in ancillas]
        fasebin = ''.join(str(j) for j in fasebinlist)
        faseint = int(fasebin, 2)
        phase = faseint / (2.**(len(ancillas)))
        results = np.append(results, phase)
        All(Measure) | autovector
        eng.flush()

    num_phase = (results == 0.125).sum()
    assert num_phase / 100. >= 0.35, "Statistics phase calculation are not correct (%f vs. %f)" % (
        num_phase / 100., 0.35)
Beispiel #8
0
def test_x_gate_invalid():
    sim = ClassicalSimulator()
    eng = MainEngine(sim, [AutoReplacer(DecompositionRuleSet())])
    a = eng.allocate_qureg(2)

    with pytest.raises(ValueError):
        X | a
def test_simple_test_X_eigenvectors():
    rule_set = DecompositionRuleSet(modules=[pe, dqft])
    eng = MainEngine(
        backend=Simulator(),
        engine_list=[
            AutoReplacer(rule_set),
        ],
    )
    N = 150
    results = np.array([])
    for i in range(N):
        autovector = eng.allocate_qureg(1)
        X | autovector
        H | autovector
        unit = X
        ancillas = eng.allocate_qureg(1)
        QPE(unit) | (ancillas, autovector)
        All(Measure) | ancillas
        fasebinlist = [int(q) for q in ancillas]
        fasebin = ''.join(str(j) for j in fasebinlist)
        faseint = int(fasebin, 2)
        phase = faseint / (2.0**(len(ancillas)))
        results = np.append(results, phase)
        All(Measure) | autovector
        eng.flush()

    num_phase = (results == 0.5).sum()
    assert num_phase / N >= 0.35, "Statistics phase calculation are not correct (%f vs. %f)" % (
        num_phase / N,
        0.35,
    )
Beispiel #10
0
def eng():
    return MainEngine(
        backend=Simulator(),
        engine_list=[
            AutoReplacer(rule_set),
            InstructionFilter(no_math_emulation)
        ],
    )
Beispiel #11
0
def ibm_default_engines():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [TagRemover(),
            LocalOptimizer(10),
            AutoReplacer(rule_set),
            TagRemover(),
            IBMCNOTMapper(),
            LocalOptimizer(10)]
Beispiel #12
0
def get_engine(api=None):
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    compilerengines = [
        AutoReplacer(rule_set),
        InstructionFilter(high_level_gates),
        TagRemover(),
        LocalOptimizer(3),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3), resource_counter
    ]

    # make the compiler and run the circuit on the simulator backend
    backend = Simulator()
    return MainEngine(backend, compilerengines), backend
Beispiel #13
0
def get_engine_list():
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(5),
        AutoReplacer(rule_set),
        InstructionFilter(high_level_gates),
        TagRemover(),
        LocalOptimizer(5),
        AutoReplacer(rule_set),
        TagRemover(),
        GridMapper(2, 8, grid_to_physical),
        LocalOptimizer(5),
        SwapAndCNOTFlipper(ibmqx5_connections),
        LocalOptimizer(5)
    ]
Beispiel #14
0
def default_engines():
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(),
        TagRemover(),
        LocalOptimizer(10)
    ]
Beispiel #15
0
def test_available_gates():
    sim = ClassicalSimulator()
    eng = MainEngine(sim, [AutoReplacer(DecompositionRuleSet())])
    a = eng.allocate_qubit()
    X | a
    NOT | a
    Measure | a
    eng.flush()
def test_decomposition():
    for basis_state_index in range(0, 16):
        basis_state = [0] * 16
        basis_state[basis_state_index] = 1.0
        correct_dummy_eng = DummyEngine(save_commands=True)
        correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])
        rule_set = DecompositionRuleSet(modules=[cnu2toffoliandcu])
        test_dummy_eng = DummyEngine(save_commands=True)
        test_eng = MainEngine(
            backend=Simulator(),
            engine_list=[
                AutoReplacer(rule_set),
                InstructionFilter(_decomp_gates),
                test_dummy_eng,
            ],
        )
        test_sim = test_eng.backend
        correct_sim = correct_eng.backend
        correct_qb = correct_eng.allocate_qubit()
        correct_ctrl_qureg = correct_eng.allocate_qureg(3)
        correct_eng.flush()
        test_qb = test_eng.allocate_qubit()
        test_ctrl_qureg = test_eng.allocate_qureg(3)
        test_eng.flush()

        correct_sim.set_wavefunction(basis_state, correct_qb + correct_ctrl_qureg)
        test_sim.set_wavefunction(basis_state, test_qb + test_ctrl_qureg)

        with Control(test_eng, test_ctrl_qureg[:2]):
            Rx(0.4) | test_qb
        with Control(test_eng, test_ctrl_qureg):
            Ry(0.6) | test_qb
        with Control(test_eng, test_ctrl_qureg):
            X | test_qb

        with Control(correct_eng, correct_ctrl_qureg[:2]):
            Rx(0.4) | correct_qb
        with Control(correct_eng, correct_ctrl_qureg):
            Ry(0.6) | correct_qb
        with Control(correct_eng, correct_ctrl_qureg):
            X | correct_qb

        test_eng.flush()
        correct_eng.flush()

        assert len(correct_dummy_eng.received_commands) == 9
        assert len(test_dummy_eng.received_commands) == 25

        for fstate in range(16):
            binary_state = format(fstate, '04b')
            test = test_sim.get_amplitude(binary_state, test_qb + test_ctrl_qureg)
            correct = correct_sim.get_amplitude(binary_state, correct_qb + correct_ctrl_qureg)
            assert correct == pytest.approx(test, rel=1e-12, abs=1e-12)

        All(Measure) | test_qb + test_ctrl_qureg
        All(Measure) | correct_qb + correct_ctrl_qureg
        test_eng.flush(deallocate_qubits=True)
        correct_eng.flush(deallocate_qubits=True)
Beispiel #17
0
def get_engine_list():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(10)
    ]
Beispiel #18
0
def ibm_default_engines():
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(),
        TagRemover(),
        IBMCNOTMapper(),
        LocalOptimizer(10)
    ]
def test_complex_aa():
    rule_set = DecompositionRuleSet(modules=[aa])

    eng = MainEngine(
        backend=Simulator(),
        engine_list=[
            AutoReplacer(rule_set),
        ],
    )

    system_qubits = eng.allocate_qureg(6)

    # Prepare the control qubit in the |-> state
    control = eng.allocate_qubit()
    X | control
    H | control

    # Creates the initial state form the Algorithm
    complex_algorithm(eng, system_qubits)

    # Get the probabilty of getting the marked state before the AA
    # to calculate the number of iterations
    eng.flush()
    prob000000 = eng.backend.get_probability('000000', system_qubits)
    prob111111 = eng.backend.get_probability('111111', system_qubits)

    total_amp_before = math.sqrt(prob000000 + prob111111)
    theta_before = math.asin(total_amp_before)

    # Apply Quantum Amplitude Amplification the correct number of times
    # Theta is calculated previously using get_probability
    # We calculate also the theoretical final probability
    # of getting the good state
    num_it = int(math.pi / (4.0 * theta_before) + 1)
    theoretical_prob = math.sin((2 * num_it + 1.0) * theta_before)**2
    with Loop(eng, num_it):
        QAA(complex_algorithm, complex_oracle) | (system_qubits, control)

    # Get the probabilty of getting the marked state after the AA
    # to compare with the theoretical probability after the AA
    eng.flush()
    prob000000 = eng.backend.get_probability('000000', system_qubits)
    prob111111 = eng.backend.get_probability('111111', system_qubits)
    total_prob_after = prob000000 + prob111111

    All(Measure) | system_qubits
    H | control
    Measure | control

    eng.flush()

    assert total_prob_after == pytest.approx(
        theoretical_prob, abs=1e-2
    ), "The obtained probability is less than expected %f vs. %f" % (
        total_prob_after,
        theoretical_prob,
    )
def test_wrong_number_of_angles():
    rule_set = DecompositionRuleSet(modules=[ucr2cnot])
    eng = MainEngine(
        backend=DummyEngine(),
        engine_list=[AutoReplacer(rule_set),
                     InstructionFilter(_decomp_gates)])
    qb = eng.allocate_qubit()
    with pytest.raises(ValueError):
        UniformlyControlledRy([0.1, 0.2]) | ([], qb)
def test_no_control_qubits():
    rule_set = DecompositionRuleSet(modules=[ucr2cnot])
    eng = MainEngine(
        backend=DummyEngine(),
        engine_list=[AutoReplacer(rule_set),
                     InstructionFilter(_decomp_gates)])
    qb = eng.allocate_qubit()
    with pytest.raises(TypeError):
        UniformlyControlledRy([0.1]) | qb
Beispiel #22
0
def run(args, param="simulation"):
    """
    Be careful the Measure command can take a lot of time to execute as you can create as much as qubit as you want
    :param args: list of int
    :param param: choose between simulation or latex
    :return:
    """
    # build compilation engine list
    resource_counter = ResourceCounter()
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    compilerengines = [
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(3), resource_counter
    ]

    # create a main compiler engine
    if param == "latex":
        drawing_engine = CircuitDrawer()
        eng2 = MainEngine(drawing_engine)
        Xreg = initialisation(eng2, args)
        m = len(Xreg)
        All(Measure) | Xreg
        eng2.flush()
        print(drawing_engine.get_latex())
    else:
        eng = MainEngine(Simulator(), compilerengines)
        Xreg = initialisation(eng, args)
        m = len(Xreg)
        n = Xreg[0].__len__()
        for i in range(m):
            All(Measure) | Xreg[i]
        eng.flush()
        measurement = []
        for i in range(m):
            measurement.append([0] * n)
            for k in range(n):
                measurement[i][k] = int(Xreg[i][k])

        return measurement
Beispiel #23
0
def test_chooser_Ry_reducer_synthetic():
    backend = DummyEngine(save_commands=True)
    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])

    engine_list = [
        AutoReplacer(rule_set, chooser_Ry_reducer),
        TagRemover(),
        InstructionFilter(filter_gates),
    ]

    eng = MainEngine(backend=backend, engine_list=engine_list)
    control = eng.allocate_qubit()
    target = eng.allocate_qubit()
    CNOT | (control, target)
    CNOT | (control, target)
    eng.flush()
    idx0 = len(backend.received_commands) - 2
    idx1 = len(backend.received_commands)
    CNOT | (control, target)
    eng.flush()

    assert isinstance(backend.received_commands[idx0].gate, Ry)
    assert isinstance(backend.received_commands[idx1].gate, Ry)
    assert (backend.received_commands[idx0].gate.get_inverse() ==
            backend.received_commands[idx1].gate)

    eng = MainEngine(backend=backend, engine_list=engine_list)
    control = eng.allocate_qubit()
    target = eng.allocate_qubit()
    H | target
    eng.flush()
    idx0 = len(backend.received_commands) - 2
    idx1 = len(backend.received_commands)
    H | target
    eng.flush()

    assert isinstance(backend.received_commands[idx0].gate, Ry)
    assert isinstance(backend.received_commands[idx1].gate, Ry)
    assert (backend.received_commands[idx0].gate.get_inverse() ==
            backend.received_commands[idx1].gate)

    eng = MainEngine(backend=backend, engine_list=engine_list)
    control = eng.allocate_qubit()
    target = eng.allocate_qubit()
    Rz(1.23456) | target
    eng.flush()
    idx0 = len(backend.received_commands) - 2
    idx1 = len(backend.received_commands)
    Rz(1.23456) | target
    eng.flush()

    assert isinstance(backend.received_commands[idx0].gate, Ry)
    assert isinstance(backend.received_commands[idx1].gate, Ry)
    assert (backend.received_commands[idx0].gate.get_inverse() ==
            backend.received_commands[idx1].gate)
Beispiel #24
0
def test_ibm_backend_functional_test(monkeypatch):
    correct_info = ('{"name": "ProjectQ Experiment", "qasm": "\\ninclude \\"'
                    'qelib1.inc\\";\\nqreg q[5];\\ncreg c[5];\\nh q[0];\\ncx'
                    ' q[0], q[2];\\ncx q[0], q[1];\\ntdg q[0];\\nsdg q[0];\\'
                    'nmeasure q[0] -> c[0];\\nmeasure q[2] -> c[2];\\nmeasure'
                    ' q[1] -> c[1];", "codeType": "QASM2"}')

    # patch send
    def mock_send(*args, **kwargs):
        assert json.loads(args[0]) == json.loads(correct_info)
        return {'date': '2017-01-19T14:28:47.622Z',
                'data': {'time': 14.429004907608032, 'serialNumberDevice':
                         'Real5Qv1', 'p': {'labels': ['00000', '00001',
                                                      '00010', '00011',
                                                      '00100', '00101',
                                                      '00110', '00111'],
                                           'values': [0.4521484375,
                                                      0.0419921875,
                                                      0.0185546875,
                                                      0.0146484375,
                                                      0.005859375,
                                                      0.0263671875,
                                                      0.0537109375,
                                                      0.38671875],
                                           'qubits': [0, 1, 2]},
                         'qasm': ('...')}}
    monkeypatch.setattr(_ibm, "send", mock_send)

    backend = _ibm.IBMBackend(verbose=True)
    # no circuit has been executed -> raises exception
    with pytest.raises(RuntimeError):
        backend.get_probabilities([])
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    engine_list = [TagRemover(),
                   LocalOptimizer(10),
                   AutoReplacer(rule_set),
                   TagRemover(),
                   IBMCNOTMapper(),
                   LocalOptimizer(10)]
    eng = MainEngine(backend=backend, engine_list=engine_list)
    unused_qubit = eng.allocate_qubit()
    qureg = eng.allocate_qureg(3)
    # entangle the qureg
    Entangle | qureg
    Tdag | qureg[0]
    Sdag | qureg[0]
    # measure; should be all-0 or all-1
    Measure | qureg
    # run the circuit
    eng.flush()
    prob_dict = eng.backend.get_probabilities([qureg[0], qureg[2], qureg[1]])
    assert prob_dict['111'] == pytest.approx(0.38671875)
    assert prob_dict['101'] == pytest.approx(0.0263671875)

    with pytest.raises(RuntimeError):
        eng.backend.get_probabilities(eng.allocate_qubit())
Beispiel #25
0
def test_entangle():
	sim = Simulator()
	eng = MainEngine(sim, [AutoReplacer(), InstructionFilter(low_level_gates)])
	qureg = eng.allocate_qureg(4)
	Entangle | qureg
	
	assert .5 == pytest.approx(abs(sim.cheat()[1][0])**2)
	assert .5 == pytest.approx(abs(sim.cheat()[1][-1])**2)
	
	Measure | qureg
Beispiel #26
0
def test_decomposition_errors(gate_matrix):
    test_gate = BasicGate()
    test_gate.matrix = np.matrix(gate_matrix)
    rule_set = DecompositionRuleSet(modules=[arb1q])
    eng = MainEngine(backend=DummyEngine(),
                     engine_list=[AutoReplacer(rule_set),
                                  InstructionFilter(z_y_decomp_gates)])
    qb = eng.allocate_qubit()
    with pytest.raises(Exception):
        test_gate | qb
Beispiel #27
0
def get_engine_list():
    """Return the default list of compiler engine."""
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(10)
    ]
Beispiel #28
0
def test_decomposition(angle):
    """
    Test that this decomposition of Rz produces correct amplitudes

    Note that this function tests each DecompositionRule in
    rz2rx.all_defined_decomposition_rules
    """
    decomposition_rule_list = rz2rx.all_defined_decomposition_rules
    for rule in decomposition_rule_list:
        for basis_state in ([1, 0], [0, 1]):
            correct_dummy_eng = DummyEngine(save_commands=True)
            correct_eng = MainEngine(backend=Simulator(),
                                     engine_list=[correct_dummy_eng])

            rule_set = DecompositionRuleSet(rules=[rule])
            test_dummy_eng = DummyEngine(save_commands=True)
            test_eng = MainEngine(backend=Simulator(),
                                  engine_list=[
                                      AutoReplacer(rule_set),
                                      InstructionFilter(rz_decomp_gates),
                                      test_dummy_eng
                                  ])

            correct_qb = correct_eng.allocate_qubit()
            Rz(angle) | correct_qb
            correct_eng.flush()

            test_qb = test_eng.allocate_qubit()
            Rz(angle) | test_qb
            test_eng.flush()

            # Create empty vectors for the wave vectors for the correct and
            # test qubits
            correct_vector = np.zeros((2, 1), dtype=np.complex_)
            test_vector = np.zeros((2, 1), dtype=np.complex_)

            i = 0
            for fstate in ['0', '1']:
                test = test_eng.backend.get_amplitude(fstate, test_qb)
                correct = correct_eng.backend.get_amplitude(fstate, correct_qb)
                correct_vector[i] = correct
                test_vector[i] = test
                i += 1

            # Necessary to transpose vector to use matrix dot product
            test_vector = test_vector.transpose()
            # Remember that transposed vector should come first in product
            vector_dot_product = np.dot(test_vector, correct_vector)

            assert np.absolute(vector_dot_product) == pytest.approx(1,
                                                                    rel=1e-12,
                                                                    abs=1e-12)

            Measure | test_qb
            Measure | correct_qb
Beispiel #29
0
def test_decomposition(gate_matrix):
    # Create single qubit gate with gate_matrix
    test_gate = MatrixGate()
    test_gate.matrix = np.matrix(gate_matrix)

    for basis_state in ([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,
                                                                   1]):
        correct_dummy_eng = DummyEngine(save_commands=True)
        correct_eng = MainEngine(backend=Simulator(),
                                 engine_list=[correct_dummy_eng])

        rule_set = DecompositionRuleSet(modules=[carb1q])
        test_dummy_eng = DummyEngine(save_commands=True)
        test_eng = MainEngine(
            backend=Simulator(),
            engine_list=[
                AutoReplacer(rule_set),
                InstructionFilter(_decomp_gates),
                test_dummy_eng,
            ],
        )
        test_sim = test_eng.backend
        correct_sim = correct_eng.backend

        correct_qb = correct_eng.allocate_qubit()
        correct_ctrl_qb = correct_eng.allocate_qubit()
        correct_eng.flush()
        test_qb = test_eng.allocate_qubit()
        test_ctrl_qb = test_eng.allocate_qubit()
        test_eng.flush()

        correct_sim.set_wavefunction(basis_state, correct_qb + correct_ctrl_qb)
        test_sim.set_wavefunction(basis_state, test_qb + test_ctrl_qb)

        with Control(test_eng, test_ctrl_qb):
            test_gate | test_qb
        with Control(correct_eng, correct_ctrl_qb):
            test_gate | correct_qb

        test_eng.flush()
        correct_eng.flush()

        assert correct_dummy_eng.received_commands[3].gate == test_gate
        assert test_dummy_eng.received_commands[3].gate != test_gate

        for fstate in ['00', '01', '10', '11']:
            test = test_sim.get_amplitude(fstate, test_qb + test_ctrl_qb)
            correct = correct_sim.get_amplitude(fstate,
                                                correct_qb + correct_ctrl_qb)
            assert correct == pytest.approx(test, rel=1e-12, abs=1e-12)

        All(Measure) | test_qb + test_ctrl_qb
        All(Measure) | correct_qb + correct_ctrl_qb
        test_eng.flush(deallocate_qubits=True)
        correct_eng.flush(deallocate_qubits=True)
Beispiel #30
0
def get_engine_list():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(rule_set),
        TagRemover(),
        IBM5QubitMapper(),
        SwapAndCNOTFlipper(ibmqx4_connections),
        LocalOptimizer(10)
    ]