Beispiel #1
0
    def test_online_qasm_simulator_two_registers(self, qe_token, qe_url):
        """Test online_qasm_simulator_two_registers.

        If all correct should return correct counts.
        """
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qr1 = QuantumRegister(2)
        cr1 = ClassicalRegister(2)
        qr2 = QuantumRegister(2)
        cr2 = ClassicalRegister(2)
        qcr1 = QuantumCircuit(qr1, qr2, cr1, cr2)
        qcr2 = QuantumCircuit(qr1, qr2, cr1, cr2)
        qcr1.x(qr1[0])
        qcr2.x(qr2[1])
        qcr1.measure(qr1[0], cr1[0])
        qcr1.measure(qr1[1], cr1[1])
        qcr1.measure(qr2[0], cr2[0])
        qcr1.measure(qr2[1], cr2[1])
        qcr2.measure(qr1[0], cr1[0])
        qcr2.measure(qr1[1], cr1[1])
        qcr2.measure(qr2[0], cr2[0])
        qcr2.measure(qr2[1], cr2[1])
        shots = 1024
        qobj = transpiler.compile([qcr1, qcr2], backend, seed=8458, shots=shots)
        job = backend.run(qobj)
        result = job.result()
        result1 = result.get_counts(qcr1)
        result2 = result.get_counts(qcr2)
        self.assertEqual(result1, {'00 01': 1024})
        self.assertEqual(result2, {'10 00': 1024})
    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.use_account(qe_token, qe_url)
        filtered_backends = IBMQ.backends(n_qubits=n_qubits, local=False)
        self.assertTrue(filtered_backends)
Beispiel #3
0
    def test_get_backend_name(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = transpiler.compile(self._qc, backend)
        job = backend.run(qobj)
        self.assertTrue(job.backend_name() == backend.name())
Beispiel #4
0
    def test_execute_several_circuits_simulator_online(self, qe_token, qe_url):
        """Test execute_several_circuits_simulator_online.

        If all correct should return correct counts.
        """
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qr = QuantumRegister(2)
        cr = ClassicalRegister(2)
        qcr1 = QuantumCircuit(qr, cr)
        qcr2 = QuantumCircuit(qr, cr)
        qcr1.h(qr)
        qcr2.h(qr[0])
        qcr2.cx(qr[0], qr[1])
        qcr1.measure(qr[0], cr[0])
        qcr1.measure(qr[1], cr[1])
        qcr2.measure(qr[0], cr[0])
        qcr2.measure(qr[1], cr[1])
        shots = 1024
        qobj = transpiler.compile([qcr1, qcr2], backend, seed=73846087, shots=shots)
        job = backend.run(qobj)
        result = job.result()
        counts1 = result.get_counts(qcr1)
        counts2 = result.get_counts(qcr2)
        target1 = {'00': shots / 4, '01': shots / 4,
                   '10': shots / 4, '11': shots / 4}
        target2 = {'00': shots / 2, '11': shots / 2}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts1, target1, threshold)
        self.assertDictAlmostEqual(counts2, target2, threshold)
