예제 #1
0
def get_qiskit_noise_model(
    device_name: str,
    hub: str = "ibm-q",
    group: str = "open",
    project: str = "main",
    api_token: Optional[str] = None,
) -> Tuple[NoiseModel, CircuitConnectivity]:
    """Get a qiskit noise model to use noisy simulations with a qiskit simulator

    Args:
        device_name: The name of the device trying to be emulated
        hub: The ibmq hub (see qiskit documentation)
        group: The ibmq group (see qiskit documentation)
        project: The ibmq project (see qiskit documentation)
        api_token: The ibmq api token (see qiskit documentation)


    """
    if api_token is not None and api_token is not "None":
        try:
            IBMQ.enable_account(api_token)
        except IBMQAccountError as e:
            if (e.message !=
                    "An IBM Quantum Experience account is already in use for the session."
                ):
                raise RuntimeError(e)

    # Get qiskit noise model from qiskit
    provider = IBMQ.get_provider(hub=hub, group=group, project=project)
    noisy_device = provider.get_backend(device_name)

    noise_model = AerNoise.NoiseModel.from_backend(noisy_device)
    coupling_map = noisy_device.configuration().coupling_map

    return noise_model, CircuitConnectivity(coupling_map)
    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)
예제 #3
0
    def test_disable_accounts(self):
        """Test disabling an account in a session."""
        with custom_qiskitrc(), mock_ibmq_provider():
            IBMQ.enable_account('QISKITRC_TOKEN')
            IBMQ.disable_accounts(token='QISKITRC_TOKEN')

            self.assertEqual(len(IBMQ._accounts), 0)
    def test_online_qasm_simulator_two_registers(self, qe_token, qe_url):
        """Test online_qasm_simulator_two_registers."""
        IBMQ.enable_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, name="circuit1")
        qcr2 = QuantumCircuit(qr1, qr2, cr1, cr2, name="circuit2")
        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 = compile([qcr1, qcr2],
                       backend,
                       seed=8458,
                       shots=shots,
                       seed_mapper=88434)
        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})
예제 #5
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)
예제 #6
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)
예제 #7
0
    def _wrapper(obj, *args, **kwargs):

        qe_token = kwargs.pop('qe_token')
        qe_url = kwargs.pop('qe_url')
        if not IBMQ.active_account():
            IBMQ.enable_account(qe_token, qe_url)

        backend_name = os.getenv('QE_STAGING_DEVICE', None) if \
            os.getenv('USE_STAGING_CREDENTIALS', '') else os.getenv('QE_DEVICE', None)

        _backend = None
        provider = _get_custom_provider(IBMQ) or list(
            IBMQ._providers.values())[0]

        if backend_name:
            # Put desired provider as the first in the list.
            providers = [provider] + IBMQ.providers()
            for provider in providers:
                backends = provider.backends(name=backend_name)
                if backends:
                    _backend = backends[0]
                    break
        else:
            _backend = least_busy(
                provider.backends(
                    simulator=False,
                    filters=lambda b: b.configuration().n_qubits >= 5))

        if not _backend:
            raise Exception('Unable to find a suitable backend.')

        kwargs.update({'backend': _backend})

        return func(obj, *args, **kwargs)
