Beispiel #1
0
    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)
Beispiel #2
0
 def test_compact_flag(self):
     """Test the compact flag for available_backends works"""
     compact_names = available_backends()
     expanded_names = available_backends(compact=False)
     self.assertIn('local_qasm_simulator', compact_names)
     self.assertIn('local_statevector_simulator', compact_names)
     self.assertIn('local_unitary_simulator', compact_names)
     self.assertIn('local_qasm_simulator_py', expanded_names)
     self.assertIn('local_statevector_simulator_py', expanded_names)
Beispiel #3
0
def backend_lists():
    Experiment().IBMQ_register()
    remote_backends = available_backends({'local': False, 'simulator': False})
    remote_simulator = available_backends({'local': False, 'simulator': True})
    local_simulators = available_backends({'local': True})
    print("Remote backends: {}".format(remote_backends))
    print("Remote simulator: {}".format(remote_simulator))
    print("Local backends: {}".format(local_simulators))
    return (remote_backends, remote_simulator, local_simulators)
Beispiel #4
0
    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_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)
Beispiel #6
0
    def register_and_get_operational_backends(*args,
                                              provider_class=IBMQProvider,
                                              **kwargs):
        try:
            for provider in q_registered_providers():
                if isinstance(provider, provider_class):
                    q_unregister(provider)
                    logger.debug(
                        "Provider '{}' unregistered with Qiskit successfully.".
                        format(provider_class))
                    break
        except Exception as e:
            logger.debug(
                "Failed to unregister provider '{}' with Qiskit: {}".format(
                    provider_class, str(e)))

        preferences = Preferences()
        if args or kwargs or preferences.get_token() is not None:
            try:
                q_register(*args, provider_class=provider_class, **kwargs)
                logger.debug(
                    "Provider '{}' registered with Qiskit successfully.".
                    format(provider_class))
            except Exception as e:
                logger.debug(
                    "Failed to register provider '{}' with Qiskit: {}".format(
                        provider_class, str(e)))

        backends = available_backends()
        backends = [
            x for x in backends
            if x not in QuantumAlgorithm.UNSUPPORTED_BACKENDS
        ]
        return backends
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
Beispiel #8
0
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
Beispiel #9
0
    def register_and_get_operational_backends(qconfig):
        try:
            for provider in q_registered_providers():
                if isinstance(provider,IBMQProvider):
                    q_unregister(provider)
                    logger.debug("Provider 'IBMQProvider' unregistered with Qiskit successfully.")
                    break
        except Exception as e:
                logger.debug("Failed to unregister provider 'IBMQProvider' with Qiskit: {}".format(str(e)))

        if qconfig is not None:
            hub = qconfig.config.get('hub', None)
            group = qconfig.config.get('group', None)
            project = qconfig.config.get('project', None)
            proxies = qconfig.config.get('proxies', None)
            verify = qconfig.config.get('verify', True)
            try:
                q_register(qconfig.APItoken,
                           provider_class=IBMQProvider,
                           url=qconfig.config["url"],
                           hub=hub,
                           group=group,
                           project=project,
                           proxies=proxies,
                           verify=verify)
                logger.debug("Provider 'IBMQProvider' registered with Qiskit successfully.")
            except Exception as e:
                logger.debug("Failed to register provider 'IBMQProvider' with Qiskit: {}".format(str(e)))

        backends = available_backends()
        backends = [x for x in backends if x not in QuantumAlgorithm.UNSUPPORTED_BACKENDS]
        return backends
    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
Beispiel #11
0
def getBitString(sim):

    qbits = 9
    qr = QuantumRegister(qbits)
    cr = ClassicalRegister(qbits)
    qc = QuantumCircuit(qr, cr)

    for i in range(qbits):
        qc.h(qr[i])

    for i in range(qbits):
        qc.measure(qr[i], cr[i])

    backends = available_backends()
    backend = present_backends(sim, backends)
    if backend.status["available"] is True:
        stats = go_job(backend, qc, False, 10000)
        max = 0
        for bitString in stats:
            if (stats[bitString] > max):
                max = stats[bitString]
        for bitString in stats:
            if (stats[bitString] == max):
                return (bitString)
    else:
        print(color.FAIL, '  Backend', backend.name,
              'is unavailable, try again later.', color.ENDC)
