Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def eng():
    return MainEngine(
        backend=Simulator(),
        engine_list=[
            AutoReplacer(rule_set),
            InstructionFilter(no_math_emulation)
        ],
    )
Ejemplo n.º 4
0
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)
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)
Ejemplo n.º 6
0
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)
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
Ejemplo n.º 8
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)
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
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)
def test_uniformly_controlled_ry(n, gate_classes):
    random_angles = [
        0.5, 0.8, 1.2, 2.5, 4.4, 2.32, 6.6, 15.12, 1, 2, 9.54, 2.1, 3.1415,
        1.1, 0.01, 0.99
    ]
    angles = random_angles[:2**n]
    for basis_state_index in range(0, 2**(n + 1)):
        basis_state = [0] * 2**(n + 1)
        basis_state[basis_state_index] = 1.
        correct_dummy_eng = DummyEngine(save_commands=True)
        correct_eng = MainEngine(backend=Simulator(),
                                 engine_list=[correct_dummy_eng])
        rule_set = DecompositionRuleSet(modules=[ucr2cnot])
        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(n)
        correct_eng.flush()
        test_qb = test_eng.allocate_qubit()
        test_ctrl_qureg = test_eng.allocate_qureg(n)
        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)

        gate_classes[1](angles) | (test_ctrl_qureg, test_qb)
        slow_implementation(angles=angles,
                            control_qubits=correct_ctrl_qureg,
                            target_qubit=correct_qb,
                            eng=correct_eng,
                            gate_class=gate_classes[0])
        test_eng.flush()
        correct_eng.flush()

        for fstate in range(2**(n + 1)):
            binary_state = format(fstate, '0' + str(n + 1) + 'b')
            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-10, abs=1e-10)

        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)
Ejemplo n.º 14
0
def test_qubitop2singlequbit():
    num_qubits = 4
    random_initial_state = [
        0.2 + 0.1 * x * cmath.exp(0.1j + 0.2j * x)
        for x in range(2**(num_qubits + 1))
    ]
    rule_set = DecompositionRuleSet(modules=[qubitop2onequbit])
    test_eng = MainEngine(
        backend=Simulator(),
        engine_list=[AutoReplacer(rule_set),
                     InstructionFilter(_decomp_gates)],
    )
    test_qureg = test_eng.allocate_qureg(num_qubits)
    test_ctrl_qb = test_eng.allocate_qubit()
    test_eng.flush()
    test_eng.backend.set_wavefunction(random_initial_state,
                                      test_qureg + test_ctrl_qb)
    correct_eng = MainEngine()
    correct_qureg = correct_eng.allocate_qureg(num_qubits)
    correct_ctrl_qb = correct_eng.allocate_qubit()
    correct_eng.flush()
    correct_eng.backend.set_wavefunction(random_initial_state,
                                         correct_qureg + correct_ctrl_qb)

    qubit_op_0 = QubitOperator("X0 Y1 Z3", -1.0j)
    qubit_op_1 = QubitOperator("Z0 Y1 X3", cmath.exp(0.6j))

    qubit_op_0 | test_qureg
    with Control(test_eng, test_ctrl_qb):
        qubit_op_1 | test_qureg
    test_eng.flush()

    correct_eng.backend.apply_qubit_operator(qubit_op_0, correct_qureg)
    with Control(correct_eng, correct_ctrl_qb):
        Ph(0.6) | correct_qureg[0]
        Z | correct_qureg[0]
        Y | correct_qureg[1]
        X | correct_qureg[3]
    correct_eng.flush()

    for fstate in range(2**(num_qubits + 1)):
        binary_state = format(fstate, '0' + str(num_qubits + 1) + 'b')
        test = test_eng.backend.get_amplitude(binary_state,
                                              test_qureg + test_ctrl_qb)
        correct = correct_eng.backend.get_amplitude(
            binary_state, correct_qureg + correct_ctrl_qb)
        assert correct == pytest.approx(test, rel=1e-10, abs=1e-10)

    All(Measure) | correct_qureg + correct_ctrl_qb
    All(Measure) | test_qureg + test_ctrl_qb
    correct_eng.flush()
    test_eng.flush()
