コード例 #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
コード例 #2
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))
コード例 #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
ファイル: ibm.py プロジェクト: willyxq/ProjectQ
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 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]
コード例 #7
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)
コード例 #8
0
ファイル: ibm.py プロジェクト: silky/ProjectQ
def ibm_default_engines():
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(),
        TagRemover(),
        IBMCNOTMapper(),
        LocalOptimizer(10)
    ]
コード例 #9
0
def get_engine_list():
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    return [
        TagRemover(),
        LocalOptimizer(10),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(10)
    ]
コード例 #10
0
ファイル: _ibm_test.py プロジェクト: willyxq/ProjectQ
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
ファイル: default.py プロジェクト: Takishima/ProjectQ
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
ファイル: ibm.py プロジェクト: peter-janderks/quantumbomb
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 test_simulator_probability(mapper, capsys):
    sim = StabilizerSimulator(6)
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)
    eng = MainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(6)
    All(H) | qubits
    eng.flush()
    bits = [0, 0, 1, 0, 1, 0]
    for i in range(6):
        assert (eng.backend.get_probability(
            bits[:i], qubits[:i]) == pytest.approx(0.5**i))
    extra_qubit = eng.allocate_qubit()
    with pytest.raises(RuntimeError):
        eng.backend.get_probability([0], extra_qubit)
    del extra_qubit

    All(H) | qubits
    eng.flush()
    assert eng.backend.get_probability('0' * len(qubits),
                                       qubits) == pytest.approx(1.0)
    assert eng.backend.get_probability('1' * len(qubits),
                                       qubits) == pytest.approx(0.0)
    All(Measure) | qubits
コード例 #15
0
def test_simulator_collapse_wavefunction(mapper):
    sim = StabilizerSimulator(16)
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)
    eng = MainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(4)
    # unknown qubits: raises
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [0] * 4)
    eng.flush()
    eng.backend.collapse_wavefunction(qubits, [0] * 4)
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == 1.
    All(H) | qubits[:-1]
    eng.flush()
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == .125
    # impossible outcome: raises
    prob = eng.backend.get_probability([1, 0, 1, 0], qubits)
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [0] * 3 + [1])
    # Make sure nothing the state of the simulator has not changed
    assert pytest.approx(prob) == eng.backend.get_probability([1, 0, 1, 0],
                                                              qubits)
    eng.backend.collapse_wavefunction(qubits[1:], [0, 1, 0])
    probability = eng.backend.get_probability([1, 0, 1, 0], qubits)
    assert probability == pytest.approx(.5)
    eng.backend.set_qubits(qubits, [0] * 3 + [1])
    H | qubits[0]
    CNOT | (qubits[0], qubits[1])
    eng.flush()
    eng.backend.collapse_wavefunction([qubits[0]], [1])
    probability = eng.backend.get_probability([1, 1], qubits[0:2])
    assert probability == pytest.approx(1.)
コード例 #16
0
def test_simulator_collapse_wavefunction(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)
    eng = MainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(4)
    # unknown qubits: raises
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [0] * 4)
    eng.flush()
    eng.backend.collapse_wavefunction(qubits, [0] * 4)
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == 1.
    All(H) | qubits[1:]
    eng.flush()
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == .125
    # impossible outcome: raises
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [1] + [0] * 3)
    eng.backend.collapse_wavefunction(qubits[:-1], [0, 1, 0])
    probability = eng.backend.get_probability([0, 1, 0, 1], qubits)
    assert probability == pytest.approx(.5)
    eng.backend.set_wavefunction([1.] + [0.] * 15, qubits)
    H | qubits[0]
    CNOT | (qubits[0], qubits[1])
    eng.flush()
    eng.backend.collapse_wavefunction([qubits[0]], [1])
    probability = eng.backend.get_probability([1, 1], qubits[0:2])
    assert probability == pytest.approx(1.)
コード例 #17
0
def test_simulator_probability(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)
    eng = MainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(6)
    All(H) | qubits
    eng.flush()
    bits = [0, 0, 1, 0, 1, 0]
    for i in range(6):
        assert (eng.backend.get_probability(
            bits[:i], qubits[:i]) == pytest.approx(0.5**i))
    extra_qubit = eng.allocate_qubit()
    with pytest.raises(RuntimeError):
        eng.backend.get_probability([0], extra_qubit)
    del extra_qubit
    All(H) | qubits
    Ry(2 * math.acos(math.sqrt(0.3))) | qubits[0]
    eng.flush()
    assert eng.backend.get_probability([0], [qubits[0]]) == pytest.approx(0.3)
    Ry(2 * math.acos(math.sqrt(0.4))) | qubits[2]
    eng.flush()
    assert eng.backend.get_probability([0], [qubits[2]]) == pytest.approx(0.4)
    assert (eng.backend.get_probability([0, 0],
                                        qubits[:3:2]) == pytest.approx(0.12))
    assert (eng.backend.get_probability([0, 1],
                                        qubits[:3:2]) == pytest.approx(0.18))
    assert (eng.backend.get_probability([1, 0],
                                        qubits[:3:2]) == pytest.approx(0.28))
    All(Measure) | qubits
コード例 #18
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)
    ]
コード例 #19
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
コード例 #20
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
コード例 #21
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
コード例 #22
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
コード例 #23
0
ファイル: _main_test.py プロジェクト: silky/ProjectQ
def test_main_engine_del():
    # need engine which caches commands to test that del calls flush
    caching_engine = LocalOptimizer(m=5)
    backend = DummyEngine(save_commands=True)
    eng = _main.MainEngine(backend=backend, engine_list=[caching_engine])
    qubit = eng.allocate_qubit()
    H | qubit
    assert len(backend.received_commands) == 0
    eng.__del__()
    # Allocate, H, and Flush Gate
    assert len(backend.received_commands) == 3
