Exemplo n.º 1
0
def test_run(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(name='testy!',
                         qam=QVM(connection=forest, gate_noise=[0.01] * 3),
                         device=device,
                         compiler=DummyCompiler())
    bitstrings = qc.run(Program(H(0), CNOT(0, 1), CNOT(1, 2), MEASURE(0, 0),
                                MEASURE(1, 1),
                                MEASURE(2, 2)).wrap_in_numshots_loop(1000),
                        classical_addresses=None)

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15
Exemplo n.º 2
0
def test_run_with_parameters(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(name='testy!',
                         qam=QVM(connection=forest),
                         device=device,
                         compiler=DummyCompiler())
    bitstrings = qc.run(executable=Program(
        Declare(name='theta', memory_type='REAL'),
        Declare(name='ro', memory_type='BIT'), RX(MemoryReference('theta'), 0),
        MEASURE(0, MemoryReference('ro'))).wrap_in_numshots_loop(1000),
                        memory_map={'theta': [np.pi]})

    assert bitstrings.shape == (1000, 1)
    assert all([bit == 1 for bit in bitstrings])
Exemplo n.º 3
0
def test_readout_symmetrization(forest):
    device = NxDevice(nx.complete_graph(3))
    noise_model = decoherence_noise_with_asymmetric_ro(
        gates=gates_in_isa(device.get_isa()))
    qc = QuantumComputer(name='testy!',
                         qam=QVM(connection=forest, noise_model=noise_model),
                         device=device,
                         compiler=DummyCompiler())

    prog = Program(I(0), X(1), MEASURE(0, 0), MEASURE(1, 1))
    prog.wrap_in_numshots_loop(1000)

    bs1 = qc.run(prog)
    avg0_us = np.mean(bs1[:, 0])
    avg1_us = 1 - np.mean(bs1[:, 1])
    diff_us = avg1_us - avg0_us
    assert diff_us > 0.03

    bs2 = qc.run_symmetrized_readout(prog, 1000)
    avg0_s = np.mean(bs2[:, 0])
    avg1_s = 1 - np.mean(bs2[:, 1])
    diff_s = avg1_s - avg0_s
    assert diff_s < 0.05
Exemplo n.º 4
0
def test_run_pyqvm_noiseless():
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!", qam=PyQVM(n_qubits=3), device=device, compiler=DummyCompiler()
    )
    prog = Program(H(0), CNOT(0, 1), CNOT(1, 2))
    ro = prog.declare("ro", "BIT", 3)
    for q in range(3):
        prog += MEASURE(q, ro[q])
    bitstrings = qc.run(prog.wrap_in_numshots_loop(1000))

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert np.mean(parity) == 0
Exemplo n.º 5
0
def test_run_pyqvm_noisy():
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name='testy!',
        qam=PyQVM(n_qubits=3,
                  post_gate_noise_probabilities={'relaxation': 0.01}),
        device=device,
        compiler=DummyCompiler())
    bitstrings = qc.run(
        Program(H(0), CNOT(0, 1), CNOT(1, 2), MEASURE(0, 0), MEASURE(1, 1),
                MEASURE(2, 2)).wrap_in_numshots_loop(1000))

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15
Exemplo n.º 6
0
    def __init__(self, data, label, shuffle=False, qpu=False):
        weights = np.load(data)
        n_graphs = len(weights)

        # read labels from file, or as single label
        if os.path.exists(label):
            labels = np.load(label)
        else:
            labels = [label for _ in range(n_graphs)]

        if shuffle:
            self._shuffled_order = np.random.permutation(n_graphs)
            weights = weights[self._shuffled_order]
            labels = labels[self._shuffled_order]

        self.pset = AllProblems(weights, labels)
        self.num_qubits = self.pset.num_variables()

        qubits = list(range(self.num_qubits))
        angles = np.linspace(0, 2 * np.pi, NUM_ANGLES, endpoint=False)
        self.instrs = [
            CNOT(q0, q1) for q0, q1 in product(qubits, qubits) if q0 != q1
        ]
        self.instrs += [
            op(theta, q)
            for q, op, theta in product(qubits, [RX, RY, RZ], angles)
        ]
        self.action_space = gym.spaces.Discrete(len(self.instrs))

        obs_len = NUM_SHOTS * self.num_qubits + len(self.pset.problem(0))
        self.observation_space = gym.spaces.Box(np.full(obs_len, -1.0),
                                                np.full(obs_len, 1.0),
                                                dtype=np.float32)

        self.reward_threshold = 0.8

        self.qpu = qpu
        if qpu:
            self._qc = get_qc(QPU_NAME)
        else:
            self._qc = QuantumComputer(
                name="qvm",
                qam=PyQVM(n_qubits=self.num_qubits),
                device=NxDevice(nx.complete_graph(self.num_qubits)),
                compiler=MinimalPyQVMCompiler(),
            )

        self.reset()
