Ejemplo n.º 1
0
 def test_filter_config_callable(self, qe_token, qe_url):
     """Test filtering by lambda function on configuration properties"""
     IBMQ.enable_account(qe_token, qe_url)
     filtered_backends = IBMQ.backends(
         filters=lambda x: (not x.configuration().simulator and x.
                            configuration().n_qubits >= 5))
     self.assertTrue(filtered_backends)
Ejemplo n.º 2
0
    def test_filter_config_properties(self, qe_token, qe_url):
        """Test filtering by configuration properties"""
        n_qubits = 20 if self.using_ibmq_credentials else 5

        IBMQ.enable_account(qe_token, qe_url)
        filtered_backends = IBMQ.backends(n_qubits=n_qubits, local=False)
        self.assertTrue(filtered_backends)
Ejemplo n.º 3
0
    def test_retrieve_job_uses_appropriate_backend(self, qe_token, qe_url):
        """Test that retrieved jobs come from their appropriate backend."""
        IBMQ.enable_account(qe_token, qe_url)
        simulator_backend = IBMQ.get_backend('ibmq_qasm_simulator')
        backends = IBMQ.backends(simulator=False)
        real_backend = least_busy(backends)

        qobj_sim = compile(self._qc, simulator_backend)
        job_sim = simulator_backend.run(qobj_sim)

        qobj_real = compile(self._qc, real_backend)
        job_real = real_backend.run(qobj_real)

        # test a retrieved job's backend is the same as the queried backend
        self.assertEqual(simulator_backend.retrieve_job(job_sim.job_id()).backend().name(),
                         simulator_backend.name())
        self.assertEqual(real_backend.retrieve_job(job_real.job_id()).backend().name(),
                         real_backend.name())

        # test retrieve requests for jobs that exist on other backends throw errors
        with self.assertWarns(Warning) as context_manager:
            self.assertRaises(IBMQBackendError,
                              simulator_backend.retrieve_job, job_real.job_id())
        self.assertIn('belongs to', str(context_manager.warning))
        with self.assertWarns(Warning) as context_manager:
            self.assertRaises(IBMQBackendError,
                              real_backend.retrieve_job, job_sim.job_id())
        self.assertIn('belongs to', str(context_manager.warning))
    def test_run_device(self, qe_token, qe_url):
        """Test running in a real device."""
        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)
Ejemplo n.º 5
0
    def test_retrieve_job_error(self, qe_token, qe_url):
        """Test retrieving an invalid job."""
        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')
Ejemplo n.º 6
0
 def test_backend_monitor(self, qe_token, qe_url):
     """Test backend_monitor"""
     IBMQ.enable_account(qe_token, qe_url)
     for back in IBMQ.backends():
         if not back.configuration().simulator:
             backend = back
             break
     backend_monitor(backend)
Ejemplo n.º 7
0
    def test_running_job_properties(self, qe_token, qe_url):
        """Test fetching properties of a running job."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(IBMQ.backends(simulator=False))

        qobj = assemble(transpile(self._qc, backend=backend), backend=backend)
        job = backend.run(qobj)
        _ = job.properties()
 def test_remote_backend_properties(self, qe_token, qe_url):
     """Test backend properties."""
     IBMQ.enable_account(qe_token, qe_url)
     remotes = IBMQ.backends(simulator=False)
     for backend in remotes:
         properties = backend.properties()
         if backend.configuration().simulator:
             self.assertEqual(properties, None)
Ejemplo n.º 9
0
    def test_filter_status_dict(self, qe_token, qe_url):
        """Test filtering by dictionary of mixed status/configuration properties"""
        IBMQ.enable_account(qe_token, qe_url)
        filtered_backends = IBMQ.backends(
            operational=True,  # from status
            local=False,
            simulator=True)  # from configuration

        self.assertTrue(filtered_backends)
Ejemplo n.º 10
0
    def _get_backends(self, qe_token, qe_url):
        sim_backend = BasicAer.get_backend('qasm_simulator')
        try:
            IBMQ.enable_account(qe_token, qe_url)
            real_backends = IBMQ.backends(simulator=False)
            real_backend = least_busy(real_backends)
        except QiskitError:
            real_backend = None

        return sim_backend, real_backend
Ejemplo n.º 11
0
    def test_get_jobs_filter_job_status(self, qe_token, qe_url):
        """Test retrieving jobs from a backend filtered by status."""
        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 job in job_list:
            self.assertTrue(job.status() is JobStatus.DONE)
Ejemplo n.º 12
0
    def test_get_jobs_filter_date(self, qe_token, qe_url):
        """Test retrieving jobs from a backend filtered by date."""
        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')
Ejemplo n.º 13
0
    def test_get_jobs_from_backend(self, qe_token, qe_url):
        """Test retrieving jobs from a backend."""
        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)
Ejemplo n.º 14
0
    def test_compile_remote(self, qe_token, qe_url):
        """Test Compiler remote."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(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)

        circuits = transpile(qc, backend)
        self.assertIsInstance(circuits, QuantumCircuit)
    def test_websockets_device(self, qe_token, qe_url):
        """Test checking status of a job via websockets for a device."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(IBMQ.backends(simulator=False))

        qc = transpile(self._qc1, backend=backend)
        qobj = assemble(qc, backend=backend)

        job = backend.run(qobj)
        # Manually disable the non-websocket pooling.
        job._wait_for_final_status = None
        result = job.result()

        self.assertEqual(result.status, 'COMPLETED')
Ejemplo n.º 16
0
    def test_run_async_device(self, qe_token, qe_url):
        """Test running in a real device asynchronously."""
        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 = assemble(transpile(qc, backend=backend), backend=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.success 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))))
Ejemplo n.º 17
0
    def test_get_jobs_filter_job_status(self, qe_token, qe_url):
        """Test retrieving jobs from a backend filtered by status."""
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        with warnings.catch_warnings():
            # Disable warnings from pre-qobj jobs.
            warnings.filterwarnings('ignore',
                                    category=DeprecationWarning,
                                    module='qiskit.providers.ibmq.ibmqbackend')
            job_list = backend.jobs(limit=5, skip=0, status=JobStatus.DONE)

        for job in job_list:
            self.assertTrue(job.status() is JobStatus.DONE)
Ejemplo n.º 18
0
    def test_run_device(self, qe_token, qe_url):
        """Test running in a real device."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(IBMQ.backends(simulator=False))

        qobj = compile(self._qc, backend)
        shots = qobj.config.shots
        job = backend.run(qobj)
        while not job.status() is JobStatus.DONE:
            time.sleep(4)

        result = job.result()
        counts_qx = result.get_counts(0)
        counts_ex = {'00': shots/2, '11': shots/2}
        self.assertDictAlmostEqual(counts_qx, counts_ex, shots*0.1)

        # Test fetching the job properties, as this is a real backend and is
        # guaranteed to have them.
        _ = job.properties()
