def main(): parser = argparse.ArgumentParser() parser.add_argument('--apiToken') parser.add_argument('--url', nargs='?', default='https://quantumexperience.ng.bluemix.net/api') parser.add_argument('--hub', nargs='?', default=None) parser.add_argument('--group', nargs='?', default=None) parser.add_argument('--project', nargs='?', default=None) args = vars(parser.parse_args()) if (args['url'] is None): args['url'] = 'https://quantumexperience.ng.bluemix.net/api' if (args['hub'] is None) or (args['group'] is None) or (args['project'] is None): api = IBMQuantumExperience(args['apiToken'], {'url': args['url']}) register(args['apiToken'], args['url']) else: api = IBMQuantumExperience(args['apiToken'], { 'url': args['url'], 'hub': args['hub'], 'group': args['group'], 'project': args['project']}) register(args['apiToken'], args['url'], args['hub'], args['group'], args['project']) backs = available_backends() for back in backs: try: back_status = api.backend_status(back) print(json.dumps(back_status, indent=2, sort_keys=True)) except: pass
def setup(self): need_token = self.use_actual_hardware or not self.run_locally if need_token: if self.ibm_qe_api_token is None: self.ibm_qe_api_token = getpass.getpass( 'Please input your token and hit enter: ') self.qx_config = { 'APItoken': self.ibm_qe_api_token, 'url': 'https://quantumexperience.ng.bluemix.net/api' } try: print('registering API token...') register(self.qx_config['APItoken'], self.qx_config['url']) print('\nYou have access to great power!') print(available_backends({'local': False, 'simulator': False})) except: print('Something went wrong.\nDid you enter a correct token?') exit() # If no backend is requested, find the least busy one if self.qiskit_backend is None: self.qiskit_backend = least_busy( available_backends({ 'simulator': (not self.use_actual_hardware), 'local': self.run_locally })) print('available_backends: {}'.format(available_backends())) print('Using simulator backend: ' + self.qiskit_backend)
def configure(Qconfig_path,Qconfig_name): import time,sys,getpass from qiskit import register try: sys.path.append(Qconfig_path) Qconfig = __import__(Qconfig_name) qx_config = { "APItoken": Qconfig.APItoken, "url" : Qconfig.config['url'], "hub" : Qconfig.config['hub'], "group" : Qconfig.config['group'], "project" : Qconfig.config['project'] } print('Qconfig loaded from %s. ' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url" : "https://quantumexperience.ng.bluemix.net/api", "hub" : None, "group" : None, "project" : None, } print("Qconfig not found. Loaded from user input") register(qx_config['APItoken'],qx_config['url'],qx_config['hub'],qx_config['group'],qx_config['project'])
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 setUp(self): super().setUp() qiskit.register(QE_TOKEN, QE_URL, hub=QE_HUB, group=QE_GROUP, project=QE_PROJECT) self.backend = 'ibmqx_qasm_simulator'
def _set_api(token, config): api = IBMQuantumExperience(token=token, config=config) qiskit.register(token=token, url=config.get('url'), hub=config.get('hub'), group=config.get('group'), project=config.get('project')) return api
def IBMQ_register(): try: register(Qconfig.APItoken, Qconfig.config['url']) print("Successfully connected to IBMQ.") except ConnectionError as e: print( "{}\n\nFailed to connect to IBMQ - only local simulations are possible." .format(e))
def qis_module_init(): if IBM_BACKEND: QX_TOKEN = APItoken QX_URL = "https://quantumexperience.ng.bluemix.net/api" # Authenticate with the IBM Q API in order to use online devices. # You need the API Token and the QX URL. register(QX_TOKEN, QX_URL)
def setUp(self): super().setUp() qiskit.register(QE_TOKEN, QE_URL, hub=QE_HUB, group=QE_GROUP, project=QE_PROJECT) # TODO: FIXME: Change this backend name when changed in IBM-Q self.backend = 'ibmqx_qasm_simulator'
def backends(qconsole=False): key = 'qconsole' if qconsole else 'qx' token = Qconfig.APItoken[key] config = Qconfig.config[key] url = config.get('url', None) hub = config.get('hub', None) group = config.get('group', None) project = config.get('project', None) register(token, url, hub, group, project) return available_backends()
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_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_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 __init__(self, backend=None, shots=1024): try: register(Qconfig.APItoken, Qconfig.config['url']) print("Successfully connected to IBMQ.") except ConnectionError as e: print( "{}\n\nFailed to connect to IBMQ - only local simulations are possible." .format(e)) self.backend = backend self.shots = shots self.register_initialised = False self.qc_initialised = False self.coupling_map = False self.results = False
def use_sympy_backends(): """ Usage examples for the Sympy simulators """ # register with the SympyProvider to get access to its simulators register(provider_class=SympyProvider) q_circuit = load_qasm_file('simple.qasm') # sympy statevector simulator result = execute(q_circuit, backend='sympy_statevector_simulator').result() print("final quantum amplitude vector: ") print(result.get_statevector(q_circuit)) # sympy unitary simulator result = execute([q_circuit], backend='sympy_unitary_simulator').result() print("\nunitary matrix of the circuit: ") print(result.get_unitary(q_circuit))
def test_store_credentials(self): """Test storing credentials and using them for autoregister.""" with no_file('Qconfig.py'), no_envs(), custom_qiskitrc(), mock_ibmq_provider(): qiskit.wrapper.store_credentials('QISKITRC_TOKEN', proxies={'http': 'foo'}) provider = qiskit.register() self.assertEqual(provider._token, 'QISKITRC_TOKEN') self.assertEqual(provider._proxies, {'http': 'foo'})
def register_program(): try: import sys sys.path.append('../') import Qconfig qx_config = { 'APItoken': Qconfig.APItoken, 'url': Qconfig.config['url'] } except Exception as e: qx_config = { 'APItoken': '04ff39f24fe6d848b2c02ceccd1e1913e5243c3d5e723acc793071097de8be357baa25c319a761c202d3a024b55c04265e5f4c18914757b9fceff112997a2bdb', 'url': 'https://quantumexperience.ng.bluemix.net/api' } #Setup API register(qx_config['APItoken'], qx_config['url'])
def signIn(): try: import sys sys.path.append("../") import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url'] } register(qx_config['APItoken'], qx_config['url']) except Exception as e: print(e) APIToken = getpass.getpass('\nPlease enter your token and press enter') qx_config = { "APItoken": APIToken, "url": 'https://quantumexperience.ng.bluemix.net/api' } register(qx_config['APItoken'], qx_config['url']) print(available_backends())
def add(first, second, n): pie = math.pi a = QuantumRegister(n + 1, "a") b = QuantumRegister(n + 1, "b") cl = ClassicalRegister(n + 1, "cl") qc = QuantumCircuit(a, b, cl, name="qc") #Flip the corresponding qubit in register a if a bit in the string #first is a 1 for i in range(0, n): if first[i] == "1": qc.x(a[n - (i + 1)]) #Flip the corresponding qubit in register b if a bit in the string #second is a 1 for i in range(0, n): if second[i] == "1": qc.x(b[n - (i + 1)]) #Compute the Fourier transform of register a for i in range(0, n + 1): createInputState(qc, a, n - i, pie) #Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> #to |F(ψ(reg_a+reg_b))> for i in range(0, n + 1): evolveQFTState(qc, a, b, n - i, pie) #Compute the inverse Fourier transform of register a for i in range(0, n + 1): inverseQFT(qc, a, i, pie) for i in range(0, n + 1): qc.measure(a[i], cl[i]) print(qc.qasm()) #Import config file and set API Token and url import Qconfig register(Qconfig.APIToken, Qconfig.config['url']) #Select backend and execute job result = execute(qc, backend='ibmq_qasm_simulator', shots=256).result() counts = result.get_counts("qc") print(counts) #Select result with maximum probabilities output = max(counts.items(), key=operator.itemgetter(1))[0] print(output)
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 main(): warnings.simplefilter('ignore') parser = argparse.ArgumentParser() parser.add_argument('--apiToken') parser.add_argument('--url', nargs='?', default='https://quantumexperience.ng.bluemix.net/api') parser.add_argument('--hub', nargs='?', default=None) parser.add_argument('--group', nargs='?', default=None) parser.add_argument('--project', nargs='?', default=None) parser.add_argument('--status', default=False) args = vars(parser.parse_args()) if (args['url'] is None): args['url'] = 'https://quantumexperience.ng.bluemix.net/api' if (args['hub'] is None) or (args['group'] is None) or (args['project'] is None): register(args['apiToken'], args['url']) else: register(args['apiToken'], args['url'], args['hub'], args['group'], args['project']) backs = available_backends({'local': False}) if str(args['status']) == "True": statusDevices = [] for back in backs: fullInfoBack = createDeviceStatus(back) statusDevices.append(fullInfoBack) print(json.dumps(statusDevices, indent=2, sort_keys=True)) else: print(json.dumps(backs, indent=2, sort_keys=True))
def init(): print('') sim = 0 for i in range(len(sys.argv)): if (sys.argv[i] == '-s'): print('The circuit will be running on a simulator.') sim = 1 # Get the user's IBM Q Experience API token if (sim == 0): print("Now attempting to get you connected to the IBM Q Experience :", end='') APItoken = input("Please enter your API token : ") qx_config = { "APItoken": APItoken, "url": "https://quantumexperience.ng.bluemix.net/api" } try: register(qx_config['APItoken'], qx_config['url']) print(color.OKGREEN, 'You have access to great power !', color.ENDC) except: print(color.FAIL, 'Something went wrong, is your token correct?', color.ENDC) return (sim)
import math # APItoken = getpass.getpass('Please input your token and hit enter: ') # qx_config = { # "APItoken": APItoken, # "url": "https://quantumexperience.ng.bluemix.net/api"} # print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url": "https://quantumexperience.ng.bluemix.net/api" } try: register(qx_config['APItoken'], qx_config['url']) print('\nYou have access to great power!') print(available_backends({'local': False, 'simulator': False})) except: print('Something went wrong.\nDid you enter a correct token?') # backend = least_busy(available_backends({'simulator': False, 'local': False})) # print("The least busy backend is " + backend) ''' using load_random from Iris.py to obtain some training and test examples for example: sample_train array([[-0.99407732, -0.10867513, 0. ], [-0.30654501, 0.95185616, 0. ], [-0.92072409, -0.39021423, 1. ],
In QISKit 0.6 we will be working on a pass manager for level 2+ users Note: if you have only cloned the QISKit repository but not used `pip install`, the examples only work from the root directory. """ import pprint # Import the QISKit modules from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError, QuantumJob from qiskit import available_backends, compile, register, get_backend try: import Qconfig register(Qconfig.APItoken, Qconfig.config['url']) except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a Qconfig.py file with your personal token? For now, there's only access to local simulator backends...""") 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'])
Example used in the readme. In this example a Bell state is made """ import sys import os from pprint import pprint # so we need a relative position from this file path. # TODO: Relative imports for intra-package imports are highly discouraged. # http://stackoverflow.com/a/7506006 sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from qiskit import QuantumProgram, QISKitError, available_backends, register try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: offline = True print("""WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator""") # Running this block before registering quietly returns a list of local-only simulators # print("The backends available for use are:") backends = available_backends() pprint(backends) print("\n")
import time import matplotlib.pyplot as plt import numpy as np import sys import pandas as pd import Qconfig from tqdm import tqdm from random import randint, choice, uniform from math import ceil from statistics import stdev, mean from skopt import gbrt_minimize, dummy_minimize, forest_minimize, gp_minimize from qiskit import register, available_backends, QuantumCircuit, QuantumRegister, ClassicalRegister, execute register(Qconfig.APItoken, Qconfig.config["url"]) pbar = None DEBUG = False def debug(string): if DEBUG: sys.stdout.write(string) sys.stdout.flush() # ### Classical Stage: # # In the classical stage, two parameters gamma and beta are randomly chosen and fed into the quantum computer. The quantum computer returns an expectation value to the classical computer based on those two parameters. Based on what expectation values it has seen and what it has now, the classical computer alters the parameters to optimize the cost function in aim for a minimum expectation value. This repeats until the classical computer reaches a local minimum. # In[2]:
# Simulation or real experimemt? 's' for simulation, 'r' for real run_type = 'r' reg = False # Set to true to register at IBM notes = '' # Optional notes to be stored in the datafile maximum_credits = 8 # Maximum number of credits nr_batches = 1 # Tries 6 batches, if total number of circuits is not divisible adds one extra batch with the leftovers ############################################################################### # Register at IBM Quantum Experience using token if reg == True: from IBM_Q_Experience.Q_Exp_register import qx_config register(qx_config['APItoken']) # Import Quantum program of desired circuit from Circuits.circuit_hadamard import Q_program, q, c circuit_name = Q_program.get_circuit_names()[0] ############################################################################### # Set number of shots, timeout, measurement- and preperation basis and backend shots = 200 # shots for every circuit # timeout = 500000 # timeout in seconds before execution halts. This is the per-batch timeout, so total runtime <500*(nr_batches+1) seconds # 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'
# Import the QISKit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, register import Qconfig # Set your API Token. # You can get it from https://quantumexperience.ng.bluemix.net/qx/account, # looking for "Personal Access Token" section. QX_TOKEN = Qconfig.APItoken QX_URL = Qconfig.config["url"] # Authenticate with the IBM Q API in order to use online devices. # You need the API Token and the QX URL. register(QX_TOKEN, QX_URL) # 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]) # Add a Measure gate to see the state. qc.measure(q, c) # Compile and run the Quantum Program on a real device backend
In QISKit 0.6 we will be working on a pass manager for level 2+ users Note: if you have only cloned the QISKit repository but not used `pip install`, the examples only work from the root directory. """ import pprint # Import the QISKit modules from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import available_backends, compile, register, get_backend try: import Qconfig register(Qconfig.APItoken, Qconfig.config['url']) except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a Qconfig.py file with your personal token? For now, there's only access to local simulator backends...""") 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'])
- The total number of batches """ # importing the needed Qiskit functions from qiskit import register, execute, get_backend, unregister # Import other needed functions import Functions.Data_storage as store import Functions.Create_tomo_circuits as tomo # Import Quantum program of desired circuit from Circuits.circuit_FTSWAP import Q_program, q, c, Unitary # Change the import file for different circuit circuit_name = Q_program.get_circuit_names()[0] ############################################################################### # Register at IBM Quantum Experience using token from IBM_Q_Experience.Q_Exp_register import qx_config provider = register(qx_config['APItoken']) ############################################################################### # Simulation or real experimemt? 's' for simulation, 'r' for real run_type = 's' notes = '' # Optional notes to be stored in the datafile maximum_credits = 15 # Maximum number of credits PER BATCH nr_batches = 4 # Tries that nr of batches, if total number of circuits is not divisible adds one extra batch with the leftovers ############################################################################### # Set number of shots, timeout, measurement- and preperation basis and backend shots = 8192 # shots for every circuit (max is 8192) # 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
def _set_api(token, config): api = IBMQuantumExperience(token=token, config=config) qiskit.register(token=token, url=config.get('url'), hub=config.get('hub'), group=config.get('group'), project=config.get('project')) return api
def setUp(self): super().setUp() qiskit.register(QE_TOKEN, QE_URL, hub=QE_HUB, group=QE_GROUP, project=QE_PROJECT) # TODO: FIXME: Change this backend name when changed in IBM-Q self.backend = 'ibmqx_qasm_simulator'
def main(): count = -1 #Used to trigger exit from loop only when both inputs are valid while count == -1: first = input("Enter a binary number with less than 8 digits") second = input("Enter another binary number with less than 8 digits") l = len(first) l2 = len(second) #Checking if the length of either number is more than 8 digits if l > 8 or l2 > 8: print("Please enter valid inputs. Try again.") else: count = 0 #Finding out which number is larger and assign that length to variable n if l > l2: n = l else: n = l2 #Initialising the registers; two quantum registers with n bits each #1 more with n+1 bits, which will also hold the sum of the two numbers #The classical register has n+1 bits, which is used to make the sum readable a = QuantumRegister(n) b = QuantumRegister(n + 1) c = QuantumRegister(n) cl = ClassicalRegister(n + 1) #Combining all of them into one quantum circuit qc = QuantumCircuit(a, b, c, cl) #Setting up the registers a and b to hold the values inputted counter = 0 for i in first: if i == "1": qc.x(a[l - (counter + 1)]) counter += 1 counter = 0 for i in second: if i == "1": qc.x(b[l2 - (counter + 1)]) counter += 1 #Implementing a carry gate that is applied on all (c[i], a[i], b[i]) with #output fed to c[i+1] for i in range(n - 1): qc.ccx(a[i], b[i], c[i + 1]) qc.cx(a[i], b[i]) qc.ccx(c[i], b[i], c[i + 1]) #For the last iteration of the carry gate, instead of feeding the result to #c[n], we use b[n], which is why c has only n bits, with c[n-1] being the last carry bit qc.ccx(a[n - 1], b[n - 1], b[n]) qc.cx(a[n - 1], b[n - 1]) qc.ccx(c[n - 1], b[n - 1], b[n]) #Reversing the gate operation performed on b[n-1] qc.cx(c[n - 1], b[n - 1]) #Reversing the gate operations performed during the carry gate implementations #This is done to ensure the sum gates are fed with the correct input bit states for i in range(n - 1): qc.ccx(c[(n - 2) - i], b[(n - 2) - i], c[(n - 1) - i]) qc.cx(a[(n - 2) - i], b[(n - 2) - i]) qc.ccx(a[(n - 2) - i], b[(n - 2) - i], c[(n - 1) - i]) #These two operations act as a sum gate; if a control bit is at the 1> state #then the target bit b[(n-2)-i] is flipped qc.cx(c[(n - 2) - i], b[(n - 2) - i]) qc.cx(a[(n - 2) - i], b[(n - 2) - i]) #Measure qubits, which forces them to revert to one of two possible states: |0> or |1> #Since no superposition was created, all qubits are already in the |0> or |1> state #So this effectively transfers the qubit states to the classical register for i in range(n + 1): qc.measure(b[i], cl[i]) #Import configuration and set API token and url import Qconfig register(Qconfig.APIToken, Qconfig.config['url']) #Set chosen backend and execute job num_shots = 2 #Setting the number of times to repeat measurement selected_backend = "local_qasm_simulator" job = execute(qc, selected_backend, shots=num_shots) #Get results of program job_stats = job.result().get_counts() print(type(job_stats))