示例#1
0
文件: qpu.py 项目: ProteinQure/pyquil
def get_devices(async_endpoint=ASYNC_ENDPOINT, api_key=None, user_id=None,
                as_dict=False):
    """
    Get a list of currently available devices. The arguments for this method are the same as those for QPUConnection.
    Note that this method will only work for accounts that have QPU access.

    :return: Set or Dictionary (keyed by device name) of all available devices.
    :rtype: Set|Dict
    """
    session = get_session(api_key, user_id)
    response = session.get(async_endpoint + '/devices')
    if response.status_code >= 400:
        raise parse_error(response)

    if not as_dict:
        warnings.warn("""
Warning: The return type Set for get_devices() is being deprecated for Dict. This will eventually
return the following:

    get_devices()
    # {'19Q-Acorn': <Device 19Q-Acorn online>, '8Q-Agave': <Device 8Q-Agave offline>}
    acorn = get_devices()['19Q-Acorn']

To use this Dict return type now, you may optionally pass the flag get_devices(as_dict=True). This
will become the default behavior in a future pyQuil release.
""", DeprecationWarning, stacklevel=2)
        return {Device(name, device) for (name, device) in response.json()['devices'].items()}

    return {name: Device(name, device) for (name, device) in response.json()['devices'].items()}
示例#2
0
def test_NxDevice(isa_dict, noise_model_dict):
    graph = isa_to_graph(ISA.from_dict(isa_dict))
    nxdev = NxDevice(graph)

    device_raw = {'isa': isa_dict,
                  'noise_model': noise_model_dict,
                  'is_online': True,
                  'is_retuning': False}
    dev = Device(DEVICE_FIXTURE_NAME, device_raw)

    nx.is_isomorphic(nxdev.qubit_topology(), dev.qubit_topology())
    isa = nxdev.get_isa()
    assert isa.qubits[0].type == 'Xhalves'
示例#3
0
def test_NxDevice(isa_dict, noise_model_dict):
    graph = isa_to_graph(ISA.from_dict(isa_dict))
    nxdev = NxDevice(graph)

    device_raw = {
        "isa": isa_dict,
        "noise_model": noise_model_dict,
        "is_online": True,
        "is_retuning": False,
    }
    dev = Device(DEVICE_FIXTURE_NAME, device_raw)

    nx.is_isomorphic(nxdev.qubit_topology(), dev.qubit_topology())
    isa = nxdev.get_isa()
    assert isa.qubits[0].type == "Xhalves"
示例#4
0
def test_device(isa_dict, noise_model_dict):
    device_raw = {'isa': isa_dict,
                  'noise_model': noise_model_dict,
                  'is_online': True,
                  'is_retuning': False}

    device = Device(DEVICE_FIXTURE_NAME, device_raw)
    assert device.name == DEVICE_FIXTURE_NAME
    assert device.is_online()
    assert not device.is_retuning()

    isa = ISA.from_dict(isa_dict)
    noise_model = NoiseModel.from_dict(noise_model_dict)
    assert isinstance(device.isa, ISA)
    assert device.isa == isa
    assert isinstance(device.noise_model, NoiseModel)
    assert device.noise_model == noise_model
示例#5
0
def test_http_compilation_failure(compiler):
    device_name = "test_device"
    mock_url = "http://mock-qpu-compiler"

    config = PyquilConfig(TEST_CONFIG_PATHS)
    session = get_session(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("http://", mock_adapter)

    headers = {
        # access token from ./data/user_auth_token_valid.json.
        "Authorization": "Bearer secret"
    }

    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/get_version_info",
        status_code=200,
        json={},
        headers=headers,
    )

    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/native_quilt_to_binary",
        status_code=500,
        json={"message": "test compilation failed"},
        headers=headers,
    )

    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/get_quilt_calibrations",
        status_code=200,
        json=CALIBRATIONS_RESPONSE,
        headers=headers,
    )

    device = Device(name="not_actually_device_name",
                    raw={
                        "device_name": device_name,
                        "isa": DUMMY_ISA_DICT
                    })

    compiler = QPUCompiler(
        quilc_endpoint=session.config.quilc_url,
        qpu_compiler_endpoint=mock_url,
        device=device,
        session=session,
    )

    native_quil = compiler.quil_to_native_quil(simple_program())

    try:
        compiler.native_quil_to_executable(native_quil)
    except UserMessageError as e:
        assert "test compilation failed" in str(e)
