def test_backend_overview(self, qe_token, qe_url): """Test backend_overview""" from qiskit import IBMQ # pylint: disable: import-error IBMQ.enable_account(qe_token, qe_url) self.addCleanup(IBMQ.disable_account) with patch('sys.stdout', new=StringIO()) as fake_stdout: backend_overview() stdout = fake_stdout.getvalue() self.assertIn('Operational:', stdout) self.assertIn('Avg. T1:', stdout) self.assertIn('Num. Qubits:', stdout)
def set_parameters(description='Lloyd algorithm', parser_class=None, additional_argument_list=None): """ :param additional_argument_list: list of (args, kwargs) """ if parser_class is None: parser = DefaultArgumentParser(description=description) else: parser = parser_class(description=description) if additional_argument_list is not None: for additional_argument in additional_argument_list: parser.add_argument(*additional_argument[0], **additional_argument[1]) args = parser.parse_args() try: from Qconfig import APItoken, config if args.token is not None: token = args.token else: token = APItoken IBMQ.enable_account(token, **config) except ImportError: pass global BACKENDS BACKENDS += IBMQ.backends() if args.show_backends: for backend in BACKENDS: print(backend.name()) sys.exit() if args.file: exec_file = os.path.basename(sys.argv[0])[:-3] output_dir = 'outputs' if not os.path.exists(output_dir): os.mkdir(output_dir) filename = f"{output_dir}/output_{exec_file}_" \ f"{args.backend}_{description.lower().replace(' ', '-')}_" \ f"{datetime.datetime.today().strftime('%Y_%m_%d')}" sys.stdout = open(filename, 'a') sys.stderr = open(filename, 'a') return { 'backend_name': args.backend, 'shots': args.shots, 'args': args # args can have additional field that isn't covered recently }
def test_cancel(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backend_name = ('ibmq_20_tokyo' if self.using_ibmq_credentials else 'ibmqx4') backend = IBMQ.get_backend(backend_name) qobj = 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)
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)
def __init__( self, device_name, n_samples=None, noise_model=None, device_connectivity=None, basis_gates=None, api_token=None, optimization_level=0, **kwargs, ): """Get a qiskit device (simulator or QPU) that adheres to the zquantum.core.interfaces.backend.QuantumSimulator Args: device_name (string): the name of the device n_samples (int): the number of samples to use when running the device noise_model (qiskit.providers.aer.noise.NoiseModel): an optional noise model to pass in for noisy simulations device_connectivity (zquantum.core.circuit.CircuitConnectivity): an optional input of an object representing the connectivity of the device that will be used in simulations basis_gates (list): an optional input of the list of basis gates used in simulations api_token (string): IBMQ Api Token optimization_level (int): optimization level for the default qiskit transpiler (0, 1, 2, or 3) Returns: qeqiskit.backend.QiskitSimulator """ self.device_name = device_name self.n_samples = n_samples self.noise_model = noise_model self.device_connectivity = device_connectivity self.num_circuits_run = 0 self.num_jobs_run = 0 if basis_gates is None and self.noise_model is not None: self.basis_gates = self.noise_model.basis_gates else: self.basis_gates = basis_gates 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) self.optimization_level = optimization_level self.get_device(**kwargs)
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.enable_account(self._qe_token, self._qe_url) self._backend = IBMQ.get_backend(self._testing_device) self._qc = _bell_circuit()
def _refresh_ibmq_account(): """ Refresh IBMQ account by enabling or disabling it depending on preferences stored values """ preferences = Preferences().ibmq_credentials_preferences token = preferences.token or '' proxies = preferences.proxies or {} hub = preferences.hub group = preferences.group project = preferences.project provider = None try: # pylint: disable=no-name-in-module, import-error from qiskit import IBMQ providers = IBMQ.providers() if token != '': # check if there was a previous account that needs to be disabled first disable_account = False enable_account = True for provider in providers: if provider.credentials.token == token and provider.credentials.proxies == proxies: enable_account = False else: disable_account = True if disable_account: IBMQ.disable_account() logger.info('Disabled IBMQ account.') if enable_account: IBMQ.enable_account(token, proxies=proxies) logger.info('Enabled IBMQ account.') providers = IBMQ.providers(hub=hub, group=group, project=project) provider = providers[0] if providers else None if provider is None: logger.info( "No Provider found for IBMQ account. " "Hub/Group/Project: '%s/%s/%s' Proxies:'%s'", hub, group, project, proxies) else: if providers: IBMQ.disable_account() logger.info('Disabled IBMQ account.') except Exception as ex: # pylint: disable=broad-except logger.warning( "IBMQ account Account Failure. " "Hub/Group/Project: '%s/%s/%s' " "Proxies:'%s' :%s", hub, group, project, proxies, str(ex)) return provider
def test_run_async_simulator(self, qe_token, qe_url): IBMQJob._executor = futures.ThreadPoolExecutor(max_workers=2) IBMQ.enable_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 = 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.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.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))))
def test_retrieve_job(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend('ibmq_qasm_simulator') qobj = compile(self._qc, backend) job = backend.run(qobj) rjob = backend.retrieve_job(job.job_id()) self.assertEqual(job.job_id(), rjob.job_id()) self.assertEqual(job.result().get_counts(), rjob.result().get_counts()) if getattr(backend.configuration(), 'allow_q_object'): self.assertEqual(job.qobj().as_dict(), qobj.as_dict()) else: self.assertEqual(job.qobj(), None)
def activate_ibmq(self): """Activates IBMQ account and gets IBMQ provider Note: you will get an import error if you do not have a python scipt named my_secrets.py with your IBMQ API token in the same directory as this file """ from my_secrets import pw key = pw try: IBMQ.enable_account(key) except: print('IBMQAccountError: Account already activated') finally: self.provider = IBMQ.get_provider('ibm-q')
def test_remote_backend_status(self, qe_token, qe_url): """Test backend_status. If all correct should pass the validation. """ schema_path = self._get_resource_path( 'backend_status_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) IBMQ.enable_account(qe_token, qe_url) for backend in IBMQ.backends(): status = backend.status() jsonschema.validate(status.to_dict(), schema)
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))))
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_remote_backend_configuration(self, qe_token, qe_url): """Test backend configuration. If all correct should pass the validation. """ IBMQ.enable_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)
def test_compile_run_remote(self, qe_token, qe_url): """Test Compiler and run remote.""" IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend(local=False, simulator=True) 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 = compile(qc, backend, seed=TestCompiler.seed) job = backend.run(qobj) result = job.result(timeout=20) self.assertIsInstance(result, Result)
def test_execute_remote(self, qe_token, qe_url): """Test Execute remote.""" IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend(local=False, simulator=True) qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg) qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, backend, seed=TestCompiler.seed) results = job.result() self.assertIsInstance(results, Result)
def test_enable_account(self): """Test enabling one account.""" with custom_qiskitrc(), mock_ibmq_provider(): IBMQ.enable_account('QISKITRC_TOKEN', url='someurl', proxies=PROXIES) # Compare the session accounts with the ones stored in file. loaded_accounts = read_credentials_from_qiskitrc() _, provider = list(IBMQ._accounts.items())[0] self.assertEqual(loaded_accounts, {}) self.assertEqual('QISKITRC_TOKEN', provider.credentials.token) self.assertEqual('someurl', provider.credentials.url) self.assertEqual(PROXIES, provider.credentials.proxies)
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.enable_account(self._qe_token, self._qe_url) self._local_backend = Aer.get_backend('qasm_simulator_py') 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())
def test_run_circuit_and_get_expval_simple_ibmq(self, token, op, monkeypatch): """Test running an empty circuit.""" lst = [] IBMQ.enable_account(token) backend_specs = '{"module_name": "qeqiskit.backend", "function_name": "QiskitBackend", "device_name": "ibmq_qasm_simulator", "n_samples": 8192}' simple_qasm = 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[3];\ncreg c[3];\n' monkeypatch.setattr(expval, "save_list", lambda val, name: lst.append(val)) expval.run_circuit_and_get_expval(backend_specs, simple_qasm, op) assert math.isclose(lst[0][0], 1.0, abs_tol=tol)
def test_remote_backend_configuration(self, qe_token, qe_url): """Test backend configuration. If all correct should pass the validation. """ schema_path = self._get_resource_path( 'backend_configuration_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) IBMQ.enable_account(qe_token, qe_url) remotes = IBMQ.backends() for backend in remotes: configuration = backend.configuration() jsonschema.validate(configuration.to_dict(), schema)
def test_track_sampler(self, token): """Test that the tracker works.""" IBMQ.enable_account(token) dev = IBMQSamplerDevice(wires=1, backend="ibmq_qasm_simulator", shots=1) dev.tracker.active = True @qml.qnode(dev) def circuit(): qml.PauliX(wires=0) return qml.probs(wires=0) circuit() assert len(dev.tracker.history) == 2
def test_remote_backend_properties(self, qe_token, qe_url): """Test backend properties. If all correct should pass the validation. """ schema_path = self._get_resource_path( 'backend_properties_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) IBMQ.enable_account(qe_token, qe_url) remotes = IBMQ.backends(simulator=False) for backend in remotes: properties = backend.properties() jsonschema.validate(properties.to_dict(), schema)
def test_remote_backend_properties(self, qe_token, qe_url): """Test backend properties.""" schema_path = self._get_resource_path('backend_properties_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) 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) else: jsonschema.validate(properties.to_dict(), schema)
def __init__(self, wires, provider=None, backend="ibmq_qasm_simulator", shots=1024, **kwargs): token = os.getenv("IBMQX_TOKEN") or kwargs.get("ibmqx_token", None) url = os.getenv("IBMQX_URL") or kwargs.get("ibmqx_url", None) # Specify a single hub, group and project hub = kwargs.get("hub", "ibm-q") group = kwargs.get("group", "open") project = kwargs.get("project", "main") if token is not None: # token was provided by the user, so attempt to enable an # IBM Q account manually ibmq_kwargs = {"url": url} if url is not None else {} IBMQ.enable_account(token, **ibmq_kwargs) else: # check if an IBM Q account is already active. # # * IBMQ v2 credentials stored in active_account(). # If no accounts are active, it returns None. if IBMQ.active_account() is None: # no active account try: # attempt to load a v2 account stored on disk IBMQ.load_account() except IBMQAccountError: # attempt to enable an account manually using # a provided token raise IBMQAccountError( "No active IBM Q account, and no IBM Q token provided." ) from None # IBM Q account is now enabled # get a provider p = provider or IBMQ.get_provider( hub=hub, group=group, project=project) super().__init__(wires=wires, provider=p, backend=backend, shots=shots, **kwargs)
def test_remote_backend_status(self, qe_token, qe_url): """Test backend_status. If all correct should pass the validation. """ IBMQ.enable_account(qe_token, qe_url) remotes = IBMQ.backends() remotes = remove_backends_from_list(remotes) for backend in remotes: status = backend.status() self.log.debug(status) schema_path = self._get_resource_path('backend_status_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) jsonschema.validate(status, schema)
def backend(account, backend_id): token = utils.accounts()[account]["token"] try: IBMQ.disable_account() except: pass provider = IBMQ.enable_account(token) return provider.get_backend(backend_id)
def test_simple_circuit(token, tol, shots): IBMQ.enable_account(token) dev = IBMQDevice(wires=2, backend="ibmq_qasm_simulator", shots=shots) @qml.qnode(dev) def circuit(theta, phi): qml.RX(theta, wires=0) qml.RX(phi, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) theta = 0.432 phi = 0.123 res = circuit(theta, phi) expected = np.array([np.cos(theta), np.cos(theta) * np.cos(phi)]) assert np.allclose(res, expected, **tol)
def _get_provider(): if IBMQ.active_account() is None: ibmq_token = os.environ["IBMQ_TOKEN"] provider = IBMQ.enable_account(ibmq_token) else: provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main") return provider
def test_backend_monitor(self, qe_token, qe_url): """Test backend_monitor""" from qiskit import IBMQ # pylint: disable: import-error IBMQ.enable_account(qe_token, qe_url) for back in IBMQ.backends(): if not back.configuration().simulator: backend = back break with patch('sys.stdout', new=StringIO()) as fake_stout: backend_monitor(backend) stdout = fake_stout.getvalue() self.assertIn('Configuration', stdout) self.assertIn( 'Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]', stdout) self.assertIn('Multi-Qubit Gates [Name / Type / Gate Error]', stdout)
def __init__(self, wires, provider=None, backend="ibmq_qasm_simulator", shots=1024, **kwargs): token = os.getenv("IBMQX_TOKEN") or kwargs.get("ibmqx_token", None) url = os.getenv("IBMQX_URL") or kwargs.get("ibmqx_url", None) if token is not None: # token was provided by the user, so attempt to enable an # IBM Q account manually ibmq_kwargs = {"url": url} if url is not None else {} IBMQ.enable_account(token, **ibmq_kwargs) else: # turn off deprecation warnings # TODO: remove IBM Q v1 API calls when fully deprecated with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) # check if an IBM Q account is already active. # # * IBMQ v1 credentials stored in active_accounts(). # If no accounts are active, it returns [] # # * IBMQ v2 credentials stored in active_account(). # If no accounts are active, it returns None. if IBMQ.active_account() is None and not IBMQ.active_accounts(): # no active account try: # attempt to load a v1 account stored on disk IBMQ.load_accounts() except IBMQAccountError: try: # attempt to load a v2 account stored on disk IBMQ.load_account() except IBMQAccountError: # attempt to enable an account manually using # a provided token raise IBMQAccountError( "No active IBM Q account, and no IBM Q token provided." ) from None # IBM Q account is now enabled # get a provider p = provider or IBMQ.get_provider() super().__init__(wires=wires, provider=p, backend=backend, shots=shots, **kwargs)