Ejemplo n.º 15
0
def test_entangle():
    rule_set = DecompositionRuleSet(modules=[entangle])
    sim = Simulator()
    eng = MainEngine(sim,
                     [AutoReplacer(rule_set),
                      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)

    All(Measure) | qureg
Ejemplo n.º 16
0
def test_decomposition():
    """Test that this decomposition of H produces correct amplitudes

    Function tests each DecompositionRule in
    h2rx.all_defined_decomposition_rules
    """
    decomposition_rule_list = h2rx.all_defined_decomposition_rules
    for rule in decomposition_rule_list:
        for basis_state_index in range(2):
            basis_state = [0] * 2
            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(rules=[rule])
            test_dummy_eng = DummyEngine(save_commands=True)
            test_eng = MainEngine(
                backend=Simulator(),
                engine_list=[
                    AutoReplacer(rule_set),
                    InstructionFilter(h_decomp_gates),
                    test_dummy_eng,
                ],
            )

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

            correct_eng.backend.set_wavefunction(basis_state, correct_qb)
            test_eng.backend.set_wavefunction(basis_state, test_qb)

            H | correct_qb
            H | test_qb

            correct_eng.flush()
            test_eng.flush()

            assert H in (cmd.gate
                         for cmd in correct_dummy_eng.received_commands)
            assert H not in (cmd.gate
                             for cmd in test_dummy_eng.received_commands)

            assert correct_eng.backend.cheat()[1] == pytest.approx(
                test_eng.backend.cheat()[1], rel=1e-12, abs=1e-12)

            Measure | test_qb
            Measure | correct_qb
Ejemplo n.º 17
0
def test_decomposition():
    """ Test that this decomposition of CNOT produces correct amplitudes

        Function tests each DecompositionRule in
        cnot2rxx.all_defined_decomposition_rules
    """
    decomposition_rule_list = cnot2rxx.all_defined_decomposition_rules
    for rule in decomposition_rule_list:
        for basis_state_index in range(0, 4):
            basis_state = [0] * 4
            basis_state[basis_state_index] = 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(_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)
            CNOT | (test_ctrl_qb, test_qb)
            CNOT | (correct_ctrl_qb, correct_qb)

            test_eng.flush()
            correct_eng.flush()

            assert len(correct_dummy_eng.received_commands) == 5
            assert len(test_dummy_eng.received_commands) == 10

            assert correct_eng.backend.cheat()[1] == pytest.approx(
                test_eng.backend.cheat()[1], 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)
def test_decompose_commuting_terms():
    saving_backend = DummyEngine(save_commands=True)

    def my_filter(self, cmd):
        if len(cmd.qubits[0]) <= 2 or isinstance(cmd.gate,
                                                 ClassicalInstructionGate):
            return True
        return False

    rules = DecompositionRuleSet([te.rule_commuting_terms])
    replacer = AutoReplacer(rules)
    filter_eng = InstructionFilter(my_filter)
    eng = MainEngine(backend=saving_backend,
                     engine_list=[replacer, filter_eng])
    qureg = eng.allocate_qureg(5)
    with Control(eng, qureg[3]):
        op1 = QubitOperator("X1 Y2", 0.7)
        op2 = QubitOperator("Y2 X4", -0.8)
        op3 = QubitOperator((), 0.6)
        TimeEvolution(1.5, op1 + op2 + op3) | qureg

    cmd1 = saving_backend.received_commands[5]
    cmd2 = saving_backend.received_commands[6]
    cmd3 = saving_backend.received_commands[7]

    found = [False, False, False]
    scaled_op1 = QubitOperator("X0 Y1", 0.7)
    scaled_op2 = QubitOperator("Y0 X1", -0.8)
    for cmd in [cmd1, cmd2, cmd3]:
        if (cmd.gate == Ph(-1.5 * 0.6) and cmd.qubits[0][0].id == qureg[1].id
                and cmd.control_qubits[0].id
                == qureg[3].id  # 1st qubit of [1,2,4]
            ):
            found[0] = True
        elif (isinstance(cmd.gate, TimeEvolution)
              and cmd.gate.hamiltonian.isclose(scaled_op1)
              and cmd.gate.time == pytest.approx(1.5)
              and cmd.qubits[0][0].id == qureg[1].id
              and cmd.qubits[0][1].id == qureg[2].id
              and cmd.control_qubits[0].id == qureg[3].id):
            found[1] = True
        elif (isinstance(cmd.gate, TimeEvolution)
              and cmd.gate.hamiltonian.isclose(scaled_op2)
              and cmd.gate.time == pytest.approx(1.5)
              and cmd.qubits[0][0].id == qureg[2].id
              and cmd.qubits[0][1].id == qureg[4].id
              and cmd.control_qubits[0].id == qureg[3].id):
            found[2] = True
    assert all(found)
Ejemplo n.º 19
0
def test_comparator():
    sim = Simulator()
    eng = MainEngine(
        sim, [AutoReplacer(rule_set),
              InstructionFilter(no_math_emulation)])
    qureg_a = eng.allocate_qureg(3)
    qureg_b = eng.allocate_qureg(3)
    compare_qubit = eng.allocate_qubit()

    init(eng, qureg_a, 5)
    init(eng, qureg_b, 3)

    Comparator() | (qureg_a, qureg_b, compare_qubit)

    assert 1. == pytest.approx(eng.backend.get_probability([1], compare_qubit))
Ejemplo n.º 20
0
def test_cnot_decomposition():
    for basis_state_index in range(0, 4):
        basis_state = [0] * 4
        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=[cnot2cz])
        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)
        CNOT | (test_ctrl_qb, test_qb)
        CNOT | (correct_ctrl_qb, correct_qb)

        test_eng.flush()
        correct_eng.flush()

        assert len(correct_dummy_eng.received_commands) == 5
        assert len(test_dummy_eng.received_commands) == 7

        for fstate in range(4):
            binary_state = format(fstate, '02b')
            test = test_sim.get_amplitude(binary_state, test_qb + test_ctrl_qb)
            correct = correct_sim.get_amplitude(binary_state,
                                                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)