示例#6
0
def get_lattice(lattice_name: str = None):
    """
    Construct a Device object to match the Forest 2.0 server's understanding of the named lattice.

    :param lattice_name: Name of the desired lattice.
    :return: A Device object.
    """
    raw_lattice = _get_raw_lattice_data(lattice_name)

    return Device(raw_lattice["name"], raw_lattice)
示例#7
0
def test_compile_with_quilt_calibrations(compiler):
    device_name = "test_device"
    mock_url = "http://mock-qpu-compiler"

    config = PyquilConfig(TEST_CONFIG_PATHS)
    session = get_session(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("http://", mock_adapter)

    headers = {
        # access token from ./data/user_auth_token_valid.json.
        "Authorization": "Bearer secret"
    }
    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/get_version_info",
        status_code=200,
        json={},
        headers=headers,
    )

    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/native_quilt_to_binary",
        status_code=200,
        json=SIMPLE_RESPONSE,
        headers=headers,
    )

    device = Device(name="not_actually_device_name",
                    raw={
                        "device_name": device_name,
                        "isa": DUMMY_ISA_DICT
                    })
    compiler = QPUCompiler(
        quilc_endpoint=session.config.quilc_url,
        qpu_compiler_endpoint=mock_url,
        device=device,
        session=session,
    )

    program = simple_program()
    q = FormalArgument("q")
    defn = DefCalibration(
        "H", [], [q],
        [RZ(math.pi / 2, q),
         RX(math.pi / 2, q),
         RZ(math.pi / 2, q)])
    cals = [defn]
    program._calibrations = cals
    # this should more or less pass through
    compilation_result = compiler.quil_to_native_quil(program, protoquil=True)
    assert compilation_result.calibrations == cals
    assert program.calibrations == cals
    assert compilation_result == program
示例#8
0
def get_devices(async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None):
    """
    Get a list of currently available devices. The arguments for this method are the same as those for QPUConnection.
    Note that this method will only work for accounts that have QPU access.

    :return: set of online and offline devices
    :rtype: set
    """
    session = get_session(api_key, user_id)
    response = session.get(async_endpoint + '/devices')
    if response.status_code >= 400:
        raise parse_error(response)
    return {Device(name, device) for (name, device) in response.json()['devices'].items()}
示例#9
0
def run_quilc_pass(circ: Circuit, backend: str):
    try:
        RebaseQuil().apply(circ)
        p_circ = tk_to_pyquil(circ)
        if backend == _BACKEND_IBM:
            devgraph = nx.from_edgelist(ibm_coupling)
            twoq_type = ['CZ']
            twoq_set = {OpType.CZ}
        elif backend == _BACKEND_RIGETTI:
            devgraph = nx.from_edgelist(rigetti_coupling)
            twoq_type = ['CZ', 'XY']
            twoq_set = {OpType.CZ, OpType.ISWAP}
        elif backend == _BACKEND_GOOGLE:
            devgraph = nx.from_edgelist(google_coupling)
            twoq_type = ['CZ']
            twoq_set = {OpType.CZ}
        elif backend == _BACKEND_FULL:
            devgraph = nx.complete_graph(circ.n_qubits)
            twoq_type = ['CZ', 'XY']
            twoq_set = {OpType.CZ, OpType.ISWAP}
        isa = isa_from_graph(devgraph, twoq_type=twoq_type)
        device = Device_("dev", {"isa": isa.to_dict()})
        device._isa = isa
        qcompiler = QVMCompiler(PyquilConfig().quilc_url, device, timeout=600)
        start_time = time.time()
        compiled_pr = qcompiler.quil_to_native_quil(p_circ)
        time_elapsed = time.time() - start_time
        print(time_elapsed)
        circ2 = pyquil_to_tk(compiled_pr)
        return [
            circ2.n_gates,
            circ2.depth(),
            sum(circ2.n_gates_of_type(op) for op in twoq_set),
            circ2.depth_by_type(twoq_set), time_elapsed
        ]
    except Exception as e:
        print(e)
        print("quilc error")
        return [nan, nan, nan, nan, nan]
示例#10
0
def test_device(isa_dict, noise_model_dict):
    device_raw = {'isa': isa_dict,
                  'noise_model': noise_model_dict,
                  'is_online': True,
                  'is_retuning': False}

    device = Device(DEVICE_FIXTURE_NAME, device_raw)
    assert device.name == DEVICE_FIXTURE_NAME

    isa = ISA.from_dict(isa_dict)
    noise_model = NoiseModel.from_dict(noise_model_dict)
    # Device.isa is deprecated, but seemingly this is what we want here
    with pytest.warns(DeprecationWarning):
        assert isinstance(device.isa, ISA)
        assert device.isa == isa
    assert isinstance(device.noise_model, NoiseModel)
    assert device.noise_model == noise_model