Beispiel #5
0
    def test_run_device(self, qe_token, qe_url):
        IBMQ.use_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 = transpiler.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(result.get_names()[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)
Beispiel #6
0
    def test_get_jobs_filter_counts(self, qe_token, qe_url):
        # TODO: consider generalizing backend name
        # TODO: this tests depends on the previous executions of the user
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        my_filter = {
            'backend.name': 'ibmq_qasm_simulator',
            'shots': 1024,
            'qasms.result.data.counts.00': {
                'lt': 500
            }
        }
        self.log.info('searching for at most 5 jobs with 1024 shots, a count '
                      'for "00" of < 500, on the ibmq_qasm_simulator backend')
        job_list = backend.jobs(limit=5, skip=0, 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', i)
            result = job.result()
            self.assertTrue(
                any(cresult.data['counts']['00'] < 500
                    for cresult in result.results.values()))
            for circuit_name in result.get_names():
                self.log.info('\tcircuit_name: %s', circuit_name)
                if circuit_name:
                    counts = result.get_counts(circuit_name)
                    self.log.info('\t%s', str(counts))
 def test_filter_config_callable(self, qe_token, qe_url):
     """Test filtering by lambda function on configuration properties"""
     IBMQ.use_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)
Beispiel #8
0
    def test_job_id(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = transpiler.compile(self._qc, backend)
        job = backend.run(qobj)
        self.log.info('job_id: %s', job.id())
        self.assertTrue(job.id() is not None)
Beispiel #9
0
    def test_remote_backends_exist_simulator(self, qe_token, qe_url):
        """Test if there are remote backends that are simulators.

        If all correct some should exists.
        """
        IBMQ.use_account(qe_token, qe_url)
        remotes = IBMQ.backends(simulator=True)
        self.assertTrue(remotes)
Beispiel #10
0
    def test_remote_backends_exist(self, qe_token, qe_url):
        """Test if there are remote backends.

        If all correct some should exists.
        """
        IBMQ.use_account(qe_token, qe_url)
        remotes = IBMQ.backends()
        self.assertTrue(len(remotes) > 0)
Beispiel #11
0
    def test_double_submit_fails(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = transpiler.compile(self._qc, backend)
        # backend.run() will automatically call job.submit()
        job = backend.run(qobj)
        with self.assertRaises(JobError):
            job.submit()
    def test_filter_status_dict(self, qe_token, qe_url):
        """Test filtering by dictionary of mixed status/configuration properties"""
        IBMQ.use_account(qe_token, qe_url)
        filtered_backends = IBMQ.backends(
            operational=True,  # from status
            local=False,
            simulator=True)  # from configuration

        self.assertTrue(filtered_backends)
Beispiel #13
0
    def test_get_jobs_filter_job_status(self, qe_token, qe_url):
        IBMQ.use_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)
Beispiel #14
0
    def test_retrieve_job(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = transpiler.compile(self._qc, backend)
        job = backend.run(qobj)
        rjob = backend.retrieve_job(job.id())
        self.assertTrue(job.id() == rjob.id())
        self.assertTrue(
            job.result().get_counts() == rjob.result().get_counts())
Beispiel #15
0
    def test_get_jobs_filter_date(self, qe_token, qe_url):
        IBMQ.use_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')
Beispiel #16
0
    def test_run_async_simulator(self, qe_token, qe_url):
        IBMQJob._executor = futures.ThreadPoolExecutor(max_workers=2)

        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        self.log.info('submitting to backend %s', backend.name())
        num_qubits = 16
        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] * 10, backend)
        num_jobs = 5
        job_array = [backend.run(qobj) for _ in range(num_jobs)]
        found_async_jobs = False
        timeout = 30
        start_time = time.time()
        while not found_async_jobs:
            check = sum(
                [job.status() is JobStatus.RUNNING for job in job_array])
            if check >= 2:
                self.log.info('found %d simultaneous jobs', check)
                break
            if all([job.status() is JobStatus.DONE for job in job_array]):
                # done too soon? don't generate error
                self.log.warning('all jobs completed before simultaneous jobs '
                                 'could be detected')
                break
            for job in job_array:
                self.log.info('%s %s %s %s', job.status(),
                              job.status() is JobStatus.RUNNING, check,
                              job.id())
            self.log.info('-' * 20 + ' ' + str(time.time() - start_time))
            if time.time() - start_time > timeout:
                raise TimeoutError('failed to see multiple running jobs after '
                                   '{0} s'.format(timeout))
            time.sleep(0.2)

        result_array = [job.result() for job in job_array]
        self.log.info('got back all job results')
        # 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.id() for job in job_array]
        self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
Beispiel #17
0
    def test_cancel(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend_name = ('ibmq_20_tokyo'
                        if self.using_ibmq_credentials else 'ibmqx4')
        backend = IBMQ.get_backend(backend_name)

        qobj = transpiler.compile(self._qc, backend)
        job = backend.run(qobj)
        self.wait_for_initialization(job, timeout=5)
        can_cancel = job.cancel()
        self.assertTrue(can_cancel)
        self.assertTrue(job.status() is JobStatus.CANCELLED)
Beispiel #18
0
    def setUp(self):
        super().setUp()
        self._testing_device = os.getenv('IBMQ_QOBJ_DEVICE', None)
        self._qe_token = os.getenv('IBMQ_TOKEN', None)
        self._qe_url = os.getenv('IBMQ_QOBJ_URL')
        if not self._testing_device or not self._qe_token or not self._qe_url:
            self.skipTest('No credentials or testing device available for '
                          'testing Qobj capabilities.')

        IBMQ.use_account(self._qe_token, self._qe_url)
        self._backend = IBMQ.get_backend(self._testing_device)

        self._qc = _bell_circuit()
Beispiel #19
0
    def test_run_async_device(self, qe_token, qe_url):
        IBMQ.use_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.id() for job in job_array]
        self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
Beispiel #20
0
    def test_get_jobs_from_backend(self, qe_token, qe_url):
        IBMQ.use_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.id(), str))
        self.log.info('time to get job statuses: %0.3f s',
                      time.time() - start_time)