예제 #8
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))
예제 #9
0
    def test_get_jobs_filter_counts(self, qe_token, qe_url):
        """Test retrieving jobs from a backend filtered by counts."""
        # TODO: consider generalizing backend name
        # TODO: this tests depends on the previous executions of the user
        IBMQ.enable_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')

        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, db_filter=my_filter)

        for i, job in enumerate(job_list):
            self.log.info('match #%d', i)
            result = job.result()
            self.assertTrue(any(cresult.data.counts.to_dict()['0x0'] < 500
                                for cresult in result.results))
    def test_run_job_object_storage(self, qe_token, qe_url):
        """Test running a job against a simulator using object storage."""
        IBMQ.enable_account(qe_token, qe_url)

        # Create a Qobj.
        backend_name = 'ibmq_qasm_simulator'
        backend = IBMQ.get_backend(backend_name)
        circuit = transpile(self.qc1, backend, seed_transpiler=self.seed)
        qobj = assemble(circuit, backend, shots=1)
        print('complied')

        # Run the job through the IBMQClient directly using object storage.
        api = backend._api
        job = api.job_submit_object_storage(backend_name, qobj.as_dict())
        job_id = job['id']
        self.assertEqual(job['kind'], 'q-object-external-storage')

        # Wait for completion.
        api.job_final_status_websocket(job_id)

        # Fetch results and qobj via object storage.
        result = api.job_result_object_storage(job_id)
        qobj_downloaded = api.job_download_qobj_object_storage(job_id)

        self.assertEqual(qobj_downloaded, qobj.as_dict())
        self.assertEqual(result['status'], 'COMPLETED')
예제 #11
0
    def test_run_simulator(self, qe_token, qe_url):
        """Test running in a simulator."""
        IBMQ.enable_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 = compile([self._qc, qc], backend)
        shots = qobj.config.shots
        job = backend.run(qobj)
        result = job.result()
        counts_qx1 = result.get_counts(0)
        counts_qx2 = result.get_counts(1)
        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)
예제 #12
0
    def test_store_credentials_overwrite(self):
        """Test overwriting qiskitrc credentials."""
        credentials = Credentials('QISKITRC_TOKEN', url=QE_URL, hub='HUB')
        credentials2 = Credentials('QISKITRC_TOKEN_2', url=QE_URL)

        with custom_qiskitrc():
            store_credentials(credentials)
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            # Attempt overwriting.
            with warnings.catch_warnings(record=True) as w:
                store_credentials(credentials)
                self.assertIn('already present', str(w[0]))

            with no_file('Qconfig.py'), no_envs(
                    CREDENTIAL_ENV_VARS), mock_ibmq_provider():
                # Attempt overwriting.
                store_credentials(credentials2, overwrite=True)
                IBMQ.load_accounts()

        # Ensure that the credentials are the overwritten ones - note that the
        # 'hub' parameter was removed.
        self.assertEqual(len(IBMQ._accounts), 1)
        self.assertEqual(
            list(IBMQ._accounts.values())[0].credentials.token,
            'QISKITRC_TOKEN_2')
 def tearDownClass(cls) -> None:
     super().tearDownClass()
     from qiskit.providers.ibmq import IBMQ
     try:
         IBMQ.disable_account()
     except IBMQAccountCredentialsNotFound:
         pass
    def test_execute_several_circuits_simulator_online(self, qe_token, qe_url):
        """Test execute_several_circuits_simulator_online."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qr = QuantumRegister(2)
        cr = ClassicalRegister(2)
        qcr1 = QuantumCircuit(qr, cr, name='qc1')
        qcr2 = QuantumCircuit(qr, cr, name='qc2')
        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 = compile([qcr1, qcr2],
                       backend=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)
예제 #15
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')
    def test_autoregister_no_credentials(self):
        """Test register() with no credentials available."""
        with no_file('Qconfig.py'), custom_qiskitrc(), no_envs():
            with self.assertRaises(IBMQAccountError) as context_manager:
                IBMQ.load_accounts()

        self.assertIn('No IBMQ credentials found', str(context_manager.exception))
예제 #17
0
 def test_pass_bad_proxy(self):
     """Test proxy pass through."""
     with self.assertRaises(RequestsApiError) as context_manager:
         IBMQ.enable_account('dummy_token',
                             'https://dummy_url',
                             proxies=PROXIES)
     self.assertIsInstance(context_manager.exception.original_exception,
                           ProxyError)
예제 #18
0
    def test_get_backend_name(self, qe_token, qe_url):
        """Test getting a backend name."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = compile(self._qc, backend)
        job = backend.run(qobj)
        self.assertTrue(job.backend().name() == backend.name())
