예제 #1
0
def least_busy(names):
    """
    Return the least busy available backend for those that
    have a `pending_jobs` in their `status`. Backends such as
    local backends that do not have this are not considered.

    Args:
        names (list[str]): backend names to choose from
                    (e.g. output of ``available_backends()``)

    Returns:
        str: the name of the least busy backend

    Raises:
        QISKitError: if passing a list of backend names that is
            either empty or none have attribute ``pending_jobs``
    .. deprecated:: 0.6+
        After 0.6, this function is deprecated. Please use the methods in
        `qiskit.IBMQ` instead
        (`backends()`).
    """
    backends = [get_backend(name) for name in names]
    warnings.warn(
        'the global least_busy() will be deprecated after 0.6. Please '
        'use least_busy() imported from qiskit.backends.ibmq',
        DeprecationWarning)
    return ibmq.least_busy(backends).name()
예제 #2
0
def get_appropriate_backend(n, real, online, backend_name):
    # Online, real or simuator?
    if (not online):
        global Aer
        from qiskit import Aer
        max_credits = 10
        shots = 4098
        print("Local simulator backend")
        backend = Aer.get_backend('qasm_simulator')
    # list of online devices: ibmq_qasm_simulator, ibmqx2, ibmqx4, ibmqx5, ibmq_16_melbourne
    else:
        global IBMQ
        from qiskit import IBMQ
        print("Online {0} backend".format("real" if real else "simulator"))
        max_credits = 3
        shots = 4098
        import Qconfig
        IBMQ.load_accounts()
        if (backend_name is not None):
            backend = IBMQ.get_backend(backend_name)
        else:
            large_enough_devices = IBMQ.backends(
                filters=lambda x: x.configuration()['n_qubits'] >= n and x.configuration()[
                    'simulator'] == (not real)
            )
            backend = least_busy(large_enough_devices)

    print("Backend name is {0}; max_credits = {1}, shots = {2}".format(
        backend, max_credits, shots))
    return backend, max_credits, shots
예제 #3
0
def get_backend(local=False):
    if local:
        return Aer.get_backend('qasm_simulator_py')
    IBMQ.load_accounts()
    available_backends = IBMQ.backends(operational=True, simulator=False)
    backend = least_busy(available_backends)
    return backend
예제 #4
0
    def test_run_device(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)

        self.log.info('devices: %s', [b.name() for b in backends])
        backend = least_busy(backends)
        self.log.info('using backend: %s', backend.name())
        qobj = compile(self._qc, backend)
        shots = qobj.config.shots
        job = backend.run(qobj)
        while not job.status() is JobStatus.DONE:
            self.log.info(job.status())
            time.sleep(4)
        self.log.info(job.status)
        result = job.result()
        counts_qx = result.get_counts(0)
        counts_ex = {'00': shots / 2, '11': shots / 2}
        states = counts_qx.keys() | counts_ex.keys()
        # contingency table
        ctable = numpy.array([[counts_qx.get(key, 0) for key in states],
                              [counts_ex.get(key, 0) for key in states]])
        self.log.info('states: %s', str(states))
        self.log.info('ctable: %s', str(ctable))
        contingency = chi2_contingency(ctable)
        self.log.info('chi2_contingency: %s', str(contingency))
        self.assertDictAlmostEqual(counts_qx, counts_ex, shots * 0.1)
예제 #5
0
def online_real(qc):
    from qiskit import IBMQ
    from qiskit.backends.ibmq import least_busy
    IBMQ.load_accounts()
    large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()[
        'n_qubits'] > 2 and not x.configuration()['simulator'])

    backend = least_busy(large_enough_devices)
    return backend