Beispiel #12
0
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']
Beispiel #14
0
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']
Beispiel #15
0
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']
Beispiel #16
0
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_execute_invalid_api_parameters(self):
        """Test calling the API with invalid hub parameters."""
        # Invoke with hub, group and project parameters.
        _ = self._set_api(QE_TOKEN, {'url': QE_URL,
                                     'hub': 'FAKE_HUB',
                                     'group': 'FAKE_GROUP',
                                     'project': 'FAKE_PROJECT'})

        # TODO: this assertion is brittle. If the hub/group/token parameters
        # are invalid, login will work, but all the API calls will be made
        # against invalid URLS that return 400, ie:
        # /api/Network/FAKE_HUB/Groups/FAKE_GROUP/Projects/FAKE_PROJECT/devices
        self.assertEqual([],
                         qiskit.available_backends(filters={'local': False}))
    def listLocalBackends(self):

        if (version.parse(__version__) > version.parse("0.5")
                and version.parse(__version__) < version.parse("0.6")):
            backs = available_backends({'local': True})

        elif (version.parse(__version__) > version.parse("0.6")):
            backs = [backend.name() for backend in Aer.backends()]

        else:
            raise QiskitUnsupportedVersion(
                'Qiskit-terra version must be v0.5 or v0.6')

        return backs
Beispiel #19
0
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
Beispiel #20
0
    def test_execute_invalid_api_parameters(self):
        """Test calling the API with invalid hub parameters."""
        # Invoke with hub, group and project parameters.
        _ = self._set_api(
            QE_TOKEN, {
                'url': QE_URL,
                'hub': 'FAKE_HUB',
                'group': 'FAKE_GROUP',
                'project': 'FAKE_PROJECT'
            })

        # TODO: this assertion is brittle. If the hub/group/token parameters
        # are invalid, login will work, but all the API calls will be made
        # against invalid URLS that return 400, ie:
        # /api/Network/FAKE_HUB/Groups/FAKE_GROUP/Projects/FAKE_PROJECT/devices
        self.assertEqual([],
                         qiskit.available_backends(filters={'local': False}))
    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)
Beispiel #22
0
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())
Beispiel #23
0
    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)
Beispiel #24
0
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
Beispiel #25
0
def go_measure(qc, qr, cr, sim):

    for i in range(9):
        qc.measure(qr[i], cr[i])

    backends = available_backends()
    backend = present_backends(sim, backends)

    if backend.status["available"] is True:
        stats = go_job(backend, qc, True, 1024)
        max = 0
        res = []
        # print('Stats :\n', stats)
        for bitString in stats:
            if (stats[bitString] > max):
                max = stats[bitString]
        for bitString in stats:
            if (stats[bitString] == max):
                res.append(bitString)
        print_map(res, max)
        return (1)
    else:
        print(color.FAIL, '  Backend', backend.name,
              'is unavailable, try again later.', color.ENDC)
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))
    clbit_reg = ClassicalRegister(2, name='c')

    # 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
Beispiel #28
0
    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")

if 'CK_IBM_BACKEND' in os.environ:
    backend = os.environ['CK_IBM_BACKEND']
if backend not in backends:
    print(
        "Your choice '%s' was not available, so picking a random one for you..."
        % backend)
    backend = backends[0]
    print("Picked '%s' backend!" % backend)