예제 #19
0
    def test_save_account(self):
        """Test saving one account."""
        with custom_qiskitrc(), mock_ibmq_provider():
            IBMQ.save_account('QISKITRC_TOKEN', url=QE_URL, proxies=PROXIES)

            # Compare the session accounts with the ones stored in file.
            stored_accounts = read_credentials_from_qiskitrc()
            self.assertEqual(len(stored_accounts.keys()), 1)
예제 #20
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)
예제 #21
0
파일: ibmq.py 프로젝트: vanmagnan/shor
 def _try_login_saved_account(cls) -> bool:
     if not QiskitIBMQ.active_account():
         try:
             QiskitIBMQ.load_account()
         except IBMQAccountCredentialsNotFound:
             print(f"No saved account found for IBMQ. Only simulator devices will be available. {_IBMQHints.LOGIN}")
             return False  # Failed login
     return True  # Successful login
예제 #22
0
파일: ibmq.py 프로젝트: vanmagnan/shor
    def login(cls, token: str = "", remember: bool = False, **kwargs) -> bool:

        if not token:
            return cls._try_login_saved_account()
        else:
            QiskitIBMQ.enable_account(token, **kwargs)
            if remember:
                QiskitIBMQ.save_account(token, **kwargs)
예제 #23
0
    def test_load_account_no_credentials(self) -> None:
        """Test ``load_account()`` with no credentials available."""
        with custom_qiskitrc(), no_envs(CREDENTIAL_ENV_VARS):
            with self.assertRaises(IBMQAccountError) as context_manager:
                IBMQ.load_account()

        self.assertIn('No IBM Quantum Experience credentials found',
                      str(context_manager.exception))
 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)
예제 #25
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()
예제 #26
0
def _enable_account(qe_token: str, qe_url: str) -> None:
    """Enable the account if one is not already active.

    :param qe_token: API token.
    :param qe_url: API URL.
    """
    if not IBMQ.active_account():
        IBMQ.enable_account(qe_token, qe_url)
예제 #27
0
    def test_delete_accounts(self):
        """Test deleting an account from disk."""
        with custom_qiskitrc(), mock_ibmq_provider():
            IBMQ.save_account('QISKITRC_TOKEN')
            self.assertEqual(len(read_credentials_from_qiskitrc()), 1)

            IBMQ._accounts.clear()
            IBMQ.delete_accounts(token='QISKITRC_TOKEN')
            self.assertEqual(len(read_credentials_from_qiskitrc()), 0)
예제 #28
0
    def test_autoregister_no_credentials(self):
        """Test ``register()`` with no credentials available."""
        with no_file('Qconfig.py'), custom_qiskitrc(), no_envs(
                CREDENTIAL_ENV_VARS):
            with self.assertRaises(IBMQAccountError) as context_manager:
                IBMQ.load_account()

        self.assertIn('No IBM Quantum Experience credentials found',
                      str(context_manager.exception))
예제 #29
0
 def test_ibmq_result_fields(self, qe_token, qe_url):
     """Test components of a result from a remote simulator."""
     IBMQ.enable_account(qe_token, qe_url)
     remote_backend = IBMQ.get_backend(local=False, simulator=True)
     remote_result = execute(self._qc1, remote_backend).result()
     self.assertEqual(remote_result.backend_name, remote_backend.name())
     self.assertIsInstance(remote_result.job_id, str)
     self.assertEqual(remote_result.status, 'COMPLETED')
     self.assertEqual(remote_result.results[0].status, 'DONE')
예제 #30
0
    def test_job_id(self, qe_token, qe_url):
        """Test getting a job id."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = compile(self._qc, backend)
        job = backend.run(qobj)
        self.log.info('job_id: %s', job.job_id())
        self.assertTrue(job.job_id() is not None)