예제 #6
0
    def test_get_jobs_filter_job_status(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        job_list = backend.jobs(limit=5, skip=0, status=JobStatus.DONE)
        self.log.info('found %s matching jobs', len(job_list))
        for i, job in enumerate(job_list):
            self.log.info('match #%d: %s', i, job.result().status)
            self.assertTrue(job.status() is JobStatus.DONE)
예제 #7
0
    def _get_backends(self, qe_token, qe_url):
        sim_backend = qiskit.Aer.get_backend('qasm_simulator_py')
        try:
            qiskit.IBMQ.enable_account(qe_token, qe_url)
            real_backends = qiskit.IBMQ.backends(simulator=False)
            real_backend = least_busy(real_backends)
        except Exception:
            real_backend = None

        return sim_backend, real_backend
예제 #8
0
    def test_get_jobs_filter_date(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        my_filter = {'creationDate': {'lt': '2017-01-01T00:00:00.00'}}
        job_list = backend.jobs(limit=5, db_filter=my_filter)
        self.log.info('found %s matching jobs', len(job_list))
        for i, job in enumerate(job_list):
            self.log.info('match #%d: %s', i, job.creation_date)
            self.assertTrue(job.creation_date < '2017-01-01T00:00:00.00')
예제 #9
0
    def test_get_jobs_from_backend(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(IBMQ.backends())

        start_time = time.time()
        job_list = backend.jobs(limit=5, skip=0)
        self.log.info('time to get jobs: %0.3f s', time.time() - start_time)
        self.log.info('found %s jobs on backend %s', len(job_list), backend.name())
        for job in job_list:
            self.log.info('status: %s', job.status())
            self.assertTrue(isinstance(job.job_id(), str))
        self.log.info('time to get job statuses: %0.3f s', time.time() - start_time)
예제 #10
0
    def test_run_async_device(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        self.log.info('submitting to backend %s', backend.name())
        num_qubits = 5
        qr = QuantumRegister(num_qubits, 'qr')
        cr = ClassicalRegister(num_qubits, 'cr')
        qc = QuantumCircuit(qr, cr)
        for i in range(num_qubits - 1):
            qc.cx(qr[i], qr[i + 1])
        qc.measure(qr, cr)
        qobj = transpiler.compile(qc, backend)
        num_jobs = 3
        job_array = [backend.run(qobj) for _ in range(num_jobs)]
        time.sleep(3)  # give time for jobs to start (better way?)
        job_status = [job.status() for job in job_array]
        num_init = sum(
            [status is JobStatus.INITIALIZING for status in job_status])
        num_queued = sum([status is JobStatus.QUEUED for status in job_status])
        num_running = sum(
            [status is JobStatus.RUNNING for status in job_status])
        num_done = sum([status is JobStatus.DONE for status in job_status])
        num_error = sum([status is JobStatus.ERROR for status in job_status])
        self.log.info('number of currently initializing jobs: %d/%d', num_init,
                      num_jobs)
        self.log.info('number of currently queued jobs: %d/%d', num_queued,
                      num_jobs)
        self.log.info('number of currently running jobs: %d/%d', num_running,
                      num_jobs)
        self.log.info('number of currently done jobs: %d/%d', num_done,
                      num_jobs)
        self.log.info('number of errored jobs: %d/%d', num_error, num_jobs)
        self.assertTrue(num_jobs - num_error - num_done > 0)

        # Wait for all the results.
        result_array = [job.result() for job in job_array]

        # Ensure all jobs have finished.
        self.assertTrue(
            all([job.status() is JobStatus.DONE for job in job_array]))
        self.assertTrue(
            all([
                result.get_status() == 'COMPLETED' for result in result_array
            ]))

        # Ensure job ids are unique.
        job_ids = [job.job_id() for job in job_array]
        self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
예제 #11
0
파일: devices.py 프로젝트: urmasrahu/ibmq
def GetIBMQDevice(useSimulator):
    if not ibmq_login.login():
        return

    print("Getting the list of IBMQ backends (simulator=",
          useSimulator,
          ")...",
          sep="")
    backends = IBMQ.backends(simulator=useSimulator)
    print("IBMQ backends:", backends)

    print("Obtaining the least busy device...")
    least_busy_device = least_busy(backends)
    print("Least busy device:", least_busy_device)

    return least_busy_device
예제 #12
0
    def test_compile_remote(self, qe_token, qe_url):
        """Test Compiler remote.

        If all correct some should exists.
        """
        qiskit.IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(qiskit.IBMQ.backends())

        qubit_reg = QuantumRegister(2, name='q')
        clbit_reg = ClassicalRegister(2, name='c')
        qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        dags = transpiler.transpile(qc, backend)
        self.assertIsInstance(dags[0], DAGCircuit)
예제 #13
0
def least_busy(names):
    """
    Return the least busy available backend for those that
    have a `pending_jobs` in their `status`. Backends such as
    local backends that do not have this are not considered.

    Args:
        names (list[str]): backend names to choose from
                    (e.g. output of ``available_backends()``)

    Returns:
        str: the name of the least busy backend

    Raises:
        QISKitError: if passing a list of backend names that is
            either empty or none have attribute ``pending_jobs``
    """
    backends = [get_backend(name) for name in names]
    return ibmq.least_busy(backends).name()
예제 #14
0
    def test_compile_remote(self, qe_token, qe_url):
        """Test Compiler remote.

        If all correct some should exists.
        """
        qiskit.IBMQ.use_account(qe_token, qe_url)
        backend = least_busy(qiskit.IBMQ.backends())

        qubit_reg = QuantumRegister(2, name='q')
        clbit_reg = ClassicalRegister(2, name='c')
        qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        qobj = transpiler.compile(qc, backend)

        # FIXME should validate the Qobj when defined
        self.assertIsInstance(qobj, Qobj)
예제 #15
0
    # Compile and run the Quantum circuit on a simulator backend
    job_sim = execute(qc, backend_sim)
    result_sim = job_sim.result()

    # Show the results
    print("simulation: ", result_sim)
    print(result_sim.get_counts(qc))

    # see a list of available remote backends
    ibmq_backends = IBMQ.backends()

    print("Remote backends: ", ibmq_backends)
    # Compile and run the Quantum Program on a real device backend
    try:
        least_busy_device = least_busy(IBMQ.backends(simulator=False))
        print("Running on current least busy device: ", least_busy_device)

        #running the job
        job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10)
        result_exp = job_exp.result()

        # Show the results
        print("experiment: ", result_exp)
        print(result_exp.get_counts(qc))
    except:
        print("All devices are currently unavailable.")

except QiskitError as ex:
    print('There was an error in the circuit!. Error = {}'.format(ex))
예제 #16
0
cr = ClassicalRegister(12)
qc = QuantumCircuit(qr, cr)

qc.h(qr)
qc.measure(qr, cr)
# circuit_drawer(qc, filename="imgs/test_14_qubis.png")

if (len(sys.argv) > 1 and sys.argv[1] == 'c'):  # c stands for cloud
    IBMQ.load_accounts()
    print("Account loaded")
    if (sys.argv[2] == 'r'):  # r stands for real
        large_enough_devices = IBMQ.backends(
            filters=
            lambda x: x.configuration()['n_qubits'] >= 14 and not x.configuration()['simulator']
        )
        backend = least_busy(large_enough_devices)
        shots = 1024
        mx = 3
    elif (sys.argv[2] == 's'):  # shoud be a s for simulator
        large_enough_devices = IBMQ.backends(
            filters=
            lambda x: x.configuration()['n_qubits'] >= 14 and x.configuration()['simulator']
        )
        backend = least_busy(large_enough_devices)
        shots = 8192
        mx = 10
    else:
        exit("s/r")
else:
    print("Local simulator started")
    print(Aer.backends())
예제 #17
0
        state = key
    print("The Quantum 8-ball says:")
    if state == '000':
        print('It is certain.')
    elif state == '001':
        print('Without a doubt.')
    elif state == '010':
        print('Yes - deinitely.')
    elif state == '011':
        print('Most likely.')
    elif state == '100':
        print("Don't count on it.")
    elif state == '101':
        print('My reply is no.')
    elif state == '110':
        print('Very doubtful.')
    else:
        print('Concentrate and ask again.')


# Execute the job on the simulator.
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1)
result = job.result().get_counts(qc)
answer(result)

# Execute the program on a real quantum computer.
backend = least_busy(IBMQ.backends(simulator=False))
print("Running on", backend.name())
job = execute(qc, backend, shots=1)
result = job.result().get_counts(qc)
answer(result)
예제 #18
0
###############################################################
# Set up the API and execute the program.
###############################################################
try:
    IBMQ.load_accounts()
except:
    print("""WARNING: There's no connection with the API for remote backends.
             Have you initialized a file with your personal token?
             For now, there's only access to local simulator backends...""")

print('Qasm simulator')
sim_backend = Aer.get_backend('qasm_simulator')
job = execute([qft3, qft4, qft5], sim_backend, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))

# Second version: real device
least_busy_device = least_busy(
    IBMQ.backends(simulator=False,
                  filters=lambda x: x.configuration()['n_qubits'] > 4))
print("Running on current least busy device: ", least_busy_device)
job = execute([qft3, qft4, qft5], least_busy_device, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
예제 #19
0
 def test_filter_least_busy(self, qe_token, qe_url):
     """Test filtering by least busy function"""
     IBMQ.enable_account(qe_token, qe_url)
     backends = IBMQ.backends()
     filtered_backends = least_busy(backends)
     self.assertTrue(filtered_backends)
예제 #20
0
    def test_retrieve_job_error(self, qe_token, qe_url):
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        self.assertRaises(IBMQBackendError, backend.retrieve_job, 'BAD_JOB_ID')
예제 #21
0
import Qconfig
# print(Qconfig.APItoken, Qconfig.config['url'])

import getpass
import time
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import available_backends, execute, register
from qiskit.backends.ibmq import least_busy

# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer

# APItoken = getpass.getpass('Please input your token and hit enter: ')
# qx_config = {
#     "APItoken": APItoken,
#     "url": "https://quantumexperience.ng.bluemix.net/api"}

try:
    # qx_config['APItoken'], qx_config['url']
    register(Qconfig.APItoken, Qconfig.config['url'])

    print('\nYou have access to great power!')
    print(available_backends({'local': False, 'simulator': False}))
except:
    print('Something went wrong.\nDid you enter a correct token?')

backend = least_busy(available_backends({'simulator': False, 'local': False}))
print("The least busy backend is " + backend)

예제 #22
0
cr = ClassicalRegister(1)

circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.measure(qr, cr)
circuit_drawer(circuit, filename="imgs/" + id_string + ".png")

shots = 4096
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circuit, shots=shots, backend=backend_sim)
result_sim = job_sim.result()
# Show the results
print("simulation: ", result_sim)
print(result_sim.get_counts(circuit))

IBMQ.load_accounts()
large_enough_devices = IBMQ.backends(
    filters=
    lambda x: x.configuration()['n_qubits'] > 1 and not x.configuration()['simulator']
)
backend_real = least_busy(large_enough_devices)
print("The best backend is " + backend_real.name())

max_credits = 3
job_real = execute(
    circuit, backend=backend_real, shots=shots, max_credits=max_credits)
result_real = (job_real.result())
print("real: ", result_real)
print(result_real.get_counts(circuit))