示例#11
0
def test_http_compilation(compiler):
    device_name = "test_device"
    mock_url = "http://mock-qpu-compiler"

    config = PyquilConfig(TEST_CONFIG_PATHS)
    session = get_session(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("http://", mock_adapter)

    headers = {
        # access token from ./data/user_auth_token_valid.json.
        "Authorization": "Bearer secret"
    }
    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/get_version_info",
        status_code=200,
        json={},
        headers=headers,
    )

    mock_adapter.register_uri(
        "POST",
        f"{mock_url}/devices/{device_name}/native_quil_to_binary",
        status_code=200,
        json=SIMPLE_RESPONSE,
        headers=headers,
    )

    device = Device(
        name="not_actually_device_name", raw={"device_name": device_name, "isa": DUMMY_ISA_DICT}
    )
    compiler = QPUCompiler(
        quilc_endpoint=session.config.quilc_url,
        qpu_compiler_endpoint=mock_url,
        device=device,
        session=session,
    )

    compilation_result = compiler.native_quil_to_executable(
        compiler.quil_to_native_quil(simple_program())
    )

    assert isinstance(compilation_result, BinaryExecutableResponse)
    assert compilation_result.program == SIMPLE_RESPONSE["program"]
示例#12
0
def test_invalid_protocol():
    device_name = "test_device"
    mock_url = "not-http-or-tcp://mock-qpu-compiler"

    config = PyquilConfig(TEST_CONFIG_PATHS)
    session = get_session(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("", mock_adapter)
    device = Device(
        name="not_actually_device_name", raw={"device_name": device_name, "isa": DUMMY_ISA_DICT}
    )

    with pytest.raises(UserMessageError):
        QPUCompiler(
            quilc_endpoint=session.config.quilc_url,
            qpu_compiler_endpoint=mock_url,
            device=device,
            session=session,
        )
示例#13
0
def test_device(device_raw):
    return Device('test_device', device_raw)
示例#14
0
 def noise_model(self, dev: device.Device) -> noise.NoiseModel:
     return noise._decoherence_noise_model(gates=device.gates_in_isa(
         dev.get_isa()),
                                           T1=300e-6,
                                           T2=300e-6,
                                           ro_fidelity=0.99)
示例#15
0
def test_device(device_raw):
    return Device("test_device", device_raw)
示例#16
0
    neuron_prog += Program(H(inputs[0]), H(inputs[1]), CNOT(inputs[0], training), CNOT(inputs[1], training))
    
    neuron_prog += DOUBLERY(w, beta, inputs[0], inputs[1], ancilla[0])
    neuron_prog += CMIY(ancilla[0], ancilla[2])
    neuron_prog += DOUBLERYINV(w, beta, inputs[0], inputs[1], ancilla[0])
    neuron_prog += CMIY(ancilla[2], output)
    
    neuron_prog += DOUBLERYINV(w, beta, inputs[0], inputs[1], ancilla[1])
    neuron_prog += CIY(ancilla[1], ancilla[2])
    neuron_prog += DOUBLERY(w, beta, inputs[0], inputs[1], ancilla[1])
    return neuron_prog

# Load device information and generate compiler object
with open('19Q-Acorn.json', 'r') as infile:
    dev_data = json.load(infile)
acorn = Device('19Q-Acorn', dev_data)
compiler = CompilerConnection(acorn)

# Helper function which prints the status of the compilation
def print_job_stats(job):
    print("Gate depth: {}\nGate volume: {}\nTopological Swaps: {}\nMultiq gate depth: {}".format(job.gate_depth(), job.gate_volume(), job.topological_swaps(), job.multiqubit_gate_depth()))

# Helper function for checking the quality of an embedding
def check_compilation(inputs, training, ancilla, output, cmp=compiler):
    qnn_prog = make_neuron([0, 1], np.pi/3., inputs, training, ancilla, output)
    qubits = list(inputs + [training] + ancilla + [output])
    qnn_prog += Program([MEASURE(xx, xx) for xx in qubits])
    compiled_result = compiler.compile_async(Program(qnn_prog))
    job = compiler.get_job(compiled_result)
    job = wait_for_job(compiled_result)
    #print_job_stats(job)