Exemplo n.º 7
0
def test_run_with_parameters(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!", qam=QVM(connection=forest), device=device, compiler=DummyCompiler()
    )
    bitstrings = qc.run(
        executable=Program(
            Declare(name="theta", memory_type="REAL"),
            Declare(name="ro", memory_type="BIT"),
            RX(MemoryReference("theta"), 0),
            MEASURE(0, MemoryReference("ro")),
        ).wrap_in_numshots_loop(1000),
        memory_map={"theta": [np.pi]},
    )

    assert bitstrings.shape == (1000, 1)
    assert all([bit == 1 for bit in bitstrings])
def get_test_qc(n_qubits):
    class BasicQVMCompiler(AbstractCompiler):
        def quil_to_native_quil(self, program: Program):
            return basic_compile(program)

        def native_quil_to_executable(self, nq_program: Program):
            return PyQuilExecutableResponse(
                program=nq_program.out(),
                attributes=_extract_attribute_dictionary_from_program(
                    nq_program))

    return QuantumComputer(
        name='testing-qc',
        qam=PyQVM(n_qubits=n_qubits, seed=52),
        device=NxDevice(nx.complete_graph(n_qubits)),
        compiler=BasicQVMCompiler(),
    )
Exemplo n.º 9
0
def test_for_negative_probabilities():
    # trivial program to do state tomography on
    prog = Program(I(0))

    # make TomographyExperiment
    expt_settings = [ExperimentSetting(zeros_state([0]), pt) for pt in [sI(0), sX(0), sY(0), sZ(0)]]
    experiment_1q = TomographyExperiment(settings=expt_settings, program=prog)

    # make an abstract compiler
    class DummyCompiler(AbstractCompiler):
        def get_version_info(self):
            return {}

        def quil_to_native_quil(self, program: Program):
            return program

        def native_quil_to_executable(self, nq_program: Program):
            return nq_program

    # make a quantum computer object
    device = NxDevice(nx.complete_graph(1))
    qc_density = QuantumComputer(name='testy!',
                                 qam=PyQVM(n_qubits=1,
                                           quantum_simulator_type=ReferenceDensitySimulator),
                                 device=device,
                                 compiler=DummyCompiler())

    # initialize with a pure state
    initial_density = np.array([[1.0, 0.0], [0.0, 0.0]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(measure_observables(qc=qc_density, tomo_experiment=experiment_1q, n_shots=3000))
    except ValueError as e:
        # the error is from np.random.choice by way of self.rs.choice in ReferenceDensitySimulator
        assert str(e) != 'probabilities are not non-negative'

    # initialize with a mixed state
    initial_density = np.array([[0.9, 0.0], [0.0, 0.1]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(measure_observables(qc=qc_density, tomo_experiment=experiment_1q, n_shots=3000))
    except ValueError as e:
        assert str(e) != 'probabilities are not non-negative'
Exemplo n.º 10
0
def test_for_negative_probabilities():
    # trivial program to do state tomography on
    prog = Program(I(0))

    # make an Experiment
    expt_settings = [
        ExperimentSetting(zeros_state([0]), pt)
        for pt in [sI(0), sX(0), sY(0), sZ(0)]
    ]
    experiment_1q = Experiment(settings=expt_settings, program=prog)

    # make a quantum computer object
    device = NxDevice(nx.complete_graph(1))
    qc_density = QuantumComputer(
        name="testy!",
        qam=PyQVM(n_qubits=1,
                  quantum_simulator_type=ReferenceDensitySimulator),
        device=device,
        compiler=DummyCompiler(),
    )

    # initialize with a pure state
    initial_density = np.array([[1.0, 0.0], [0.0, 0.0]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(
            measure_observables(qc=qc_density,
                                tomo_experiment=experiment_1q,
                                n_shots=3000))
    except ValueError as e:
        # the error is from np.random.choice by way of self.rs.choice in ReferenceDensitySimulator
        assert str(e) != "probabilities are not non-negative"

    # initialize with a mixed state
    initial_density = np.array([[0.9, 0.0], [0.0, 0.1]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(
            measure_observables(qc=qc_density,
                                tomo_experiment=experiment_1q,
                                n_shots=3000))
    except ValueError as e:
        assert str(e) != "probabilities are not non-negative"
def quil_compile(input, device):
    name = device["name"]

    g = nx.Graph()
    g.add_edges_from(device["topology"])
    qc = NxDevice(g)

    p = Program(open(f"input/{input}.quil", "r").read())
    compiler = LocalQVMCompiler("http://localhost:6000", qc)
    np = compiler.quil_to_native_quil(p)

    volume, depth = np.native_quil_metadata[
        "gate_volume"], np.native_quil_metadata["gate_depth"]

    with open(f"output/{input}_{name}.quil", "w") as f:
        f.write(str(np))
    with open(f"output/{input}_{name}.json", "w") as f:
        f.write(json.dumps({'volume': volume, 'depth': depth}))
Exemplo n.º 12
0
def test_qc_expectation_larger_lattice(forest):
    device = NxDevice(nx.complete_graph(4))
    qc = QuantumComputer(name='testy!',
                         qam=QVM(connection=forest),
                         device=device,
                         compiler=DummyCompiler())

    q0 = 2
    q1 = 3

    # bell state program
    p = Program()
    p += RESET()
    p += H(q0)
    p += CNOT(q0, q1)
    p.wrap_in_numshots_loop(10)

    # XX, YY, ZZ experiment
    sx = ExperimentSetting(in_state=sZ(q0) * sZ(q1),
                           out_operator=sX(q0) * sX(q1))
    sy = ExperimentSetting(in_state=sZ(q0) * sZ(q1),
                           out_operator=sY(q0) * sY(q1))
    sz = ExperimentSetting(in_state=sZ(q0) * sZ(q1),
                           out_operator=sZ(q0) * sZ(q1))

    e = TomographyExperiment(settings=[sx, sy, sz], program=p)

    results = qc.experiment(e)

    # XX expectation value for bell state |00> + |11> is 1
    assert np.isclose(results[0].expectation, 1)
    assert np.isclose(results[0].std_err, 0)
    assert results[0].total_counts == 40

    # YY expectation value for bell state |00> + |11> is -1
    assert np.isclose(results[1].expectation, -1)
    assert np.isclose(results[1].std_err, 0)
    assert results[1].total_counts == 40

    # ZZ expectation value for bell state |00> + |11> is 1
    assert np.isclose(results[2].expectation, 1)
    assert np.isclose(results[2].std_err, 0)
    assert results[2].total_counts == 40
Exemplo n.º 13
0
def test_run(forest):
    qc = QuantumComputer(
        name='testy!',
        qam=QVM(connection=forest, gate_noise=[0.01] * 3),
        device=NxDevice(nx.complete_graph(3)),
    )
    bitstrings = qc.run(Program(
        H(0),
        CNOT(0, 1),
        CNOT(1, 2),
        MEASURE(0, 0),
        MEASURE(1, 1),
        MEASURE(2, 2),
    ),
                        classical_addresses=[0, 1, 2],
                        trials=1000)

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15
Exemplo n.º 14
0
def test_measure_bitstrings(forest):
    device = NxDevice(nx.complete_graph(2))
    qc_pyqvm = QuantumComputer(
        name="testy!", qam=PyQVM(n_qubits=2), device=device, compiler=DummyCompiler()
    )
    qc_forest = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, gate_noise=[0.00] * 3),
        device=device,
        compiler=DummyCompiler(),
    )
    prog = Program(I(0), I(1))
    meas_qubits = [0, 1]
    sym_progs, flip_array = _symmetrization(prog, meas_qubits, symm_type=-1)
    results = _measure_bitstrings(qc_pyqvm, sym_progs, meas_qubits, num_shots=1)
    # test with pyQVM
    answer = [np.array([[0, 0]]), np.array([[0, 1]]), np.array([[1, 0]]), np.array([[1, 1]])]
    assert all([np.allclose(x, y) for x, y in zip(results, answer)])
    # test with regular QVM
    results = _measure_bitstrings(qc_forest, sym_progs, meas_qubits, num_shots=1)
    assert all([np.allclose(x, y) for x, y in zip(results, answer)])
Exemplo n.º 15
0
def get_test_qc(n_qubits):
    class BasicQVMCompiler(AbstractCompiler):
        def quil_to_native_quil(self, program: Program):
            return basic_compile(program)

        def native_quil_to_executable(self, nq_program: Program):
            return PyQuilExecutableResponse(
                program=nq_program.out(),
                attributes=_extract_attribute_dictionary_from_program(nq_program))

    try:
        qc = QuantumComputer(
            name='testing-qc',
            qam=QVM(connection=ForestConnection(), random_seed=52),
            device=NxDevice(nx.complete_graph(n_qubits)),
            compiler=BasicQVMCompiler(),
        )
        qc.run_and_measure(Program(I(0)), trials=1)
        return qc
    except (RequestException, TimeoutError) as e:
        return pytest.skip("This test requires a running local QVM: {}".format(e))
Exemplo n.º 16
0
def test_qpu_run():
    config = PyquilConfig()
    if config.qpu_url and config.qpu_compiler_url:
        g = nx.Graph()
        g.add_node(0)
        device = NxDevice(g)

        qc = QuantumComputer(
            name="pyQuil test QC",
            qam=QPU(endpoint=config.qpu_url, user="******"),
            device=device,
            compiler=QPUCompiler(endpoint=config.compiler_url, device=device),
        )
        bitstrings = qc.run_and_measure(program=Program(X(0)), trials=1000)
        assert bitstrings[0].shape == (1000, )
        assert np.mean(bitstrings[0]) > 0.8
        bitstrings = qc.run(qc.compile(Program(X(0))))
        assert bitstrings.shape == (0, 0)
    else:
        pytest.skip(
            "QPU or compiler-server not available; skipping QPU run test.")
Exemplo n.º 17
0
def test_run_pyqvm_noiseless():
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name='testy!',
        qam=PyQVM(n_qubits=3),
        device=device,
        compiler=DummyCompiler()
    )
    bitstrings = qc.run(
        Program(
            H(0),
            CNOT(0, 1),
            CNOT(1, 2),
            MEASURE(0, 0),
            MEASURE(1, 1),
            MEASURE(2, 2)).wrap_in_numshots_loop(1000)
    )

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert np.mean(parity) == 0
Exemplo n.º 18
0
def test_qc_expectation_on_qvm_that_requires_executable(forest):
    # regression test for https://github.com/rigetti/forest-tutorials/issues/2
    device = NxDevice(nx.complete_graph(2))
    qc = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, requires_executable=True),
        device=device,
        compiler=DummyCompiler(),
    )

    p = Program()
    theta = p.declare("theta", "REAL")
    p += RESET()
    p += RY(theta, 0)
    p.wrap_in_numshots_loop(10000)

    sx = ExperimentSetting(in_state=sZ(0), out_operator=sX(0))
    e = Experiment(settings=[sx], program=p)

    thetas = [-np.pi / 2, 0.0, np.pi / 2]
    results = []

    # Verify that multiple calls to qc.experiment with the same experiment backed by a QVM that
    # requires_exectutable does not raise an exception.
    for theta in thetas:
        results.append(qc.experiment(e, memory_map={"theta": [theta]}))

    assert np.isclose(results[0][0].expectation, -1.0, atol=0.01)
    assert np.isclose(results[0][0].std_err, 0)
    assert results[0][0].total_counts == 20000

    # bounds on atol and std_err here are a little loose to try and avoid test flakiness.
    assert np.isclose(results[1][0].expectation, 0.0, atol=0.1)
    assert results[1][0].std_err < 0.01
    assert results[1][0].total_counts == 20000

    assert np.isclose(results[2][0].expectation, 1.0, atol=0.01)
    assert np.isclose(results[2][0].std_err, 0)
    assert results[2][0].total_counts == 20000
Exemplo n.º 19
0
def test_run(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, gate_noise=[0.01] * 3),
        device=device,
        compiler=DummyCompiler(),
    )
    bitstrings = qc.run(
        Program(
            Declare("ro", "BIT", 3),
            H(0),
            CNOT(0, 1),
            CNOT(1, 2),
            MEASURE(0, MemoryReference("ro", 0)),
            MEASURE(1, MemoryReference("ro", 1)),
            MEASURE(2, MemoryReference("ro", 2)),
        ).wrap_in_numshots_loop(1000))

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15
Exemplo n.º 20
0
def test_set_initial_state():
    # That is test the assigned state matrix in ReferenceDensitySimulator is persistent between
    # rounds of run.
    rho1 = np.array([[0.0, 0.0], [0.0, 1.0]])

    # run prog
    prog = Program(I(0))
    ro = prog.declare("ro", "BIT", 1)
    prog += MEASURE(0, ro[0])

    # make a quantum computer object
    device = NxDevice(nx.complete_graph(1))
    qc_density = QuantumComputer(
        name="testy!",
        qam=PyQVM(n_qubits=1,
                  quantum_simulator_type=ReferenceDensitySimulator),
        device=device,
        compiler=DummyCompiler(),
    )

    qc_density.qam.wf_simulator.set_initial_state(rho1).reset()

    out = [qc_density.run(prog) for _ in range(0, 4)]
    ans = [np.array([[1]]), np.array([[1]]), np.array([[1]]), np.array([[1]])]
    assert all([np.allclose(x, y) for x, y in zip(out, ans)])

    # Run and measure style
    progRAM = Program(I(0))

    results = qc_density.run_and_measure(progRAM, trials=10)
    ans = {0: np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])}
    assert np.allclose(results[0], ans[0])

    # test reverting ReferenceDensitySimulator to the default state
    rho0 = np.array([[1.0, 0.0], [0.0, 0.0]])
    qc_density.qam.wf_simulator.set_initial_state(rho0).reset()
    assert np.allclose(qc_density.qam.wf_simulator.density, rho0)
    assert np.allclose(qc_density.qam.wf_simulator.initial_density, rho0)
