def _get_first_available_backend(backends): """Gets the first available backend.""" for backend_name in backends: try: get_backend(backend_name) return backend_name except LookupError: pass return None
def test_aggregate(self): """Test that aggregate group names maps the first available backend of their list of backends.""" aggregate_backends = _DEFAULT_PROVIDER.grouped_backend_names() for group_name, priority_list in aggregate_backends.items(): with self.subTest(group_name=group_name, priority_list=priority_list): target_backend = _get_first_available_backend(priority_list) if target_backend: self.assertEqual(get_backend(group_name), get_backend(target_backend))
def test_deprecated(self, qe_token, qe_url): """Test that deprecated names map the same backends as the new names. """ register(qe_token, qe_url) deprecated_names = _DEFAULT_PROVIDER.deprecated_backend_names() for oldname, newname in deprecated_names.items(): if newname == 'local_qasm_simulator_cpp' and not is_cpp_simulator_available(): continue with self.subTest(oldname=oldname, newname=newname): self.assertEqual(get_backend(oldname), get_backend(newname))
def test_deprecated(self, QE_TOKEN, QE_URL, hub=None, group=None, project=None): """Test that deprecated names map the same backends as the new names. """ register(QE_TOKEN, QE_URL, hub, group, project) deprecated_names = _DEFAULT_PROVIDER.deprecated_backend_names() for oldname, newname in deprecated_names.items(): if newname == 'local_qasm_simulator_cpp' and _skip_cpp: continue with self.subTest(oldname=oldname, newname=newname): self.assertEqual(get_backend(oldname), get_backend(newname))
def test_aliases(self, QE_TOKEN, QE_URL): """Test that display names of devices map the same backends as the regular names.""" register(QE_TOKEN, QE_URL) aliased_names = _DEFAULT_PROVIDER.aliased_backend_names() for display_name, backend_name in aliased_names.items(): with self.subTest(display_name=display_name, backend_name=backend_name): backend_by_name = get_backend(backend_name) backend_by_display_name = get_backend(display_name) self.assertEqual(backend_by_name, backend_by_display_name) self.assertEqual(backend_by_display_name['name'], backend_name)
def setup(self): version_parts = qiskit.__version__.split('.') if version_parts[0] == '0' and int(version_parts[1]) < 5: self.local_qasm_simulator = None elif hasattr(qiskit, 'BasicAer'): self.local_qasm_simulator = qiskit.BasicAer.get_backend( 'qasm_simulator') elif hasattr(qiskit, 'get_backend'): self.local_qasm_simulator = qiskit.get_backend( 'local_qasm_simulator') else: self.local_qasm_simulator = qiskit.BasicAer.get_backend( "qasm_simulator") self.has_compile = False if hasattr(qiskit, 'compile'): self.has_compile = True self.single_gate_circuit = self._build_single_gate_circuit() self.cx_circuit = self._build_cx_circuit() self.qasm_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'qasm')) large_qasm_path = os.path.join(self.qasm_path, 'test_eoh_qasm.qasm') if hasattr(qiskit, 'load_qasm_file'): self.large_qasm = qiskit.load_qasm_file(large_qasm_path) elif version_parts[0] == '0' and int(version_parts[1]) < 5: self.large_qasm = qiskit.QuantumProgram() self.large_qasm.load_qasm_file(large_qasm_path, name='large_qasm') else: self.large_qasm = qiskit.QuantumCircuit.from_qasm_file( large_qasm_path)
def exec_circuits(jobs, backend): bad_backend = True runner = None while bad_backend: try: runner = get_backend(backend) bad_backend = False global BACKEND BACKEND = backend #remember new backend except Exception as e: print(available_backends()) backend = input( "chosen backend not available, choose one from the list above: " ) bad_backend = True job_num = 0 started_jobs = [] for qobj in jobs: try: job = runner.run(qobj) except Exception as e: print("job number " + str(job_num) + " failed...\nrunning next job...") job_num += 1 started_jobs.append(job) return started_jobs
def ret(params): print("Computing U^{} error with {}: ".format(2**power, params), end='') from qiskit import get_backend, execute, QuantumProgram from utils.endianness import QRegisterBE, CRegister import numpy as np import scipy.linalg as la def swap(U): from copy import deepcopy cpy = deepcopy(U) cpy[[1,2],:] = cpy[[2,1],:] cpy[:,[1,2]] = cpy[:,[2,1]] return cpy Q_SPECS = { "name": "Hamiltonian_error", "circuits": [ { "name": "4x4", "quantum_registers": [ { "name": "ctrl", "size": 1 }, { "name": "qb", "size": 2 }, ], "classical_registers": [ { "name": "classicalX", "size": 2 }] } ], } Q_program = QuantumProgram(specs=Q_SPECS) circuit = Q_program.get_circuit("4x4") qb = QRegisterBE(Q_program.get_quantum_register("qb")) ctrl = QRegisterBE(Q_program.get_quantum_register("ctrl")) classicalX = CRegister(Q_program.get_classical_register('classicalX')) circuit.optim_hamil(ctrl[0], qb, params).inverse() unitary_sim = get_backend('local_unitary_simulator') res = execute([circuit], unitary_sim).result() unitary = res.get_unitary() A = .25 * np.array([[15, 9, 5, -3], [9, 15, 3, -5], [5, 3, 15, -9], [-3, -5, -9, 15]]) expA = swap(la.expm(-1.j * A * (2**power) * 2 * np.pi / 16)) unit = unitary[1::2, 1::2] err = la.norm(unit - expA) print(err) return err
def test_local_groups(self): """test local group names are resolved correctly""" group_name = "local_qasm_simulator" backend = get_backend(group_name) if not _skip_cpp: self.assertIsInstance(backend, QasmSimulatorCpp) else: self.assertIsInstance(backend, QasmSimulatorPy)
def bestBackend(): sim = int(input("\nAllow simulators [0/1]?")) list = available_backends({'local': False, 'simulator': sim}) bestatus = [get_backend(backend).status for backend in list] best = min([x for x in bestatus if x['available'] is True], key=lambda x: x['pending_jobs']) print("Using backend: " + best['name']) return best['name']
def lowest_pending_jobs(): """Returns the backend with lowest pending jobs.""" list_of_backends = available_backends( {'local': False, 'simulator': False}) device_status = [get_backend(backend).status for backend in list_of_backends] best = min([x for x in device_status if x['available'] is True], key=lambda x: x['pending_jobs']) return best['name']
def vqe(molecule='H2', depth=6, max_trials=200, shots=1): if molecule == 'H2': n_qubits = 2 Z1 = 1 Z2 = 1 min_distance = 0.2 max_distance = 4 elif molecule == 'LiH': n_qubits = 4 Z1 = 1 Z2 = 3 min_distance = 0.5 max_distance = 5 else: raise QISKitError("Unknown molecule for VQE.") # Read Hamiltonian ham_name = os.path.join(os.path.dirname(__file__), molecule + '/' + molecule + 'Equilibrium.txt') pauli_list = Hamiltonian_from_file(ham_name) H = make_Hamiltonian(pauli_list) # Exact Energy exact = np.amin(la.eig(H)[0]).real print('The exact ground state energy is: {}'.format(exact)) # Optimization device = 'qasm_simulator' if shots == 1: device = 'statevector_simulator' if 'statevector' not in device: H = group_paulis(pauli_list) entangler_map = get_backend(device).configuration()['coupling_map'] if entangler_map == 'all-to-all': entangler_map = {i: [j for j in range(n_qubits) if j != i] for i in range(n_qubits)} else: entangler_map = mapper.coupling_list2dict(entangler_map) initial_theta = np.random.randn(2 * n_qubits * depth) # initial angles initial_c = 0.01 # first theta perturbations target_update = 2 * np.pi * 0.1 # aimed update on first trial save_step = 20 # print optimization trajectory cost = partial(cost_function, H, n_qubits, depth, entangler_map, shots, device) SPSA_params, circuits_cal = SPSA_calibration(cost, initial_theta, initial_c, target_update, stat=25) output, circuits_opt = SPSA_optimization(cost, initial_theta, SPSA_params, max_trials, save_step, last_avg=1) return circuits_cal + circuits_opt
def lowest_pending_jobs(): from qiskit import available_backends, get_backend list_of_backends = available_backends( {'local': False, 'simulator': False}) device_status = [get_backend(backend).status for backend in list_of_backends] best = min([ x for x in device_status if x['available'] is True], key = lambda x: x['pending_jobs']) return best['name']
def lowest_pending_jobs(): """Returns the backend with lowest pending jobs.""" list_of_backends = available_backends({'local': False, 'simulator': False}) device_status = [ get_backend(backend).status for backend in list_of_backends ] best = min([x for x in device_status if x['available'] is True], key=lambda x: x['pending_jobs']) return best['name']
def present_backends(sim, backends): if (sim == 0): # Gathering backend information print('Please select a backend: ') backends.sort() #Listing computers print('\n\033[92m###### Quantum Computers: ######\033[0m') print('IBMQX5 has 16 QBits - IBMQX4 and IBMQX2 have 5 QBits') for idx, backend in enumerate(backends): if backend.find('ibmqx') == 0: print(backend, '(', idx, ')') #Listing simulators print('\n\033[92m########## Simulators ##########\033[0m') for idx, backend in enumerate(backends): if backend.find('ibmqx'): print(backend, '(', idx, ')') res = input() return (get_backend(backends[int(res)])) else: return (get_backend('local_qasm_simulator'))
def get_runner(): bad_backend = True runner = None global BACKEND while bad_backend: try: runner = get_backend(BACKEND) bad_backend = False except Exception as e: print(available_backends()) BACKEND = input( "chosen backend not available, choose one from the list above: " ) bad_backend = True return runner
def test_api_calls_no_parameters(self): """Test calling some endpoints of the API with no hub parameters. Note: this tests does not make assertions, it is only intended to verify the endpoints. """ # Invoke with no hub, group or project parameters. _ = self._set_api(QE_TOKEN, {'url': QE_URL}) self.log.info(qiskit.available_backends(filters={'local': False})) all_backend_names = qiskit.available_backends() for backend_name in all_backend_names: backend = qiskit.get_backend(backend_name) self.log.info(backend.parameters) self.log.info(backend.calibration)
def test_api_calls_parameters(self): """Test calling some endpoints of the API with hub parameters. Note: this tests does not make assertions, it is only intended to verify the endpoints. """ # Invoke with hub, group and project parameters. _ = self._set_api(QE_TOKEN, {'url': QE_URL, 'hub': QE_HUB, 'group': QE_GROUP, 'project': QE_PROJECT}) all_backend_names = qiskit.available_backends() for backend_name in all_backend_names: backend = qiskit.get_backend(backend_name) self.log.info(backend.parameters) self.log.info(backend.calibration)
def get_coupling(backend): """Get coupling map of the backend Parameters: backend (str): backend name Returns: coupling_map (dict): backend coupling map """ # register(config.APItoken, config.URL) configuration = get_backend(backend).configuration couplings = configuration['coupling_map'] coupling_map = dict() for n in range(configuration['n_qubits']): coupling_map.update({n: []}) for coupling in couplings: coupling_map[coupling[0]].append(coupling[1]) return {'backend_name': backend, 'coupling_map': coupling_map}
def createDeviceStatus(self, back): if (version.parse(__version__) > version.parse("0.5") and version.parse(__version__) < version.parse("0.6")): return { 'name': self.PUBLIC_NAMES[back], 'status': self.parseBackendStatus(get_backend(back).status) } elif (version.parse(__version__) > version.parse("0.6")): return { 'name': self.PUBLIC_NAMES[back], 'status': self.parseBackendStatus(IBMQ.get_backend(back).status()) } else: raise QiskitUnsupportedVersion( 'Qiskit-terra version must be v0.5 or v0.6')
def test_api_calls_parameters(self): """Test calling some endpoints of the API with hub parameters. Note: this tests does not make assertions, it is only intended to verify the endpoints. """ # Invoke with hub, group and project parameters. _ = self._set_api(QE_TOKEN, { 'url': QE_URL, 'hub': QE_HUB, 'group': QE_GROUP, 'project': QE_PROJECT }) all_backend_names = qiskit.available_backends() for backend_name in all_backend_names: backend = qiskit.get_backend(backend_name) self.log.info(backend.parameters) self.log.info(backend.calibration)
def test_combine_results(self): """Test combining two results.""" backend = get_backend('local_qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) qc1 = QuantumCircuit(q, c) qc2 = QuantumCircuit(q, c) qc1.measure(q[0], c[0]) qc2.x(q[0]) qc2.measure(q[0], c[0]) qobj1 = compile(qc1, backend) qobj2 = compile(qc2, backend) job1 = backend.run(qobj1) job2 = backend.run(qobj2) result1 = job1.result() result2 = job2.result() counts1 = result1.get_counts(qc1) counts2 = result2.get_counts(qc2) result1 += result2 counts12 = [result1.get_counts(qc1), result1.get_counts(qc2)] self.assertEqual(counts12, [counts1, counts2])
def test_qubitpol(self): """Test the results of the qubitpol function in Results. Do two 2Q circuits: on 1st do nothing, and on 2nd do X on the first qubit. """ backend = get_backend('local_qasm_simulator') q = QuantumRegister(2) c = ClassicalRegister(2) qc1 = QuantumCircuit(q, c) qc2 = QuantumCircuit(q, c) qc2.x(q[0]) qc1.measure(q, c) qc2.measure(q, c) circuits = [qc1, qc2] xvals_dict = {circuits[0].name: 0, circuits[1].name: 1} qobj = compile(circuits, backend) job = backend.run(qobj) result = job.result() yvals, xvals = result.get_qubitpol_vs_xval(2, xvals_dict=xvals_dict) self.assertTrue(np.array_equal(yvals, [[-1, -1], [1, -1]])) self.assertTrue(np.array_equal(xvals, [0, 1]))
def test_average_data(self): """Test average_data.""" backend = get_backend('local_qasm_simulator') q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c, name="qc") qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) shots = 10000 qobj = compile(qc, backend, shots=shots) job = backend.run(qobj) result = job.result() observable = {"00": 1, "11": 1, "01": -1, "10": -1} mean_zz = result.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} mean_zi = result.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} mean_iz = result.average_data("qc", observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1)
def run(shots, qc, cfg, backend=None): if 'url' in cfg.keys(): register(cfg['token'], cfg['url'], cfg['hub'], cfg['group'], cfg['project']) print(available_backends()) if backend is None: backend = cfg['backend'] backend_config = get_backend(backend).configuration backend_coupling = backend_config['coupling_map'] qc_compiled = compile([qc], backend=backend, coupling_map=backend_coupling, seed=0) qc_compiled_qasm = qc_compiled['circuits'][0]['compiled_circuit_qasm'] #print(qc_compiled_qasm) job = execute([qc], backend=backend, shots=shots) result = job.result() return result
def setup_quantum_backend(self, backend='local_statevector_simulator', shots=1024, skip_transpiler=False, noise_params=None, coupling_map=None, initial_layout=None, hpc_params=None, basis_gates=None, max_credits=10, timeout=None, wait=5): """ Setup the quantum backend. Args: backend (str): name of selected backend shots (int): number of shots for the backend skip_transpiler (bool): skip most of the compile steps and produce qobj directly noise_params (dict): the noise setting for simulator coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (dict): initial layout of qubits in mapping hpc_params (dict): HPC simulator parameters basis_gates (str): comma-separated basis gate set to compile to max_credits (int): maximum credits to use timeout (float or None): seconds to wait for job. If None, wait indefinitely. wait (float): seconds between queries Raises: AlgorithmError: set backend with invalid Qconfig """ operational_backends = self.register_and_get_operational_backends( self.qconfig) if self.EQUIVALENT_BACKENDS.get(backend, backend) not in operational_backends: raise AlgorithmError( "This backend '{}' is not operational for the quantum algorithm\ , please check your Qconfig.py, or select any one below: {}". format(backend, operational_backends)) self._backend = backend self._qjob_config = {'timeout': timeout, 'wait': wait} shots = 1 if 'statevector' in backend else shots noise_params = noise_params if 'simulator' in backend else None if backend.startswith('local'): self._qjob_config.pop('wait', None) self.MAX_CIRCUITS_PER_JOB = sys.maxsize my_backend = get_backend(backend) if coupling_map is None: coupling_map = my_backend.configuration['coupling_map'] if basis_gates is None: basis_gates = my_backend.configuration['basis_gates'] self._execute_config = { 'shots': shots, 'skip_transpiler': skip_transpiler, 'config': { "noise_params": noise_params }, 'basis_gates': basis_gates, 'coupling_map': coupling_map, 'initial_layout': initial_layout, 'max_credits': max_credits, 'seed': self._random_seed, 'qobj_id': None, 'hpc': hpc_params } info = "Algorithm: '{}' setup with backend '{}', with following setting:\n {}\n{}".format( self._configuration['name'], my_backend.configuration['name'], self._execute_config, self._qjob_config) logger.info('Qiskit Terra version {}'.format(qiskit_version)) logger.info(info)
# Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Local Backends)") for backend_name in available_backends({'local': True}): backend = get_backend(backend_name) print(backend.status()) my_backend_name = 'local_qasm_simulator' my_backend = get_backend(my_backend_name) print("(Local QASM Simulator configuration) ") pprint.pprint(my_backend.configuration()) print("(Local QASM Simulator calibration) ") pprint.pprint(my_backend.calibration()) print("(Local QASM Simulator parameters) ") pprint.pprint(my_backend.parameters()) # Compiling the job qobj = compile([qc1, qc2], my_backend) # Note: in the near future qobj will become an object # Runing the job
# Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Local Backends)") for backend_name in available_backends({'local': True}): backend = get_backend(backend_name) print(backend.status) my_backend_name = 'local_qasm_simulator' my_backend = get_backend(my_backend_name) print("(Local QASM Simulator configuration) ") pprint.pprint(my_backend.configuration) print("(Local QASM Simulator calibration) ") pprint.pprint(my_backend.calibration) print("(Local QASM Simulator parameters) ") pprint.pprint(my_backend.parameters) # Compiling the job qobj = compile([qc1, qc2], my_backend) # Note: in the near future qobj will become an object
# Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Local Backends)") for backend_name in available_backends({'local': True}): backend = get_backend(backend_name) print(backend.status) my_backend_name = 'local_qasm_simulator' my_backend = get_backend(my_backend_name) print("(Local QASM Simulator configuration) ") pprint.pprint(my_backend.configuration) print("(Local QASM Simulator calibration) ") pprint.pprint(my_backend.calibration) print("(Local QASM Simulator parameters) ") pprint.pprint(my_backend.parameters) # Compiling the job qobj = compile([qc1, qc2], my_backend) # Note: in the near future qobj will become an object # Runing the job
# The backend to use in the simulations. Check available_backends() for all backends backendsim = 'ibmq_qasm_simulator' # The backed to use for the actual experiments (e.g. the chip) backendreal = 'ibmqx4' # Measurement and preparation basis for process tomography meas_basis, prep_basis = 'Pauli', 'Pauli' # Set backend based on run_type if run_type == 's': backendname = backendsim elif run_type == 'r': backendname = backendreal else: print('Error, wrong runtype!') ibmqxbackend = get_backend(backendreal) job_data = [] ################################################################################ # Create tomo set and tomo circuits; put them in the quantum program [Q_program, tomo_set, tomo_circuits] = tomo.create_tomo_circuits(Q_program, circuit_name, q, c, [1, 0], meas_basis, prep_basis) # Execute all the tomo circuits batch_size = int(len(tomo_circuits) / nr_batches) if len(tomo_circuits) % nr_batches != 0: nr_batches += 1 # Add an extra batch if the number of tomo circuits is not divisible by the batch number for i in range(nr_batches): run_circuits = tomo_circuits[ i * batch_size:(i + 1) *
#%% from IBM_Q_Experience.Q_Exp_register import qx_config provider = register(qx_config['APItoken']) #%% #fit_method = 'leastsq' direct = True if direct: run_type = rg.store.load_last()['Type'] circuit_name = rg.store.load_last()['Circuit name'] else: run_type = input('Runtype is (enter as string): ') circuit_name = input('Circuit name is (enter as string): ') if run_type == 's': backend = get_backend('ibmq_qasm_simulator') elif run_type == 'r': backend = get_backend('ibmqx4') #%% [jobids, jobdata] = rg.get_jobids_from_file(direct, circuit_name, run_type) stati = rg.get_status_from_jobids(jobids, printing=True) tomo_set = jobdata['Tomoset'] if 'RUNNING' not in stati: results = rg.get_results_from_jobids(jobids, backend) calibrations = rg.get_calibration_from_jobids(jobids) rg.store.save_results(circuit_name, jobdata['Experiment time'], jobdata['Type'], jobdata['Backend'],
# that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards # their requirements in conditions enabling the security of their # systems and/or data to be ensured and, more generally, to use and # operate it in the same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL-B license and that you accept its terms. # ====================================================================== """Testing the QISKit initialiser.""" import qiskit statevector_backend = qiskit.get_backend('local_statevector_simulator') ############################################################### # Make a quantum program for state initialization. ############################################################### qubit_number = 5 Q_SPECS = { "name": "StatePreparation", "circuits": [ { "name": "initializerCirc", "quantum_registers": [{ "name": "qr", "size": qubit_number }],
def test_local_deprecated(self): """test deprecated local backends are resolved correctly""" old_name = "local_qiskit_simulator" if not _skip_cpp: new_backend = get_backend(old_name) self.assertIsInstance(new_backend, QasmSimulatorCpp)