Пример #1
0
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))
Пример #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
Пример #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)
Пример #4
0
def ibm_default_engines():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [TagRemover(),
            LocalOptimizer(10),
            AutoReplacer(rule_set),
            TagRemover(),
            IBMCNOTMapper(),
            LocalOptimizer(10)]
Пример #5
0
def default_engines():
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(),
        TagRemover(),
        LocalOptimizer(10)
    ]
Пример #6
0
def get_engine_list():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(10)
    ]
Пример #7
0
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]
Пример #8
0
def ibm_default_engines():
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(),
        TagRemover(),
        IBMCNOTMapper(),
        LocalOptimizer(10)
    ]
Пример #9
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)
Пример #10
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())
Пример #11
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)
    ]
Пример #12
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)
    ]
Пример #13
0
def test_ibm_backend_functional_test(monkeypatch):
    correct_info = ('{"qasms": [{"qasm": "\\ninclude \\"qelib1.inc\\";'
                    '\\nqreg q[3];\\ncreg c[3];\\nh q[2];\\ncx q[2], q[0];'
                    '\\ncx q[2], q[1];\\ntdg q[2];\\nsdg q[2];'
                    '\\nbarrier q[2], q[0], q[1];'
                    '\\nu3(0.2, -pi/2, pi/2) q[2];\\nmeasure q[2] -> '
                    'c[2];\\nmeasure q[0] -> c[0];\\nmeasure q[1] -> c[1];"}]'
                    ', "shots": 1024, "maxCredits": 5, "backend": {"name": '
                    '"simulator"}}')

    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, 'counts': {'00111': 396,
                                                                '00101': 27,
                                                                '00000': 601},
                         '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(),
                   IBM5QubitMapper(),
                   SwapAndCNOTFlipper(ibmqx4_connections),
                   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]
    Barrier | qureg
    Rx(0.2) | qureg[0]
    del unused_qubit
    # measure; should be all-0 or all-1
    All(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())
Пример #14
0
def _eng_emulation():
    # Only decomposing native ProjectQ gates
    # -> using emulation for gates in projectq.libs.math
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    eng = MainEngine(
        engine_list=[
            TagRemover(),
            AutoReplacer(rule_set),
            TagRemover(),
            CommandPrinter(),
        ],
        verbose=True,
    )
    return eng
Пример #15
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
Пример #16
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)
    ]
Пример #17
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
Пример #18
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)
Пример #19
0
def get_quantum_engine():
    # Create a main compiler engine with a simulator backend:
    backend = projectq_simulator(gate_fusion=True)
    cache_depth = 10
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    engines = [TagRemover(),
               LocalOptimizer(cache_depth),
               AutoReplacer(rule_set)]
    compiler_engine = MainEngine(backend=backend, engine_list=engines)

    return compiler_engine
Пример #20
0
def get_hiq_quantum_engine():
    from hiq.projectq.backends import SimulatorMPI
    backend = SimulatorMPI(gate_fusion=True)
    cache_depth = 10
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    engines = [TagRemover(),
               LocalOptimizer(cache_depth),
               AutoReplacer(rule_set)]
    compiler_engine = MainEngine(backend=backend, engine_list=engines)
    return compiler_engine
    return
Пример #21
0
def _eng_decomp():
    def no_math_emulation(eng, cmd):
        if isinstance(cmd.gate, BasicMathGate):
            return False
        if isinstance(cmd.gate, ClassicalInstructionGate):
            return True
        try:
            return len(cmd.gate.matrix) > 0
        except AttributeError:
            return False

    rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions.qft2crandhadamard])
    eng = MainEngine(
        engine_list=[
            TagRemover(),
            AutoReplacer(rule_set),
            InstructionFilter(no_math_emulation),
            TagRemover(),
            CommandPrinter(),
        ]
    )
    return eng
Пример #22
0
def test_ibm_retrieve(monkeypatch):
    # patch send
    def mock_retrieve(*args, **kwargs):
        return {'date': '2017-01-19T14:28:47.622Z',
                'data': {'time': 14.429004907608032, 'counts': {'00111': 396,
                                                                '00101': 27,
                                                                '00000': 601},
                         'qasm': ('...')}}
    monkeypatch.setattr(_ibm, "retrieve", mock_retrieve)
    backend = _ibm.IBMBackend(retrieve_execution="ab1s2")
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    connectivity = set([(1, 2), (2, 4), (0, 2), (3, 2), (4, 3), (0, 1)])
    engine_list = [TagRemover(),
                   LocalOptimizer(10),
                   AutoReplacer(rule_set),
                   TagRemover(),
                   IBM5QubitMapper(),
                   SwapAndCNOTFlipper(connectivity),
                   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]
    Barrier | qureg
    Rx(0.2) | qureg[0]
    del unused_qubit
    # measure; should be all-0 or all-1
    All(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)