Ejemplo n.º 21
0
def test_basic_engine_is_available():
    eng = _basics.BasicEngine()
    with pytest.raises(_basics.LastEngineException):
        eng.is_last_engine = True
        eng.is_available("FakeCommand")

    def filter(self, cmd):
        if cmd == "supported":
            return True
        return False

    filter_eng = InstructionFilter(filter)
    eng.next_engine = filter_eng
    eng.is_last_engine = False
    assert eng.is_available("supported")
    assert not eng.is_available("something else")
Ejemplo n.º 22
0
def test_command_printer_is_available():
    inline_cmd_printer = _printer.CommandPrinter()
    cmd_printer = _printer.CommandPrinter()

    def available_cmd(self, cmd):
        return cmd.gate == H

    filter = InstructionFilter(available_cmd)
    eng = MainEngine(backend=cmd_printer, engine_list=[inline_cmd_printer, filter])
    qubit = eng.allocate_qubit()
    cmd0 = Command(eng, H, (qubit,))
    cmd1 = Command(eng, T, (qubit,))
    assert inline_cmd_printer.is_available(cmd0)
    assert not inline_cmd_printer.is_available(cmd1)
    assert cmd_printer.is_available(cmd0)
    assert cmd_printer.is_available(cmd1)
Ejemplo n.º 23
0
def test_globalphase():
	dummy = DummyEngine(save_commands=True)
	eng = MainEngine(dummy, [AutoReplacer(),
	                       InstructionFilter(low_level_gates_noglobalphase)])
	
	qubit = eng.allocate_qubit()
	R(1.2) | qubit
	
	rz_count = 0
	for cmd in dummy.received_commands:
		assert not isinstance(cmd.gate, R)
		if isinstance(cmd.gate, Rz):
			rz_count += 1
			assert cmd.gate == Rz(1.2)
	
	assert rz_count == 1