try:
    # Create a QuantumProgram object instance.
    Q_program = QuantumProgram()
    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)

    # See a list of available local simulators
    print("Local backends: ", available_backends({'local': True}))

    # Compile and run the Quantum circuit on a simulator backend
    job_sim = execute(qc, "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc))

    # see a list of available remote backends
    remote_backends = available_backends({'local': False, 'simulator': False})

    print("Remote backends: ", remote_backends)
    # Compile and run the Quantum Program on a real device backend
    try:
Beispiel #30
0
    clbit_reg = ClassicalRegister(2, name='c')

    # 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
def main():
    print(json.dumps(available_backends(
        {'local': True}), indent=2, sort_keys=True))
    clbit_reg = ClassicalRegister(2)

    # making first circuit: bell state
    qc1 = QuantumCircuit(qubit_reg, clbit_reg)
    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)
    qc2.h(qubit_reg)
    qc2.measure(qubit_reg, clbit_reg)

    # setting up the backend
    print("(Local Backends)")
    print(available_backends({'local': True}))

    # runing the job
    job_sim = execute([qc1, qc2], "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc1))
    print(sim_result.get_counts(qc2))

    # see a list of available remote backends
    print("\n(Remote Backends)")
    print(available_backends({'local': False}))

    # Compile and run on a real device backend
Beispiel #33
0
    clbit_reg = ClassicalRegister(2)

    # making first circuit: bell state
    qc1 = QuantumCircuit(qubit_reg, clbit_reg)
    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)
    qc2.h(qubit_reg)
    qc2.measure(qubit_reg, clbit_reg)

    # setting up the backend
    print("(Local Backends)")
    print(available_backends({'local': True}))

    # runing the job
    job_sim = execute([qc1, qc2], "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc1))
    print(sim_result.get_counts(qc2))

    # see a list of available remote backends
    print("\n(Remote Backends)")
    print(available_backends({'local': False}))

    # Compile and run on a real device backend
Beispiel #34
0
    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)

    # See a list of available local simulators
    print("Local backends: ", available_backends({'local': True}))

    # Compile and run the Quantum circuit on a simulator backend
    job_sim = execute(qc, "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc))

    # see a list of available remote backends
    remote_backends = available_backends({'local': False, 'simulator': False})

    print("Remote backends: ", remote_backends)
    # Compile and run the Quantum Program on a real device backend
    try:
Beispiel #35
0
from qiskit import available_backends, execute

# Initiate quantum registers for gate execution, and classical registers for measurements
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
print(q)

# Preform a Hadamard on the qubit in the quantum register to create a superposition
qc.h(q[0])
# Preform a controlled-not operation between the first and second qubits in the register
qc.cx(q[0], q[1])
# Preform an X-pauli on the second qubit in the register
qc.x(q[1])
# Measure the superposition
qc.measure(q, c)

# Check simulation backends
print("Local backends: ", available_backends({'local': True}))

# Submit the job to the Q QASM Simulator (Up to 32 Qubits)
job_sim = execute(qc, "local_qasm_simulator")
# Fetch result
sim_result = job_sim.result()

#Print out the simulation measuement basis and corresponding counts
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))

print(qc.qasm())
Beispiel #36
0
"""
Example on how to use: load_qasm_file
If you want to use your local cloned repository intead of the one installed via pypi,
you have to run like this:
    examples/python$ PYTHONPATH=$PYTHONPATH:../.. python load_qasm.py
"""
from qiskit.wrapper import load_qasm_file
from qiskit import QISKitError, available_backends, execute
try:
    qc = load_qasm_file("../qasm/entangled_registers.qasm")

    # See a list of available local simulators
    print("Local backends: ", available_backends({'local': True}))

    # Compile and run the Quantum circuit on a local simulator backend
    job_sim = execute(qc, "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc))

except QISKitError as ex:
    print('There was an internal QISKit error. Error = {}'.format(ex))

Beispiel #37
0
# 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.        ],
       [ 0.88418237, -0.46714188,  1.        ]])

Beispiel #38
0
import os
import qiskit

if "QX_API_TOKEN" not in os.environ:
    print("Set environment variable QX_API_TOKEN")
    exit(1)
QX_API_TOKEN = os.environ["QX_API_TOKEN"]

qiskit.register(QX_API_TOKEN, "https://quantumexperience.ng.bluemix.net/api")
print("Registered")

print("Available backends:")
print(qiskit.available_backends())