Exemplo n.º 21
0
from pyquil.api._quantum_computer import _get_qvm_with_topology
from pyquil.device import NxDevice, gates_in_isa
from pyquil import Program, get_qc
from pyquil.gates import *


def make_circuit()-> Program:

    prog = Program()

    prog += X(1)
    prog += X(2)
    prog += CCNOT(1,2,0) # number=8
    # circuit end

    return prog

if __name__ == '__main__':


    #qubits = [0, 1, 2, 3, 4, 5, 6]  # qubits are numbered by octagon
    edges = [(0, 1), (1, 0), (2, 3), (3, 2)] # second octagon

    topo = nx.from_edgelist(edges)
    device = NxDevice(topology=topo)

    qc = _get_qvm_with_topology(name="line",topology=topo)

    print(qc.run_and_measure(make_circuit(),10))

    #pyquil seems should use this way to do the topology
Exemplo n.º 22
0
    def __init__(self,
                 clauses,
                 m=None,
                 steps=1,
                 grid_size=None,
                 tol=1e-5,
                 gate_noise=None,
                 verbose=False,
                 visualize=False):
        self.clauses = clauses
        self.m = m
        self.verbose = verbose
        self.visualize = visualize
        self.step_by_step_results = None
        self.optimization_history = None
        self.gate_noise = gate_noise
        if grid_size is None:
            self.grid_size = len(clauses) + len(qubits)
        else:
            self.grid_size = grid_size

        cost_operators, mapping = self.create_operators_from_clauses()
        self.mapping = mapping
        driver_operators = self.create_driver_operators()
        # minimizer_kwargs = {'method': 'BFGS',
        #                         'options': {'gtol': tol, 'disp': False}}

        # bounds = [(0, np.pi)]*steps + [(0, 2*np.pi)]*steps
        # minimizer_kwargs = {'method': 'L-BFGS-B',
        #                         'options': {'gtol': tol, 'disp': False},
        #                         'bounds': bounds}
        minimizer_kwargs = {
            'method': 'Nelder-Mead',
            'options': {
                'ftol': tol,
                'tol': tol,
                'disp': False
            }
        }

        if self.verbose:
            print_fun = print
        else:
            print_fun = pass_fun

        qubits = list(range(len(mapping)))

        if gate_noise:
            self.samples = int(1e3)
            pauli_channel = [gate_noise] * 3
        else:
            self.samples = None
            pauli_channel = None
        connection = ForestConnection()
        qvm = QVM(connection=connection, gate_noise=pauli_channel)
        topology = nx.complete_graph(len(qubits))
        device = NxDevice(topology=topology)
        qc = QuantumComputer(name="my_qvm",
                             qam=qvm,
                             device=device,
                             compiler=QVMCompiler(
                                 device=device,
                                 endpoint=connection.compiler_endpoint))

        vqe_option = {
            'disp': print_fun,
            'return_all': True,
            'samples': self.samples
        }

        self.qaoa_inst = QAOA(qc,
                              qubits,
                              steps=steps,
                              init_betas=None,
                              init_gammas=None,
                              cost_ham=cost_operators,
                              ref_ham=driver_operators,
                              minimizer=scipy.optimize.minimize,
                              minimizer_kwargs=minimizer_kwargs,
                              rand_seed=None,
                              vqe_options=vqe_option,
                              store_basis=True)

        self.ax = None