Пример #23
0
def test_chooser_Ry_reducer_unsupported_gate():
    backend = DummyEngine(save_commands=True)
    rule_set = DecompositionRuleSet(
        rules=[DecompositionRule(H.__class__, _dummy_h2nothing_A)])

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

    eng = MainEngine(backend=backend, engine_list=engine_list)
    qubit = eng.allocate_qubit()
    H | qubit
    eng.flush()

    for cmd in backend.received_commands:
        print(cmd)

    assert isinstance(backend.received_commands[1].gate, Ry)
Пример #24
0
def get_engine_list(one_qubit_gates="any",
                    two_qubit_gates=(CNOT, ),
                    other_gates=(),
                    compiler_chooser=default_chooser):
    """
    Returns an engine list to compile to a restricted gate set.

    Note:
        If you choose a new gate set for which the compiler does not yet have
        standard rules, it raises an `NoGateDecompositionError` or a
        `RuntimeError: maximum recursion depth exceeded...`. Also note that
        even the gate sets which work might not yet be optimized. So make sure
        to double check and potentially extend the decomposition rules.
        This implemention currently requires that the one qubit gates must
        contain Rz and at least one of {Ry(best), Rx, H} and the two qubit
        gate must contain CNOT (recommended) or CZ.

    Note:
        Classical instructions gates such as e.g. Flush and Measure are
        automatically allowed.

    Example:
        get_engine_list(one_qubit_gates=(Rz, Ry, Rx, H),
                        two_qubit_gates=(CNOT,),
                        other_gates=(TimeEvolution,))

    Args:
        one_qubit_gates: "any" allows any one qubit gate, otherwise provide a
                         tuple of the allowed gates. If the gates are
                         instances of a class (e.g. X), it allows all gates
                         which are equal to it. If the gate is a class (Rz),
                         it allows all instances of this class. Default is
                         "any"
        two_qubit_gates: "any" allows any two qubit gate, otherwise provide a
                         tuple of the allowed gates. If the gates are
                         instances of a class (e.g. CNOT), it allows all gates
                         which are equal to it. If the gate is a class, it
                         allows all instances of this class.
                         Default is (CNOT,).
        other_gates:     A tuple of the allowed gates. If the gates are
                         instances of a class (e.g. QFT), it allows all gates
                         which are equal to it. If the gate is a class, it
                         allows all instances of this class.
        compiler_chooser:function selecting the decomposition to use in the
                         Autoreplacer engine
    Raises:
        TypeError: If input is for the gates is not "any" or a tuple. Also if
                   element within tuple is not a class or instance of BasicGate
                   (e.g. CRz which is a shortcut function)

    Returns:
        A list of suitable compiler engines.
    """
    if two_qubit_gates != "any" and not isinstance(two_qubit_gates, tuple):
        raise TypeError("two_qubit_gates parameter must be 'any' or a tuple. "
                        "When supplying only one gate, make sure to correctly "
                        "create the tuple (don't miss the comma), "
                        "e.g. two_qubit_gates=(CNOT,)")
    if one_qubit_gates != "any" and not isinstance(one_qubit_gates, tuple):
        raise TypeError("one_qubit_gates parameter must be 'any' or a tuple.")
    if not isinstance(other_gates, tuple):
        raise TypeError("other_gates parameter must be a tuple.")

    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    allowed_gate_classes = []  # n-qubit gates
    allowed_gate_instances = []
    allowed_gate_classes1 = []  # 1-qubit gates
    allowed_gate_instances1 = []
    allowed_gate_classes2 = []  # 2-qubit gates
    allowed_gate_instances2 = []

    if one_qubit_gates != "any":
        for gate in one_qubit_gates:
            if inspect.isclass(gate):
                allowed_gate_classes1.append(gate)
            elif isinstance(gate, BasicGate):
                allowed_gate_instances1.append(gate)
            else:
                raise TypeError("unsupported one_qubit_gates argument")
    if two_qubit_gates != "any":
        for gate in two_qubit_gates:
            if inspect.isclass(gate):
                #  Controlled gate classes don't yet exists and would require
                #  separate treatment
                assert not isinstance(gate, ControlledGate)
                allowed_gate_classes2.append(gate)
            elif isinstance(gate, BasicGate):
                if isinstance(gate, ControlledGate):
                    allowed_gate_instances2.append((gate._gate, gate._n))
                else:
                    allowed_gate_instances2.append((gate, 0))
            else:
                raise TypeError("unsupported two_qubit_gates argument")
    for gate in other_gates:
        if inspect.isclass(gate):
            #  Controlled gate classes don't yet exists and would require
            #  separate treatment
            assert not isinstance(gate, ControlledGate)
            allowed_gate_classes.append(gate)
        elif isinstance(gate, BasicGate):
            if isinstance(gate, ControlledGate):
                allowed_gate_instances.append((gate._gate, gate._n))
            else:
                allowed_gate_instances.append((gate, 0))
        else:
            raise TypeError("unsupported other_gates argument")
    allowed_gate_classes = tuple(allowed_gate_classes)
    allowed_gate_instances = tuple(allowed_gate_instances)
    allowed_gate_classes1 = tuple(allowed_gate_classes1)
    allowed_gate_instances1 = tuple(allowed_gate_instances1)
    allowed_gate_classes2 = tuple(allowed_gate_classes2)
    allowed_gate_instances2 = tuple(allowed_gate_instances2)

    def low_level_gates(eng, cmd):
        all_qubits = [q for qr in cmd.all_qubits for q in qr]
        if isinstance(cmd.gate, ClassicalInstructionGate):
            # This is required to allow Measure, Allocate, Deallocate, Flush
            return True
        elif one_qubit_gates == "any" and len(all_qubits) == 1:
            return True
        elif two_qubit_gates == "any" and len(all_qubits) == 2:
            return True
        elif isinstance(cmd.gate, allowed_gate_classes):
            return True
        elif (cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances:
            return True
        elif (isinstance(cmd.gate, allowed_gate_classes1)
              and len(all_qubits) == 1):
            return True
        elif (isinstance(cmd.gate, allowed_gate_classes2)
              and len(all_qubits) == 2):
            return True
        elif cmd.gate in allowed_gate_instances1 and len(all_qubits) == 1:
            return True
        elif ((cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances2
              and len(all_qubits) == 2):
            return True
        return False

    return [
        AutoReplacer(rule_set, compiler_chooser),
        TagRemover(),
        InstructionFilter(high_level_gates),
        LocalOptimizer(5),
        AutoReplacer(rule_set, compiler_chooser),
        TagRemover(),
        InstructionFilter(one_and_two_qubit_gates),
        LocalOptimizer(5),
        AutoReplacer(rule_set, compiler_chooser),
        TagRemover(),
        InstructionFilter(low_level_gates),
        LocalOptimizer(5),
    ]
Пример #25
0
            return True
        elif isinstance(g, AddConstantModN):
            return True
        return False
    return eng.next_engine.is_available(cmd)


if __name__ == "__main__":
    # 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
    ]

    # GET Input number from Command line
    parser = argparse.ArgumentParser(description='Shor')
    parser.add_argument("--number",
                        action="store",
                        default=10,
                        dest="input_number",
                        help="select the number to factor")
    myarg = parser.parse_args()
Пример #26
0
from projectq.setups import restrictedgateset
from projectq.cengines import (MainEngine, AutoReplacer, LocalOptimizer,
                               TagRemover, DecompositionRuleSet)
from hiq.projectq.cengines import GreedyScheduler, HiQMainEngine
from hiq.projectq.backends import SimulatorMPI
import projectq.setups.decompositions

from mpi4py import MPI

backend = SimulatorMPI(gate_fusion=True, num_local_qubits=2)

cache_depth = 10
rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
temp = LocalOptimizer(cache_depth)
engines = [
    TagRemover(), temp,
    AutoReplacer(rule_set),
    TagRemover(),
    LocalOptimizer(cache_depth),
    GreedyScheduler()
]

# create a list of restriction engines
restric_engine = restrictedgateset.get_engine_list(one_qubit_gates=(X, Y, Z, H,
                                                                    S, T, Rx,
                                                                    Ry, Rz),
                                                   two_qubit_gates=(CZ, CX))

eng = HiQMainEngine(backend, engine_list=engines + [CommandPrinter()])

Пример #27
0
from mpi4py import MPI
def adiabatic_simulation(eng):
	"""The function you need to modify.
	Returns:
	real_energy(float):
	The final ideally continously evolved energy.
	simulated_energy(float):
	The final energy simulated by your model.
	"""
	simulated_energy = 0
	real_energy = 0
	return simulated_energy, real_energy
if __name__ == "__main__":
	# use projectq simulator
	#eng = MainEngine()
	# use hiq simulator
	backend = SimulatorMPI(gate_fusion=True)
	cache_depth = 10
	rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
	engines = [TagRemover()
		, LocalOptimizer(cache_depth)
		, AutoReplacer(rule_set)
		, TagRemover()
		, LocalOptimizer(cache_depth)
		, GreedyScheduler()
		]
	# make the compiler and run the circuit on the simulator backend
	eng = HiQMainEngine(backend, engines)
	simulated_energy, real_energy = adiabatic_simulation(eng)
	simulated_error = simulated_energy - real_energy
	print(simulated_error)
def run(a=4, b=6, N=7, x=2, param="count"):
    """
    Last update 19/02 : nb of gate linear in log(N)
    Be careful this algo is a bit long to execute
    |b> --> |b+(ax) mod N> works for
    :param a:
    :param b:
    :param N:
    :param x:
    :param param:
    :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
    n = int(math.log(N, 2)) + 1

    if param == "latex":
        drawing_engine = CircuitDrawer()
        eng2 = MainEngine(drawing_engine)
        xN = initialisation_n(eng2, N, n + 1)
        xx = initialisation_n(eng2, x, n + 1)
        xb = initialisation_n(eng2, b, n + 1)
        [xc, aux] = initialisation(eng2, [1, 0])
        cMultModN_non_Dagger(eng2, a, xb, xx, xN, aux, xc)
        eng2.flush()
        Measure | aux
        Measure | xc
        All(Measure) | xx
        All(Measure) | xb
        All(Measure) | xN
        eng2.flush()
        print(drawing_engine.get_latex())
    else:
        if param == "count":
            eng = MainEngine(resource_counter)
        else:
            eng = MainEngine(Simulator(), compilerengines)
        xN = initialisation_n(eng, N, n + 1)
        xx = initialisation_n(eng, x, n + 1)
        xb = initialisation_n(eng, b, n + 1)
        [aux, xc] = initialisation(eng, [0, 1])
        cMultModN_non_Dagger(eng, a, xb, xx, xN, aux, xc, N)
        Measure | aux
        Measure | xc
        All(Measure) | xx
        All(Measure) | xb
        All(Measure) | xN
        eng.flush()
        if param == "count":
            return resource_counter

        measurements_b = [0] * n
        measurements_x = [0] * n
        measurements_N = [0] * n
        for k in range(n):
            measurements_b[k] = int(xb[k])
            measurements_N[k] = int(xN[k])
            measurements_x[k] = int(xx[k])

        mes_aux = int(aux[0])
        mes_c = int(aux[0])
        return [
            measurements_b,
            meas2int(measurements_b), (b + a * x) % N, measurements_N,
            measurements_x, mes_aux, mes_c,
            meas2int(measurements_b),
            meas2int(measurements_N),
            meas2int(measurements_x)
        ]
Пример #29
0
    All(Measure) | q_list
    All(Measure) | ancillas
    Measure | phase_q

    # Call the main engine to execute
    eng.flush()

    # Obtain the output. The measured result will be the solution with high probability.
    results = ''
    for q in q_list:
        results = results + str(int(q))

    #Translate the bit string to a list of numbers
    xlist = bin_to_n(results)
    return xlist


# Run the program
#-----------------------------------------------------------------------------------------
backend = Simulator(gate_fusion=True)
cache_depth = 10
rule_set = DecompositionRuleSet(modules=[rules])
engines = [TagRemover(), LocalOptimizer(cache_depth), AutoReplacer(rule_set)]
eng = HiQMainEngine(backend, engines)

sudoku = 'x1,0,b,b\n,2,1,b,b\n,x2,3,b,b\n1,x3,3,x4'
#sudoku4x4 =  '2,1,0,3\n,0,x1,x2,1\n,1,x3,x4,x5\n3,0,1,2'
xlist = SolveSudoku(eng, sudoku)

print(xlist)
Пример #30
0
def get_engine_list(num_qubits,
                    cyclic=False,
                    one_qubit_gates="any",
                    two_qubit_gates=(CNOT, Swap)):
    """
    Returns an engine list to compile to a linear chain of qubits.

    Note:
        If you choose a new gate set for which the compiler does not yet have
        standard rules, it raises an `NoGateDecompositionError` or a
        `RuntimeError: maximum recursion depth exceeded...`. Also note that
        even the gate sets which work might not yet be optimized. So make sure
        to double check and potentially extend the decomposition rules.
        This implemention currently requires that the one qubit gates must
        contain Rz and at least one of {Ry(best), Rx, H} and the two qubit gate
        must contain CNOT (recommended) or CZ.

    Note:
        Classical instructions gates such as e.g. Flush and Measure are
        automatically allowed.

    Example:
        get_engine_list(num_qubits=10, cyclic=False,
                        one_qubit_gates=(Rz, Ry, Rx, H),
                        two_qubit_gates=(CNOT,))

    Args:
        num_qubits(int): Number of qubits in the chain
        cyclic(bool): If a circle or not. Default is False
        one_qubit_gates: "any" allows any one qubit gate, otherwise provide
                         a tuple of the allowed gates. If the gates are
                         instances of a class (e.g. X), it allows all gates
                         which are equal to it. If the gate is a class (Rz), it
                         allows all instances of this class. Default is "any"
        two_qubit_gates: "any" allows any two qubit gate, otherwise provide
                         a tuple of the allowed gates. If the gates are
                         instances of a class (e.g. CNOT), it allows all gates
                         which are equal to it. If the gate is a class, it
                         allows all instances of this class.
                         Default is (CNOT, Swap).
    Raises:
        TypeError: If input is for the gates is not "any" or a tuple.

    Returns:
        A list of suitable compiler engines.
    """
    if two_qubit_gates != "any" and not isinstance(two_qubit_gates, tuple):
        raise TypeError("two_qubit_gates parameter must be 'any' or a tuple. "
                        "When supplying only one gate, make sure to correctly "
                        "create the tuple (don't miss the comma), "
                        "e.g. two_qubit_gates=(CNOT,)")
    if one_qubit_gates != "any" and not isinstance(one_qubit_gates, tuple):
        raise TypeError("one_qubit_gates parameter must be 'any' or a tuple.")

    rule_set = DecompositionRuleSet(
        modules=[projectq.libs.math, projectq.setups.decompositions])
    allowed_gate_classes = []
    allowed_gate_instances = []
    if one_qubit_gates != "any":
        for gate in one_qubit_gates:
            if inspect.isclass(gate):
                allowed_gate_classes.append(gate)
            else:
                allowed_gate_instances.append((gate, 0))
    if two_qubit_gates != "any":
        for gate in two_qubit_gates:
            if inspect.isclass(gate):
                #  Controlled gate classes don't yet exists and would require
                #  separate treatment
                assert not isinstance(gate, ControlledGate)
                allowed_gate_classes.append(gate)
            else:
                if isinstance(gate, ControlledGate):
                    allowed_gate_instances.append((gate._gate, gate._n))
                else:
                    allowed_gate_instances.append((gate, 0))
    allowed_gate_classes = tuple(allowed_gate_classes)
    allowed_gate_instances = tuple(allowed_gate_instances)

    def low_level_gates(eng, cmd):
        all_qubits = [q for qr in cmd.all_qubits for q in qr]
        assert len(all_qubits) <= 2
        if isinstance(cmd.gate, ClassicalInstructionGate):
            # This is required to allow Measure, Allocate, Deallocate, Flush
            return True
        elif one_qubit_gates == "any" and len(all_qubits) == 1:
            return True
        elif two_qubit_gates == "any" and len(all_qubits) == 2:
            return True
        elif isinstance(cmd.gate, allowed_gate_classes):
            return True
        elif (cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances:
            return True
        else:
            return False

    return [
        AutoReplacer(rule_set),
        TagRemover(),
        InstructionFilter(high_level_gates),
        LocalOptimizer(5),
        AutoReplacer(rule_set),
        TagRemover(),
        InstructionFilter(one_and_two_qubit_gates),
        LocalOptimizer(5),
        LinearMapper(num_qubits=num_qubits, cyclic=cyclic),
        AutoReplacer(rule_set),
        TagRemover(),
        InstructionFilter(low_level_gates),
        LocalOptimizer(5),
    ]