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 startIBMQ(): global Q, backend # Written to work with versions of IBMQ-Provider both before and after 0.3 IBMQP_Vers=float(IBMQVersion['qiskit-ibmq-provider'][:3]) print('IBMQ Provider v',IBMQP_Vers) print ('Pinging IBM Quantum Experience before start') p=ping('https://api.quantum-computing.ibm.com',1,0.5,True) try: print("requested backend: ",backendparm) except: sleep(0) # specify the simulator as the backend backend='ibmq_qasm_simulator' if p==200: if (IBMQP_Vers > 0.2): # The new authentication technique with provider as the object provider0=IBMQ.load_account() try: Q=provider0.get_backend(backendparm) except: Q=provider0.get_backend(backend) else: interval = 300 else: # The older IBMQ authentication technique IBMQ.load_accounts() try: Q=IBMQ.get_backend(backendparm) except: Q=IBMQ.get_backend(backend) else: interval = 300 else: exit()
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 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 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(), 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 test_autoregister_no_credentials(self): """Test register() with no credentials available.""" with no_file('Qconfig.py'), custom_qiskitrc(), no_envs(): with self.assertRaises(QiskitError) as context_manager: IBMQ.load_accounts() self.assertIn('No IBMQ credentials found', str(context_manager.exception))
def startIBMQ(): #global IBMQ print ('Pinging IBM Quantum Experience before start') p=ping('https://api.quantum-computing.ibm.com',1,0.5,True) if p==200: IBMQ.load_accounts() else: exit()
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 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 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 startIBMQ(): global Q, backend # Written to work with versions of IBMQ-Provider both before and after 0.3 sQPV = IBMQVersion['qiskit-ibmq-provider'] pd = '.' dot1 = [pos for pos, char in enumerate(sQPV) if char == pd][0] dot2 = [pos for pos, char in enumerate(sQPV) if char == pd][1] IBMQP_Vers = float(sQPV[dot1 + 1:dot2]) print('IBMQ Provider v', IBMQP_Vers) if not UseLocal: print('Pinging IBM Quantum Experience before start') p = ping('https://api.quantum-computing.ibm.com', 1, 0.5, True) #p=ping('https://quantum-computing.ibm.com/',1,0.5,True) try: print("requested backend: ", backendparm) except: sleep(0) # specify the simulator as the backend backend = 'ibmq_qasm_simulator' if p == 200: if ( IBMQP_Vers > 2 ): # The new authentication technique with provider as the object provider0 = IBMQ.load_account() try: Q = provider0.get_backend(backendparm) except: Q = provider0.get_backend(backend) else: interval = 300 else: # The older IBMQ authentication technique IBMQ.load_accounts() try: Q = IBMQ.get_backend(backendparm) except: Q = IBMQ.get_backend(backend) else: interval = 300 else: exit() else: # THIS IS THE CASE FOR USING LOCAL SIMULATOR backend = 'local aer qasm_simulator' print("Building ", backend, "with requested attributes...") if not AddNoise: Q = Aer.get_backend('qasm_simulator') else: fake_backend = fake_qc() Q = QasmSimulator.from_backend(fake_backend)
def __init__( self, precision=None, num = 1280, sim=True, noisy=False, noise_only=False, verbose=True ): if precision: self.precision = precision self.num = int(np.floor( 5*8192/self.precision )) else: self.num = num self.precision = int(np.floor( 5*8192/self.num )) q = QuantumRegister(5) c = ClassicalRegister(5) qc = QuantumCircuit(q,c) if not noise_only: qc.h(q) qc.measure(q,c) if sim: backend=Aer.get_backend('qasm_simulator') else: IBMQ.load_accounts() backend=IBMQ.get_backend('ibmq_5_tenerife') if verbose and not sim: print('Sending job to quantum device') try: job = execute(qc,backend,shots=8192,noise_model=get_noise(noisy),memory=True) except: job = execute(qc,backend,shots=8192,memory=True) data = job.result().get_memory() if verbose and not sim: print('Results from device received') full_data = [] for datum in data: full_data += list(datum) self.int_list = [] self.bit_list = [] n = 0 for _ in range(num): bitstring = '' for b in range(self.precision): bitstring += full_data[n] n += 1 self.bit_list.append(bitstring) self.int_list.append( int(bitstring,2) ) self.n = 0
def run_IBMQ(self): """ Run grover's on a real device """ self.grover = self.generate_grover() nqbits = self.oracle.circuit.width() print("Oracle with number of qubits: {}".format(nqbits)) IBMQ.load_accounts() backend = self.find_least_busy(nqbits) quantum_instance = QuantumInstance(backend, shots=self.niter) self.result = self.grover.run(quantum_instance) return self.result['top_measurement'][::-1]
def __init__(self, backend_name: str, monitor: bool = True): """A backend for running circuits on remote IBMQ devices. :param backend_name: name of ibmq device. e.g. `ibmqx4`, `ibmq_16_melbourne`. :type backend_name: str :param monitor: Use IBM job monitor, defaults to True :type monitor: bool, optional :raises ValueError: If no IBMQ account has been set up. """ if len(IBMQ.stored_accounts()) == 0: raise ValueError( 'No IBMQ credentials found on disk. Store some first.') IBMQ.load_accounts() self._backend = IBMQ.get_backend(backend_name) coupling = self._backend.configuration().coupling_map self.architecture = Architecture(coupling) self._monitor = monitor
def run_IBMQ(self): """ Use VQE on a real device to determine ground energy eigenvectors of the hamiltonian """ self.operator, var_form, opt = self.generate_VQE_args() nqbits = self.operator.num_qubits IBMQ.load_accounts() backend = self.find_least_busy(nqbits) quantum_instance = QuantumInstance(backend=backend) vqe = VQE(self.operator, var_form, opt) self.result = vqe.run(quantum_instance) solution = self.extract_solution(self.result, False) return solution
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 __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)
def main(): n = 8 r = 3 qr, cr, qc = preparing_initial_states(n, r) from os import sys choice = int(sys.argv[1]) if choice == 6: permutation_6(qr, qc, n) elif choice == 7: permutation_7(qr, qc, n) elif choice == 8: permutation_8(qr, qc, n) elif choice == 9: permutation_9(qr, qc, n) else: print("Error choice") return print("Choice", choice) print("Drawing") from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, filename='img/test_{0}.png'.format(choice)) print("Preparing execution") # from qiskit import Aer # backend = Aer.get_backend('qasm_simulator') from qiskit import IBMQ IBMQ.load_accounts() backend = IBMQ.get_backend('ibmq_qasm_simulator') from qiskit import execute print("Execute") job = execute(qc, backend, shots=4098) print(job.job_id()) result = job.result() print("Results ready") counts = result.get_counts(qc) print(counts) print(len(counts)) from qiskit.tools.visualization import plot_histogram plot_histogram(counts, )
def get_depth_and_size(self, dir, transpile=True, backend_name=None): # def _get_size_and_depth(self, row): # name = row.name # circ = QuantumCircuit.from_qasm_file(os.path.join(self.res_dir, name)) # row['depth'] = circ.depth() # row['size'] = circ.size() # self.df.parallel_apply(_get_size_and_depth, axis=1) # def _get_size_and_depth(slice): # for row in slice.iterrows(): # name = row.name # circ = QuantumCircuit.from_qasm(os.path.join(self.res_dir, name)) # row['depth'] = circ.depth() # row['size'] = circ.size() # self.df = parallelize_dataframe(self.df, _get_size_and_depth) if backend_name: IBMQ.load_accounts() backend = IBMQ.backends( filters=lambda x: x.name() == backend_name)[0] file_list = get_file_list(dir, '.qasm') file_list_abs = [os.path.join(dir, file) for file in file_list] pool = Pool() print('==Creating circuit list==') # circ_list = pool.map(QuantumCircuit.from_qasm_file, file_list_abs) circ_list = Parallel(n_jobs=cpu_count())( delayed(QuantumCircuit.from_qasm_file)(file) for file in file_list_abs) # pool.close() # pool.join() if transpile: print('==Transpiling!==') TextProgressBar() circ_list = compiler.transpile(circ_list, backend) file_list_pkl = [ os.path.splitext(file)[0] + '.pkl' for file in file_list ] for i in range(len(file_list_pkl)): self.df.loc[file_list_pkl[i], 'depth'] = circ_list[i].depth() self.df.loc[file_list_pkl[i], 'size'] = circ_list[i].size() return
def get_backend(provider_name, backend_name, n_qubits): # logger.debug("real: {0}, online: {1}, backend_name: {2}".format( # args.real, args.online, args.backend_name)) if provider_name == "basicaer": from qiskit import BasicAer provider = BasicAer elif provider_name == "aer": from qiskit import Aer provider = Aer elif provider_name in ("projectqp", "projectqpprovider"): from qiskit_addon_projectq import ProjectQProvider provider = ProjectQProvider() elif provider_name in ("qcgpu", "qcgpuprovider"): from qiskit_qcgpu_provider import QCGPUProvider provider = QCGPUProvider() elif provider_name in ("jku", "jkuprovider"): from qiskit_addon_jku import JKUProvider provider = JKUProvider() elif provider_name in ("ibmq"): from qiskit import IBMQ IBMQ.load_accounts() provider = IBMQ else: raise Exception("Invalid provider {0}".format(provider_name)) # only for real, online execution if backend_name == 'enough' and provider == 'ibmq': from qiskit.providers.ibmq import least_busy large_enough_devices = provider.backends( filters=lambda x: x.configuration( ).n_qubits >= n_qubits and x.configuration().simulator == False) backend = least_busy(large_enough_devices) else: backend = provider.get_backend(backend_name) if backend.configuration().n_qubits < n_qubits: raise Exception( "Backend {0} on provider {1} has only {2} qubits, while {3} are needed." .format(backend.name(), backend.provider(), backend.configuration().n_qubits, n_qubits)) return backend
def qrng(phys_or_sim, size=16, qubits=4, max_credits=3): '''Return a random size bit integer''' if phys_or_sim in ['p', "phys", "physical"]: IBMQ.load_accounts() large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits >= qubits and not x.configuration().simulator) backend = least_busy(large_enough_devices) #print("Selected", backend.name()) elif phys_or_sim in ['s', "sim", "simulated"]: backend = aer.get_backend('qasm_simulator') shots = size//qubits # quantum register with 8 qubits qreg = QuantumRegister(qubits, 'q') creg = ClassicalRegister(qubits, 'c') #print("created registers") # quantum circuit acting on q circ = QuantumCircuit(qreg, creg) for qubit in qreg: circ.h(qubit) for i in range(qubits): circ.measure(qreg[i], creg[i]) job = execute(circ, backend, shots=shots, max_credits=max_credits) #job_monitor(job) result = job.result() counts = result.get_counts(circ) #print(counts) num = "" for i in list((counts.keys())): num += i return int(num, 2)
def ibmcomputer(): from qiskit import IBMQ IBMQ.load_accounts() print("Available backends:") IBMQ.backends() from qiskit.providers.ibmq import least_busy large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration( ).n_qubits > 3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print("The best backend is " + backend.name()) from qiskit.tools.monitor import job_monitor shots = 50 * n max_credits = 3 job_exp = execute(circ, backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) res = job_exp.result() answer = res.get_counts(circ) plot_histogram(answer)
def get_scores(game, s, simulate=True, noisy=False): score = [0] * 5 #Check whether it's valid game if not game or not check_game(game, s): return score #Initialisation q = QuantumRegister(s) c = ClassicalRegister(s) qc = QuantumCircuit(q, c) #Shuffle players' qubits qbts = [i for i in range(0, s)] shuffle(qbts) pq = {} for p in range(0, s): pq[p] = qbts[p] #Parse game string and construct quantum circuit i = 0 while i < len(game): g = game[i].upper() if g == "H": p = pq[int(game[i + 1]) - 1] qc.h(q[p]) i += 2 elif g == "I": p = pq[int(game[i + 1]) - 1] qc.iden(q[p]) i += 2 elif g == "X": p = pq[int(game[i + 1]) - 1] qc.x(q[p]) i += 2 elif g == "Y": p = pq[int(game[i + 1]) - 1] qc.y(q[p]) i += 2 elif g == "Z": p = pq[int(game[i + 1]) - 1] qc.z(q[p]) i += 2 elif g == "C": p1 = pq[int(game[i + 1]) - 1] p2 = pq[int(game[i + 2]) - 1] qc.cx(q[p1], q[p2]) i += 3 elif g == "S": p1 = pq[int(game[i + 1]) - 1] p2 = pq[int(game[i + 2]) - 1] qc.swap(q[p1], q[p2]) i += 3 else: print("Error", g) #Measurement qc.measure(q, c) if simulate: if noisy: #Load IBMQ credentials IBMQ.load_accounts() device = IBMQ.get_backend('ibmqx4') #4-qubit IBMQ noise_model = noise.device.basic_device_noise_model( device.properties()) backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend, noise_model=noise_model) else: backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend, noise_model=None) else: #Load IBMQ credentials IBMQ.load_accounts() backend = IBMQ.get_backend('ibmqx4') #4-qubit IBMQ job_sim = execute(qc, backend) sim_result = job_sim.result() counts = sim_result.get_counts(qc) #Compute players' scores score = [0] * 5 for result in counts: c = counts[result] for p in range(0, s): if result[s - 1 - pq[p]] == "1": score[p] += c return score
from qiskit import IBMQ from qiskit import BasicAer as Aer from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy from ipywidgets import widgets from IPython.display import display, clear_output try: IBMQ.load_accounts() except: pass class run_game(): # Implements a puzzle, which is defined by the given inputs. def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times.
def three_part_POVM(): # angle parameters for the 1st and 2nd panel tita1 = np.arccos(np.sqrt(2 / 3)) tita2 = pi / 2 tita3 = 0 tita4 = pi / 2 # Ui and Uii are implemented as controled rotations as well. # In our example Ui = I, so no action needed # For Uii required y rotation at -pi/2 rads alpha_ui = 0 alpha_uii = -pi / 2 # Create a Quantum Register with 4 qubits. q = QuantumRegister(3, 'q') # Create a Quantum Circuit acting on the q register qc = QuantumCircuit(q) # qc.u3(0, 0, 0, q[0]) # INITIAL STATE! # Apply Ui # qc.u3(alpha_ui, 0, 0, q[0]) # for the sake of clarity # Apply the 1st AnP panel first_AP_module_new(qc, q, tita1, tita2, 0, 0) # Apply Uii, require a single qubit controled rotation nCU1('y', alpha_uii, qc, [q[1]], q[0]) # Apply 2nd Ahnert Payne POVM module second_AP_module_new(qc, q, tita3, tita4) # KRAUS OPERATORS kraus = 1 if kraus: # perform T2 on p2 branch, correspond to 10 value of q1q2 qc.x(q[2]) # nCU1('y', 2*pi/3, qc, [q[1], q[2]], q[0] ) nCU1('y', 2 * pi / 3, qc, [q[1], q[2]], q[0]) qc.x(q[2]) # perform T3 on p3 branch, correspond to 11 value of q1q2 # nCU1('y', -2*pi/3, qc, [q[1], q[2]], q[0] ) # changee??? nCU1('y', 7 * pi / 3, qc, [q[1], q[2]], q[0]) # 11->01 qc.cx(q[2], q[1]) # Add Measurements # Create a Classical Register with 3 bits. c = ClassicalRegister(3, 'c') # Create a Quantum Circuit meas = QuantumCircuit(q, c) meas.barrier(q) # 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()) # Hello there # <<<<<<<<<<< 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)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit import Aer, IBMQ # import the Aer and IBMQ providers from qiskit.providers.aer import noise # import Aer noise models # Choose a real device to simulate IBMQ.load_accounts( ) # this wont work, fix later by adding the API token on account device = IBMQ.get_backend('ibmq_16_melbourne') properties = device.properties() coupling_map = device.configuration().coupling_map # Generate an Aer noise model for device noise_model = noise.device.basic_device_noise_model(properties) basis_gates = noise_model.basis_gates # Generate a quantum circuit q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Perform noisy simulation backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates)
""" Example used in the README. In this example a Bell state is made. """ # Import the Qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError from qiskit import execute, IBMQ, BasicAer from qiskit.backends.ibmq import least_busy # Authenticate for access to remote backends try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) # Create a Classical Register with 2 bits. c = ClassicalRegister(2) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1])
def main(): args = anki_vector.util.parse_command_args() from anki_vector.util import degrees, Pose # Create a Robot object robot = anki_vector.Robot() # Connect to the Robot robot.connect() def image2screen(image_file_name): current_directory = os.path.dirname(os.path.realpath(__file__)) image_path = os.path.join(current_directory, "images", image_file_name) # Load an image image_file = Image.open(image_path) # Convert the image to the format used by the Screen print("Display image on Vector's face...") screen_data = anki_vector.screen.convert_image_to_screen_data( image_file) robot.conn.release_control() time.sleep(1) robot.conn.request_control() robot.screen.set_screen_with_image_data(screen_data, 10.0, interrupt_running=True) robot.behavior.set_head_angle(MAX_HEAD_ANGLE) time.sleep(3) robot.behavior.set_head_angle(Angle(0.0)) robot.world.disconnect_cube() robot.behavior.drive_off_charger() robot.say_text("I wonder if I will find my true love today?") print("Connecting to a cube...") robot.world.connect_cube() robot.say_text( "I got it! I'll ask a quantum eight ball on an IBM quantum computer.") image2screen("qiskit-logo.png") if robot.world.connected_light_cube: print("Begin cube docking...") dock_response = robot.behavior.dock_with_cube( robot.world.connected_light_cube, num_retries=4) if dock_response: docking_result = dock_response.result if docking_result: if docking_result.code != anki_vector.messaging.protocol.ActionResult.ACTION_RESULT_SUCCESS: print("Cube docking failed with code {0} ({1})".format( str(docking_result).rstrip('\n\r'), docking_result.code)) else: print("Cube docking failed.") robot.world.disconnect_cube() # Authenticate for access to remote backends try: IBMQ.load_accounts() except: print( """WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""" ) # Set up quantum register and classical register for 1 qubit q = QuantumRegister(1) c = ClassicalRegister(1) # Create a quantum circuit qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) def answer(result): for key in result.keys(): state = key print('The Quantum 8-ball says:') robot.say_text("The Quantum 8-ball says, ") if state == '1': image2screen("ket-1.png") print('Yes - definitely.') robot.say_text("Yes - definitely.") robot.anim.play_animation('anim_eyepose_happy') robot.anim.play_animation( 'anim_eyecontact_giggle_01_head_angle_20') robot.anim.play_animation('anim_reacttocliff_edge_01') robot.say_text('Fist bump!') robot.anim.play_animation('anim_fistbump_requestoncelong_01') robot.say_text('Later! Gotta go find my true love!') robot.behavior.set_lift_height(0.0) robot.behavior.drive_on_charger() elif state == '0': image2screen("ket-0.png") print('My reply is no.') robot.say_text("My reply is no.") robot.behavior.set_head_angle(MIN_HEAD_ANGLE) robot.anim.play_animation('anim_eyepose_sad_down') robot.say_text("I guess I should just go back home") robot.behavior.drive_on_charger() # Run the circuit on an IBM quantum simulator # Note: To run circuits on an IBM quantum computer, see instructions # in the Jupyter notebook of the following Qiskit tutorial: # https://github.com/Qiskit/qiskit-tutorials/blob/master/qiskit/basics/getting_started_with_qiskit_terra.ipynb job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1) result = job.result().get_counts(qc) answer(result) # Show the results print("result: ", result) # Disconnect from Vector robot.disconnect()
def fetchBackend(): # IBM Q backend IBMQ.load_accounts() backend = providers.ibmq.least_busy(IBMQ.backends(simulator=False)) print("Using the least busy device:", backend.name()) return backend
'seed': 10598, 'local': False, 'qbits': 5, 'records': 10 } if config['local']: config['server'] = 'qasm_simulator' else: config['qbits'] = servers[config['server']] data = json.load(open('data' + str(config['qbits']) + '.json', 'r')) IBMQ.save_account(config['token']) if config['local']: IBMQ.load_accounts(hub=None) feature_map = SecondOrderExpansion(feature_dimension=config['qbits'], depth=config['depth'], entanglement=config['entanglement']) qsvm = QSVM(feature_map, data["train"], data["test"]) backend = BasicAer.get_backend(config['server']) quantum_instance = QuantumInstance(backend, shots=config['shots'], seed_transpiler=config['seed']) result = qsvm.run(quantum_instance) print(result) else: IBMQ.load_accounts(hub=None) feature_map = SecondOrderExpansion(feature_dimension=config['qbits'], depth=config['depth'], entanglement=config['entanglement'])