Ejemplo n.º 19
0
def get_unique_backends():
    """Gets the unique backends that are available.

    Returns:
        list: Unique available backends.

    Raises:
        QiskitError: No backends available.
    """
    backends = IBMQ.backends()
    unique_hardware_backends = []
    unique_names = []
    for back in backends:
        if back.name(
        ) not in unique_names and not back.configuration().simulator:
            unique_hardware_backends.append(back)
            unique_names.append(back.name())
    if not unique_hardware_backends:
        raise QiskitError('No backends available.')
    return unique_hardware_backends
    def test_qobj_headers_in_result_devices(self, qe_token, qe_url):
        """Test that the qobj headers are passed onto the results for devices."""
        IBMQ.enable_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)

        custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}}

        for backend in backends:
            with self.subTest(backend=backend):
                qobj = compile(self.qc1, backend)

                # Update the Qobj header.
                qobj.header = QobjHeader.from_dict(custom_qobj_header)
                # Update the Qobj.experiment header.
                qobj.experiments[0].header.some_field = 'extra info'

                result = backend.run(qobj).result()
                self.assertEqual(result.header.to_dict(), custom_qobj_header)
                self.assertEqual(result.results[0].header.some_field,
                                 'extra info')
Ejemplo n.º 21
0
def _build_job_history(tabs, backend):

    backends = IBMQ.backends(backend.name())
    past_year_date = datetime.datetime.now() - datetime.timedelta(days=365)
    date_filter = {'creationDate': {'gt': past_year_date.isoformat()}}
    jobs = []
    for back in backends:
        jobs.extend(back.jobs(limit=None, db_filter=date_filter))

    with tabs.children[1]:
        month_plot = plot_job_history(jobs, interval='month')
        display(month_plot)
        plt.close(month_plot)

    with tabs.children[0]:
        year_plot = plot_job_history(jobs, interval='year')
        display(year_plot)
        plt.close(year_plot)

    with tabs.children[2]:
        week_plot = plot_job_history(jobs, interval='week')
        display(week_plot)
        plt.close(week_plot)
 def test_remote_backend_status(self, qe_token, qe_url):
     """Test backend_status."""
     IBMQ.enable_account(qe_token, qe_url)
     for backend in IBMQ.backends():
         _ = backend.status()
Ejemplo n.º 23
0
print(qft5)

###############################################################
# 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 = BasicAer.get_backend('qasm_simulator')
job = execute([qft3, qft4, qft5], sim_backend, shots=1024)
result = job.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.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))

 def get_backends(self, qe_token=None, qe_url=None):
     """Return all available remote backends."""
     IBMQ.enable_account(qe_token, qe_url)
     return IBMQ.backends()
Ejemplo n.º 25
0
 def test_remote_backend_defaults(self, qe_token, qe_url):
     """Test backend pulse defaults."""
     IBMQ.enable_account(qe_token, qe_url)
     remotes = IBMQ.backends(simulator=False)
     for backend in remotes:
         _ = backend.defaults()
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
print(qft5)

###############################################################
# 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 = BasicAer.get_backend('qasm_simulator')
job = execute([qft3, qft4, qft5], sim_backend, shots=1024)
result = job.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.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
 def test_remote_backends_exist(self, qe_token, qe_url):
     """Test if there are remote backends."""
     IBMQ.enable_account(qe_token, qe_url)
     remotes = IBMQ.backends()
     self.assertTrue(len(remotes) > 0)
 def test_remote_backend_configuration(self, qe_token, qe_url):
     """Test backend configuration."""
     IBMQ.enable_account(qe_token, qe_url)
     remotes = IBMQ.backends()
     for backend in remotes:
         _ = backend.configuration()
 def test_remote_backends_exist_simulator(self, qe_token, qe_url):
     """Test if there are remote backends that are simulators."""
     IBMQ.enable_account(qe_token, qe_url)
     remotes = IBMQ.backends(simulator=True)
     self.assertTrue(remotes)