Ejemplo n.º 24
0
def test_gate_decompositions():
	sim = Simulator()
	eng = MainEngine(sim, [])
	
	qureg = run_circuit(eng)
	
	sim2 = Simulator()
	eng_lowlevel = MainEngine(sim2, [AutoReplacer(),
	                                InstructionFilter(low_level_gates)])
	qureg2 = run_circuit(eng_lowlevel)
	
	for i in range(len(sim.cheat()[1])):
		assert sim.cheat()[1][i] == pytest.approx(sim2.cheat()[1][i])
	
	Measure | qureg
	Measure | qureg2
Ejemplo n.º 25
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
Ejemplo n.º 26
0
def test_decomposition():
    a = Debugger()
    decomp = DecompositionRuleSet(
        modules=[projectq.setups.decompositions.parity_measurement])
    engine_list = [AutoReplacer(decomp), InstructionFilter(is_supported), a]
    eng = projectq.MainEngine(engine_list=engine_list,
                              backend=CommandPrinter(accept_input=False))
    q1 = eng.allocate_qubit()
    q2 = eng.allocate_qubit()

    ParityMeasurementGate("Z0 X1") | q1 + q2

    print(a.commands)
    #TODO
    #assert(a.commands[-1].gate._bases[0][0] == 0)
    #assert(a.commands[-1].gate._bases[0][1] == "Z")
    assert (False)
Ejemplo n.º 27
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)
    ]
Ejemplo n.º 28
0
def test_adder():
	sim = Simulator()
	eng = MainEngine(sim, [AutoReplacer(),
	                       InstructionFilter(no_math_emulation)])
	qureg = eng.allocate_qureg(4)
	init(eng, qureg, 4)
	
	AddConstant(3) | qureg
	
	assert 1. == pytest.approx(abs(sim.cheat()[1][7]))
	
	init(eng, qureg, 7)  # reset
	init(eng, qureg, 2)
	
	AddConstant(15) | qureg  # check for overflow -> should be 15+2 = 1 (mod 16)
	assert 1. == pytest.approx(abs(sim.cheat()[1][1]))
	
	Measure | qureg
Ejemplo n.º 29
0
def test_quantumsubtraction():
    sim = Simulator()
    eng = MainEngine(
        sim, [AutoReplacer(rule_set),
              InstructionFilter(no_math_emulation)])

    qureg_a = eng.allocate_qureg(5)
    qureg_b = eng.allocate_qureg(5)

    init(eng, qureg_a, 5)
    init(eng, qureg_b, 7)

    SubtractQuantum() | (qureg_a, qureg_b)

    assert 1. == pytest.approx(
        eng.backend.get_probability([1, 0, 1, 0, 0], qureg_a))
    assert 1. == pytest.approx(
        eng.backend.get_probability([0, 1, 0, 0, 0], qureg_b))
Ejemplo n.º 30
0
def test_gate_decompositions():
    sim = Simulator()
    eng = MainEngine(sim, [])
    rule_set = DecompositionRuleSet(
        modules=[r2rzandph, crz2cxandrz, toffoli2cnotandtgate, ph2r])

    qureg = run_circuit(eng)

    sim2 = Simulator()
    eng_lowlevel = MainEngine(sim2, [AutoReplacer(rule_set),
                                     InstructionFilter(low_level_gates)])
    qureg2 = run_circuit(eng_lowlevel)

    for i in range(len(sim.cheat()[1])):
        assert sim.cheat()[1][i] == pytest.approx(sim2.cheat()[1][i])

    All(Measure) | qureg
    All(Measure) | qureg2