Exemplo n.º 23
0
import networkx as nx
from pyquil import Program
from pyquil.gates import X
from pyquil.device import NxDevice
from pyquil.api._qac import AbstractCompiler
from pyquil.api import QuantumComputer, QVM, ForestConnection
from matplotlib import pyplot as plt

topology = nx.from_edgelist([
    (10, 2),
    (10, 4),
    (10, 6),
    (10, 8),
])

device = NxDevice(topology)


class MyLazyCompiler(AbstractCompiler):
    def quil_to_native_quil(self, program, *, protoquil=None):
        return program

    def native_quil_to_executable(self, nq_program):
        return nq_program


my_qc = QuantumComputer(
    name='my-qvm',
    qam=QVM(connection=ForestConnection()),
    device=device,
    compiler=MyLazyCompiler(),
Exemplo n.º 24
0
def mock_qpu_compiler(request, m_endpoints, compiler: QVMCompiler):
    return QPUCompiler(
        quilc_endpoint=compiler.client.endpoint,
        qpu_compiler_endpoint=m_endpoints[0],
        device=NxDevice(nx.Graph([(0, 1)])),
    )
Exemplo n.º 25
0
def mock_compiler(request, m_endpoints):
    return QPUCompiler(endpoint=m_endpoints[0],
                       device=NxDevice(nx.Graph([(0, 1)])))
Exemplo n.º 26
0
def get_ion_device(num_qubits):
    return NxDevice(nx.complete_graph(num_qubits))
Exemplo n.º 27
0
def get_qc(name: str,
           *,
           as_qvm: bool = None,
           noisy: bool = None,
           connection: ForestConnection = None):
    """
    Get a quantum computer.

    A quantum computer is an object of type :py:class:`QuantumComputer` and can be backed
    either by a QVM simulator ("Quantum/Quil Virtual Machine") or a physical Rigetti QPU ("Quantum
    Processing Unit") made of superconducting qubits.

    You can choose the quantum computer to target through a combination of its name and optional
    flags. There are multiple ways to get the same quantum computer. The following are equivalent::

        >>> qc = get_qc("8Q-Agave-noisy-qvm")
        >>> qc = get_qc("8Q-Agave", as_qvm=True, noisy=True)

    and will construct a simulator of the 8q-agave chip with a noise model based on device
    characteristics. We also provide a means for constructing generic quantum simulators that
    are not related to a given piece of Rigetti hardware::

        >>> qc = get_qc("9q-generic-qvm")
        >>> qc = get_qc("9q-generic", as_qvm=True)

    Redundant flags are acceptable, but conflicting flags will raise an exception::

        >>> qc = get_qc("9q-generic-qvm") # qc is fully specified by its name
        >>> qc = get_qc("9q-generic-qvm", as_qvm=True) # redundant, but ok
        >>> qc = get_qc("9q-generic-qvm", as_qvm=False) # Error!

    Use :py:func:`list_quantum_computers` to retrieve a list of known qc names.

    This method is provided as a convenience to quickly construct and use QVM's and QPU's.
    Power users may wish to have more control over the specification of a quantum computer
    (e.g. custom noise models, bespoke topologies, etc.). This is possible by constructing
    a :py:class:`QuantumComputer` object by hand. Please refer to the documentation on
    :py:class:`QuantumComputer` for more information.

    :param name: The name of the desired quantum computer. This should correspond to a name
        returned by :py:func:`list_quantum_computers`. Names ending in "-qvm" will return
        a QVM. Names ending in "-noisy-qvm" will return a QVM with a noise model. Otherwise,
        we will return a QPU with the given name.
    :param as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If
        specified and set to ``True``, a QVM-backed quantum computer will be returned regardless
        of the name's suffix
    :param noisy: An optional flag to force inclusion of a noise model. If
        specified and set to ``True``, a quantum computer with a noise model will be returned
        regardless of the name's suffix. The noise model for QVM's based on a real QPU
        is an empirically parameterized model based on real device noise characteristics.
        The generic QVM noise model is simple T1 and T2 noise plus readout error. See
        :py:func:`decoherance_noise_with_asymmetric_ro`.
    :param connection: An optional :py:class:ForestConnection` object. If not specified,
        the default values for URL endpoints, ping time, and status time will be used. Your
        user id and API key will be read from ~/.pyquil_config. If you deign to change any
        of these parameters, pass your own :py:class:`ForestConnection` object.
    :return:
    """
    if connection is None:
        connection = ForestConnection()

    name, as_qvm, noisy = _parse_name(name, as_qvm, noisy)

    if name == '9q-generic':
        if not as_qvm:
            raise ValueError(
                "The device '9q-generic' is only available as a QVM")

        nineq_square = nx.convert_node_labels_to_integers(
            nx.grid_2d_graph(3, 3))
        nineq_device = NxDevice(topology=nineq_square)
        if noisy:
            noise_model = decoherance_noise_with_asymmetric_ro(
                nineq_device.get_isa())
        else:
            noise_model = None

        return QuantumComputer(name='9q-generic-qvm',
                               qam=QVM(connection=connection,
                                       noise_model=noise_model),
                               device=nineq_device)

    # At least based off a real device.
    device = get_devices(as_dict=True)[name]

    if not as_qvm:
        if noisy is not None and noisy:
            warnings.warn(
                "You have specified `noisy=True`, but you're getting a QPU. This flag "
                "is meant for controling noise models on QVMs.")
        return QuantumComputer(name=name,
                               qam=QPU(device_name=name,
                                       connection=connection),
                               device=device)

    if noisy:
        noise_model = device.noise_model
        name = "{name}-noisy-qvm".format(name=name)
    else:
        noise_model = None
        name = "{name}-qvm".format(name=name)

    return QuantumComputer(name=name,
                           qam=QVM(connection=connection,
                                   noise_model=noise_model),
                           device=device)