Beispiel #21
0
    def setUp(self):
        super().setUp()
        self._testing_device = os.getenv('IBMQ_QOBJ_DEVICE', None)
        self._qe_token = os.getenv('IBMQ_TOKEN', None)
        self._qe_url = os.getenv('IBMQ_QOBJ_URL')

        if not self._testing_device or not self._qe_token or not self._qe_url:
            self.skipTest("No credentials or testing device available for "
                          "testing Qobj capabilities.")

        IBMQ.use_account(self._qe_token, self._qe_url)
        self._local_backend = Aer.get_backend('local_qasm_simulator')
        self._remote_backend = IBMQ.get_backend(self._testing_device)
        self.log.info('Remote backend: %s', self._remote_backend.name())
        self.log.info('Local backend: %s', self._local_backend.name())
Beispiel #22
0
    def test_remote_backend_configuration(self, qe_token, qe_url):
        """Test backend configuration.

        If all correct should pass the validation.
        """
        IBMQ.use_account(qe_token, qe_url)
        remotes = IBMQ.backends(simulator=False)
        for backend in remotes:
            configuration = backend.configuration()
            schema_path = self._get_resource_path(
                'deprecated/backends/backend_configuration_schema_old_py.json',
                path=Path.SCHEMAS)
            with open(schema_path, 'r') as schema_file:
                schema = json.load(schema_file)
            jsonschema.validate(configuration, schema)
Beispiel #23
0
    def test_remote_backend_properties(self, qe_token, qe_url):
        """Test backend properties.

        If all correct should pass the validation.
        """
        IBMQ.use_account(qe_token, qe_url)
        remotes = IBMQ.backends(simulator=False)
        for backend in remotes:
            self.log.info(backend.name())
            properties = backend.properties()
            # FIXME test against schema and decide what properties
            # is for a simulator
            if backend.configuration()['simulator']:
                self.assertEqual(len(properties), 0)
            else:
                self.assertTrue(
                    all(key in properties
                        for key in ('last_update_date', 'qubits', 'backend')))
    def test_aliases(self, qe_token, qe_url):
        """Test that display names of devices map the same backends as the
        regular names."""
        IBMQ.use_account(qe_token, qe_url)
        aliased_names = IBMQ.aliased_backend_names()

        for display_name, backend_name in aliased_names.items():
            with self.subTest(display_name=display_name,
                              backend_name=backend_name):
                try:
                    backend_by_name = IBMQ.get_backend(backend_name)
                except KeyError:
                    # The real name of the backend might not exist
                    pass
                else:
                    backend_by_display_name = IBMQ.get_backend(display_name)
                    self.assertEqual(backend_by_name, backend_by_display_name)
                    self.assertEqual(backend_by_display_name.name(),
                                     backend_name)
Beispiel #25
0
    def test_remote_backend_status(self, qe_token, qe_url):
        """Test backend_status.

        If all correct should pass the validation.
        """
        # FIXME: reintroduce in 0.6
        self.skipTest('Skipping due to available vs operational')

        IBMQ.use_account(qe_token, qe_url)
        remotes = IBMQ.backends()
        remotes = remove_backends_from_list(remotes)
        for backend in remotes:
            self.log.info(backend.status())
            status = backend.status()
            schema_path = self._get_resource_path(
                'deprecated/backends/backend_status_schema_py.json',
                path=Path.SCHEMAS)
            with open(schema_path, 'r') as schema_file:
                schema = json.load(schema_file)
            jsonschema.validate(status, schema)
