def test_run_device(self, qe_token, qe_url): 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 qc_solver(h_qop, num_spin_orbitals, num_particles, map_type, \ qubit_reduction, aux_qops=None): # backends = Aer.backends() backends = IBMQ.backends(simulator=False) print(backends) # backend = IBMQ.get_backend('ibmq_qasm_simulator') # backend = IBMQ.get_backend('ibmq_16_melbourne') # backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') # setup COBYLA optimizer max_eval = 1000 cobyla = COBYLA(maxiter=max_eval) # setup hartreeFock state hf_state = HartreeFock(h_qop.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction) # setup UCCSD variational form var_form = UCCSD(h_qop.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, active_occupied=[0], active_unoccupied=[0], initial_state=hf_state, qubit_mapping=map_type, two_qubit_reduction=qubit_reduction, num_time_slices=1) # setup VQE vqe = VQE(h_qop, var_form, cobyla, operator_mode='matrix', \ aux_operators=aux_qops) quantum_instance = QuantumInstance(backend=backend, shots=1024, max_credits=10) ret = vqe.run(quantum_instance) print(ret['aux_ops']) print('The computed ground state energy is: {:.12f}'.format(\ ret['eigvals'][0]))
def main(): d = input("Do you want to play on a real device? (y/n)\n") if (d == "y"): try: IBMQ.load_accounts() except: token = input( "Could not find IBM Q API token. Please generate one at https://quantumexperience.ng.bluemix.net/qx/account/advanced and paste it here: " ) try: IBMQ.save_account(token) IBMQ.load_accounts() except: print( "Could not load API Token, please check your token again and rerun this program." ) exit() device = least_busy(IBMQ.backends(simulator=False)) # device = 'ibmqx2' else: device = BasicAer.get_backend('qasm_simulator') # Read this as shipPos[player][ship] = position of player's ship shipPos = [[], []] for i in range(2): for j in range(3): setShipPosition(i, j, shipPos) playGame(device, shipPos)
def listRemoteBackends(self, apiToken, url, hub=None, group=None, project=None): if (version.parse(__version__) >= version.parse("0.6") and (version.parse(__version__) <= version.parse("0.7"))): if (hub is None or group is None or project is None): IBMQ.enable_account(apiToken, url) else: IBMQ.enable_account(apiToken, url=url, hub=hub, group=group, project=project) backs = [backend.name() for backend in IBMQ.backends()] else: raise QiskitUnsupportedVersion( 'Qiskit-terra version must be v0.6 or v0.7') return backs
def get_backend(local=False): if local: return Aer.get_backend('qasm_simulator_py') IBMQ.load_accounts() available_backends = IBMQ.backends(operational=True, simulator=False) backend = least_busy(available_backends) return backend
def get_appropriate_backend(n, real, online, backend_name): # Online, real or simuator? if (not online): global Aer from qiskit import Aer max_credits = 10 shots = 4098 print("Local simulator backend") backend = Aer.get_backend('qasm_simulator') # list of online devices: ibmq_qasm_simulator, ibmqx2, ibmqx4, ibmqx5, ibmq_16_melbourne else: global IBMQ from qiskit import IBMQ print("Online {0} backend".format("real" if real else "simulator")) max_credits = 3 shots = 4098 import Qconfig IBMQ.load_accounts() if (backend_name is not None): backend = IBMQ.get_backend(backend_name) else: large_enough_devices = IBMQ.backends( filters=lambda x: x.configuration()['n_qubits'] >= n and x.configuration()[ 'simulator'] == (not real) ) backend = least_busy(large_enough_devices) print("Backend name is {0}; max_credits = {1}, shots = {2}".format( backend, max_credits, shots)) return backend, max_credits, shots
def listRemoteBackends(self, apiToken, url, hub=None, group=None, project=None): if (version.parse(__version__) > version.parse("0.5") and version.parse(__version__) < version.parse("0.6")): if (hub is None or group is None or project is None): register(apiToken, url) else: register(apiToken, url, hub, group, project) backs = available_backends({'local': False}) elif (version.parse(__version__) > version.parse("0.6")): if (hub is None or group is None or project is None): IBMQ.enable_account(apiToken, url) else: IBMQ.enable_account(apiToken, url=url, hub=hub, group=group, project=project) backs = [backend.name() for backend in IBMQ.backends()] else: raise QiskitUnsupportedVersion( 'Qiskit-terra version must be v0.5 or v0.6') return backs
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_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 rippleAdder(val1: int, val2: int, draw: bool = False, simulate: bool = True) -> int: x = bin(val1)[2:] y = bin(val2)[2:] if len(x) > len(y): while len(y) != len(x): y = "0" + y else: while len(x) != len(y): x = "0" + x circuit = storeValues(x, y) for i in range(len(x)): fullAdder(i, len(x)+i, len(x)+len(y)+i, len(x)+len(y)+i+1, circuit) circuit.barrier() for i in range(len(x)+1): circuit.measure([(len(x)*2)+i], [i]) if simulate: simulator = Aer.get_backend("qasm_simulator") result = execute(circuit, backend=simulator, shots=1).result() else: provider = IBMQ.load_account() backend = least_busy(IBMQ.backends()) job = execute(circuit, backend=backend, shots=1) job_monitor(job) result = job.result() if draw: circuit.draw() return int(list(result.get_counts().keys())[0], 2)
def test_remote_backends_exist(self, qe_token, qe_url): """Test if there are remote backends. If all correct some should exists. """ IBMQ.enable_account(qe_token, qe_url) remotes = IBMQ.backends() self.assertTrue(len(remotes) > 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.enable_account(qe_token, qe_url) remotes = IBMQ.backends(simulator=True) self.assertTrue(remotes)
def find_least_busy(n_qubits=5): fltr = lambda x: x.configuration( ).n_qubits > n_qubits and not x.configuration().simulator large_enough_devices = IBMQ.backends(filters=fltr) backend = least_busy(large_enough_devices) print("Using backend: " + backend.name()) return backend
def ask_for_device(): d = input("Do you want to play on a real quantum device? (y/n)\n").upper() if (d == "Y"): token = input("Paste your API token and press [Enter]:") # IBMQ.save_account('6a20a2b3071f22a06d536a9e9aad965d90d917ffc34b438a4938f3d6b8c427637b47bcc9170524b006e603cf3277c1192fb3b68665f696ca510d34697de0ff6f') IBMQ.save_account(token) IBMQ.load_accounts() ibmq_backends = IBMQ.backends() print("Remote backends: ", ibmq_backends) device = least_busy(IBMQ.backends(simulator=False)) print('quantum_backend: ', device) else: device = BasicAer.get_backend( 'qasm_simulator') # otherwise, we use a simulator return device
def test_remote_backends_exist_real_device(self, qe_token, qe_url): """Test if there are remote backends that are devices. If all correct some should exists. """ IBMQ.use_account(qe_token, qe_url) remotes = IBMQ.backends(simulator=False) self.assertTrue(remotes)
def available_backends(filters=None, compact=True): """ Return names of backends that are available in the SDK, optionally filtering them based on their capabilities. Note: In order for this function to return online backends, a connection with an online backend provider needs to be established by calling the `register()` function. Note: If two or more providers have backends with the same name, those names will be shown only once. To disambiguate and choose a backend from a specific provider, get the backend from that specific provider. Example:: p1 = register(token1) p2 = register(token2) execute(circuit, p1.get_backend('ibmq_5_tenerife')) execute(circuit, p2.get_backend('ibmq_5_tenerife')) Args: filters (dict or callable): filtering conditions. compact (bool): group backend names based on compact group names. Returns: list[str]: the names of the available backends. .. deprecated:: 0.6+ After 0.6, this function is deprecated. Please use the methods in `qiskit.IBMQ` and `qiskit.backends.local.Aer` instead (`backends()`). """ warnings.warn( 'available_backends() will be deprecated after 0.6. Please ' 'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() ' 'method instead.', DeprecationWarning) if isinstance(filters, dict): kwargs = filters else: kwargs = {'filters': filters} ibmq_names = [backend.name() for backend in IBMQ.backends(**kwargs)] aer_names = [backend.name() for backend in Aer.backends(**kwargs)] if compact: # Hack for backwards compatibility: reverse the groups for local. aer_groups = Aer.grouped_backend_names() reversed_aer_groups = {} for group, items in aer_groups.items(): for alias in items: reversed_aer_groups[alias] = group aer_names = list(set(reversed_aer_groups[name] for name in aer_names)) return ibmq_names + aer_names
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 backend_monitor(backend)
def online_real(qc): from qiskit import IBMQ from qiskit.backends.ibmq import least_busy IBMQ.load_accounts() large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()[ 'n_qubits'] > 2 and not x.configuration()['simulator']) backend = least_busy(large_enough_devices) return backend
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_get_jobs_filter_job_status(self, qe_token, qe_url): 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 i, job in enumerate(job_list): self.log.info('match #%d: %s', i, job.result().status) self.assertTrue(job.status() is JobStatus.DONE)
def execute(): # Compile and run on a real device backend try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running jobs # showing results except: print("All devices are currently unavailable.")
def two_part_POVM(): # Create a Quantum Register with 3 qubits. q = QuantumRegister(2, 'q') # Create a Quantum Circuit acting on the q register qc = QuantumCircuit(q) # Add waiting time for i in range(1000): qc.iden(q) # prepare the input state (the input state will be represented by qubit 0) qc.u3(pi * 2 / 3, 0, 0, q[0]) # qc.barrier(q) # Apply the POVM first_AP_module_new(qc, q, pi / 4, pi / 4, 0, 0) # Add Measurements # Create a Classical Register with 3 bits. c = ClassicalRegister(2, 'c') # Create a Quantum Circuit meas = QuantumCircuit(q, c) # map the quantum measurement to the classical bits meas.measure(q, c) # The Qiskit circuit object supports composition using # the addition operator. qc = qc + meas # IBMQ.save_account(token) IBMQ.load_accounts() shots = 8192 # Number of shots to run the program (experiment); maximum is 8192 shots. max_credits = 10 # Maximum number of credits to spend on executions. n_qubits = 3 backend = IBMQ.backends(name='ibmqx4')[0] print("The best backend is " + backend.name()) # <<<<<<<<<<< EXECUTING real experiment >>>>>>>>>>>>>> run = 1 # keep 0 untill you want to run the experiment, to avoid running by mistake. It is slow and cost credits! if run: job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits) result = job_exp.result() counts = result.get_counts(qc) print(counts)
def test_remote_backend_status(self, qe_token, qe_url): """Test backend_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) IBMQ.enable_account(qe_token, qe_url) for backend in IBMQ.backends(): status = backend.status() jsonschema.validate(status.to_dict(), schema)
def test_get_jobs_filter_date(self, qe_token, qe_url): IBMQ.enable_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')
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_remote_backend_configuration(self, qe_token, qe_url): """Test backend configuration.""" 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_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 StartQuantum(realMachine, userHash): # Quantum Register qr = QuantumRegister(2) # Classical Register cr = ClassicalRegister(2) # Circuit qc = QuantumCircuit(qr, cr) print("Circuit Set Succesfully") if realMachine: # You should enter your credentials in Python beforehand # To do that, try importing IBMQ and then IBMQ.save_account(YOUR_TOKEN) IBMQ.load_accounts() print("Account Loaded..") backend = least_busy(IBMQ.backends(simulator=False)) else: backend = BasicAer.get_backend('qasm_simulator') print("Starting circuit design..") # Super position with Hadamard gates qc.h(qr[1]) qc.h(qr[0]) # Set outcome returned from Oracle function based on user input # We don't know what oracle function does. It returns 0,1,2,3 based on result. oracleResult = oracle(userHash) QuantumHelper.OutcomeSetter(oracleResult, qc, qr) # Quantum inversion step. Real power of Grover's Algorithm qc.h(qr[0]) qc.h(qr[1]) qc.x(qr[1]) qc.x(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[1]) qc.x(qr[1]) qc.x(qr[0]) qc.h(qr[0]) qc.h(qr[1]) # End of Quantum Inversion # We can measure now qc.measure(qr, cr) # Executing our circuit.. print("Executing design..") results = execute(qc, backend=backend, shots=1).result() resultPass = passList[int(list((results.get_counts(qc)).keys())[0], 2)] resStr = f'Quantum Gods have spoken. Your passwords was {resultPass}\n Found in 1 shot. \n Traditional computer would find this in {oracleResult+1} shot' return resStr
def GetSpecificIBMQDevice(name): if not ibmq_login.login(): return backends = IBMQ.backends(name=name) if (len(backends) == 0): print("No backend matching name ', name, ' found", sep="") return if (len(backends) > 1): print("More than one backend with matching name found") return return backends[0]
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)