コード例 #24
0
ファイル: _main_test.py プロジェクト: Takishima/ProjectQ
def test_main_engine_del():
    # Clear previous exceptions of other tests
    sys.last_type = None
    del sys.last_type
    # need engine which caches commands to test that del calls flush
    caching_engine = LocalOptimizer(cache_size=5)
    backend = DummyEngine(save_commands=True)
    eng = _main.MainEngine(backend=backend, engine_list=[caching_engine])
    qubit = eng.allocate_qubit()
    H | qubit
    assert len(backend.received_commands) == 0
    eng.__del__()
    # Allocate, H, Deallocate, and Flush Gate
    assert len(backend.received_commands) == 4
コード例 #25
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)
コード例 #26
0
def test_simulator_set_wavefunction(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)
    eng = MainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(2)
    wf = [0., 0., math.sqrt(0.2), math.sqrt(0.8)]
    with pytest.raises(RuntimeError):
        eng.backend.set_wavefunction(wf, qubits)
    eng.flush()
    eng.backend.set_wavefunction(wf, qubits)
    assert pytest.approx(eng.backend.get_probability('1', [qubits[0]])) == .8
    assert pytest.approx(eng.backend.get_probability('01', qubits)) == .2
    assert pytest.approx(eng.backend.get_probability('1', [qubits[1]])) == 1.
    All(Measure) | qubits
コード例 #27
0
def test_check_that_local_optimizer_doesnt_merge():
    mapper = two_d.GridMapper(num_rows=2, num_columns=2)
    optimizer = LocalOptimizer(10)
    backend = DummyEngine(save_commands=True)
    backend.is_last_engine = True
    mapper.next_engine = optimizer
    optimizer.next_engine = backend
    mapper.current_mapping = {0: 0}
    mapper.storage = 1
    qb0 = WeakQubitRef(engine=None, idx=0)
    qb1 = WeakQubitRef(engine=None, idx=1)
    qb_flush = WeakQubitRef(engine=None, idx=-1)
    cmd_flush = Command(engine=None, gate=FlushGate(), qubits=([qb_flush],))
    cmd0 = Command(engine=None, gate=Allocate, qubits=([qb0],))
    cmd1 = Command(None, X, qubits=([qb0],))
    cmd2 = Command(engine=None, gate=Deallocate, qubits=([qb0],))
    mapper.receive([cmd0, cmd1, cmd2])
    assert len(mapper._stored_commands) == 0
    mapper.current_mapping = {1: 0}
    cmd3 = Command(engine=None, gate=Allocate, qubits=([qb1],))
    cmd4 = Command(None, X, qubits=([qb1],))
    cmd5 = Command(engine=None, gate=Deallocate, qubits=([qb1],))
    mapper.receive([cmd3, cmd4, cmd5, cmd_flush])
    assert len(backend.received_commands) == 7
    def _recursive_decompose(self, cmd):
        if self.is_available(cmd):
            return [cmd]

        canonical_cmd, id_map, key, used, avail = self._canonicalize(cmd)
        if key in self._cached_results:
            if self._cached_results == 'IN PROGRESS':
                raise NoGateDecompositionError(
                    'Cyclic decomposition for {}.'.format(cmd))
            return self._translate(cmd, self._cached_results[key], id_map)
        self._cached_results[key] = 'IN PROGRESS'

        rec = DummyEngine(save_commands=True)
        eng = MainEngine(backend=rec,
                         engine_list=[
                             LocalOptimizer(),
                             SimpleAdjacentCombiner(self.merge_rules),
                         ])
        involved = eng.allocate_qureg(used)
        workspace = eng.allocate_qureg(avail)
        eng.flush()
        rec.received_commands = []
        canonical_cmd.engine = eng

        self._pick_decomp_for(cmd).decompose(canonical_cmd)
        eng.flush()
        intermediate_result = rec.received_commands[:-1]

        assert involved is not None
        assert workspace is not None

        flattened_result = [
            leaf for child in intermediate_result
            for leaf in self._recursive_decompose(child)
        ]

        self._cached_results[key] = flattened_result
        return self._translate(cmd, flattened_result, id_map)
コード例 #29
0
def test_simulator_amplitude(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)

    engine_list.append(GreedyScheduler())
    eng = HiQMainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(6)
    All(X) | qubits
    All(H) | qubits
    eng.flush()
    bits = [0, 0, 1, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(1. / 8.)
    bits = [0, 0, 0, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(-1. / 8.)
    bits = [0, 1, 1, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(-1. / 8.)
    All(H) | qubits
    All(X) | qubits
    Ry(2 * math.acos(0.3)) | qubits[0]
    eng.flush()
    bits = [0] * 6
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(0.3)
    bits[0] = 1
    assert (eng.backend.get_amplitude(bits, qubits) == pytest.approx(
        math.sqrt(0.91)))
    All(Measure) | qubits
    # raises if not all qubits are in the list:
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits[:-1])
    # doesn't just check for length:
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits[:-1] + [qubits[0]])
    extra_qubit = eng.allocate_qubit()
    eng.flush()
    # there is a new qubit now!
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits)
コード例 #30
0
        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()

    # GET VARIABLES FROM CK_ENV