Beispiel #26
0
    def test_execute_one_circuit_simulator_online(self, qe_token, qe_url):
        """Test execute_one_circuit_simulator_online.

        If all correct should return correct counts.
        """
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qr = QuantumRegister(1)
        cr = ClassicalRegister(1)
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        qobj = transpiler.compile(qc, backend, seed=73846087)
        shots = qobj.config.shots
        job = backend.run(qobj)
        result = job.result()
        counts = result.get_counts(qc)
        target = {'0': shots / 2, '1': shots / 2}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)
Beispiel #27
0
    def test_run_simulator(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr, name='hadamard')
        qc.h(qr)
        qc.measure(qr, cr)
        qobj = transpiler.compile([self._qc, qc], backend)
        shots = qobj.config.shots
        job = backend.run(qobj)
        result = job.result()
        counts_qx1 = result.get_counts(result.get_names()[0])
        counts_qx2 = result.get_counts('hadamard')
        counts_ex1 = {'00': shots / 2, '11': shots / 2}
        counts_ex2 = {
            '00': shots / 4,
            '11': shots / 4,
            '10': shots / 4,
            '01': shots / 4
        }
        states1 = counts_qx1.keys() | counts_ex1.keys()
        states2 = counts_qx2.keys() | counts_ex2.keys()
        # contingency table
        ctable1 = numpy.array([[counts_qx1.get(key, 0) for key in states1],
                               [counts_ex1.get(key, 0) for key in states1]])
        ctable2 = numpy.array([[counts_qx2.get(key, 0) for key in states2],
                               [counts_ex2.get(key, 0) for key in states2]])
        self.log.info('states1: %s', str(states1))
        self.log.info('states2: %s', str(states2))
        self.log.info('ctable1: %s', str(ctable1))
        self.log.info('ctable2: %s', str(ctable2))
        contingency1 = chi2_contingency(ctable1)
        contingency2 = chi2_contingency(ctable2)
        self.log.info('chi2_contingency1: %s', str(contingency1))
        self.log.info('chi2_contingency2: %s', str(contingency2))
        self.assertGreater(contingency1[1], 0.01)
        self.assertGreater(contingency2[1], 0.01)
Beispiel #28
0
def register(*args, provider_class=None, **kwargs):
    """
    Authenticate against an online backend provider.
    This is a factory method that returns the provider that gets registered.

    Args:
        args (tuple): positional arguments passed to provider class initialization
        provider_class (BaseProvider): provider class
        kwargs (dict): keyword arguments passed to provider class initialization.
            For the IBMQSingleProvider default this can include things such as:

                * token (str): The token used to register on the online backend such
                    as the quantum experience.
                * url (str): The url used for online backend such as the quantum
                    experience.
                * hub (str): The hub used for online backend.
                * group (str): The group used for online backend.
                * project (str): The project used for online backend.
                * proxies (dict): Proxy configuration for the API, as a dict with
                    'urls' and credential keys.
                * verify (bool): If False, ignores SSL certificates errors.

    Returns:
        BaseProvider: the provider instance that was just registered.

    Raises:
        QISKitError: if the provider could not be registered

    .. deprecated:: 0.6+
        After 0.6, this function is deprecated. Please use the methods in
        `qiskit.IBMQ` instead (`use_account()`) for using IBMQ
        accounts. For custom `Provider`s, please instantiate them directly.
    """
    if provider_class:
        warnings.warn(
            'The global registry of providers and register() is deprecated '
            'since 0.6. Please instantiate "{}()" directly.'.format(
                provider_class), DeprecationWarning)
        return provider_class(*args, **kwargs)
    else:
        warnings.warn(
            'register() will be deprecated after 0.6. Please use the '
            'qiskit.IBMQ.use_account() method instead.', DeprecationWarning)

    try:
        provider = IBMQ.use_account(*args, **kwargs)
    except Exception as ex:
        raise QISKitError(
            "Couldn't instantiate provider! Error: {0}".format(ex))

    return provider
 def test_filter_least_busy(self, qe_token, qe_url):
     """Test filtering by least busy function"""
     IBMQ.use_account(qe_token, qe_url)
     backends = IBMQ.backends()
     filtered_backends = least_busy(backends)
     self.assertTrue(filtered_backends)
Beispiel #30
0
    def test_retrieve_job_error(self, qe_token, qe_url):
        IBMQ.use_account(qe_token, qe_url)
        backends = IBMQ.backends(simulator=False)
        backend = least_busy(backends)

        self.assertRaises(IBMQBackendError, backend.retrieve_job, 'BAD_JOB_ID')