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)
    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})
Beispiel #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_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)
    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))
Beispiel #6
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)
    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')
Beispiel #8
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)
    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')
    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)
    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))
Beispiel #12
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 _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)
Beispiel #14
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()
Beispiel #15
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)
Beispiel #16
0
    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)
 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)
Beispiel #18
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)
    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())
Beispiel #20
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)
Beispiel #21
0
 def test_disable_all_accounts(self):
     """Test disabling all accounts from session."""
     with custom_qiskitrc(), mock_ibmq_provider():
         IBMQ.enable_account('QISKITRC_TOKEN')
         IBMQ.enable_account('QISKITRC_TOKEN',
                             url=IBMQ_TEMPLATE.format('a', 'b', 'c'))
         IBMQ.disable_accounts()
         self.assertEqual(len(IBMQ._accounts), 0)
Beispiel #22
0
    def __init__(
        self,
        device_name: str,
        n_samples: Optional[int] = None,
        hub: Optional[str] = "ibm-q",
        group: Optional[str] = "open",
        project: Optional[str] = "main",
        api_token: Optional[str] = None,
        readout_correction: Optional[bool] = False,
        optimization_level: Optional[int] = 0,
        retry_delay_seconds: Optional[int] = 60,
        retry_timeout_seconds: Optional[int] = 86400,
        **kwargs,
    ):
        """Get a qiskit QPU that adheres to the
        zquantum.core.interfaces.backend.QuantumBackend

        Args:
            device_name: the name of the device
            n_samples: the number of samples to use when running the device
            hub: IBMQ hub
            group: IBMQ group
            project: IBMQ project
            api_token: IBMQ Api Token
            readout_correction: flag of whether or not to use basic readout correction
            optimization_level: optimization level for the default qiskit transpiler (0,
                1, 2, or 3).
            retry_delay_seconds: Number of seconds to wait to resubmit a job when backend
                job limit is reached.
            retry_timeout_seconds: Number of seconds to wait
        """
        super().__init__(n_samples=n_samples)
        self.device_name = device_name

        if 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)

        provider = IBMQ.get_provider(hub=hub, group=group, project=project)
        self.device = provider.get_backend(name=self.device_name)
        self.max_shots = self.device.configuration().max_shots
        self.batch_size = self.device.configuration().max_experiments
        self.supports_batching = True
        self.readout_correction = readout_correction
        self.readout_correction_filter = None
        self.optimization_level = optimization_level
        self.basis_gates = kwargs.get(
            "basis_gates", self.device.configuration().basis_gates
        )
        self.retry_delay_seconds = retry_delay_seconds
        self.retry_timeout_seconds = retry_timeout_seconds
Beispiel #23
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)
    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)
Beispiel #25
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')
    def test_double_submit_fails(self, qe_token, qe_url):
        """Test submitting a job twice."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = IBMQ.get_backend('ibmq_qasm_simulator')

        qobj = compile(self._qc, backend)
        # backend.run() will automatically call job.submit()
        job = backend.run(qobj)
        with self.assertRaises(JobError):
            job.submit()
    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
    def _wrapper(*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)
        provider = _get_custom_provider(IBMQ) or list(
            IBMQ._providers.values())[0]
        kwargs.update({'provider': provider})

        return func(*args, **kwargs)
    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)
    def test_api_run_job_fail_backend(self, qe_token, qe_url):
        """Test running a job against an invalid backend."""
        IBMQ.enable_account(qe_token, qe_url)

        backend_name = 'ibmq_qasm_simulator'
        backend = IBMQ.get_backend(backend_name)
        qobj = compile(self.qc1, backend=backend, seed=self.seed, shots=1)

        api = backend._api
        self.assertRaises(BadBackendError, api.run_job, qobj.as_dict(),
                          'INVALID_BACKEND_NAME')