Beispiel #1
0
    def __init__(self, q_jobs, callback, max_workers=1):
        """
        Args:
            q_jobs (list(QuantumJob)): List of QuantumJob objects.
            callback (fn(results)): The function that will be called when all
                jobs finish. The signature of the function must be:
                fn(results)
                results: A list of Result objects.
            max_workers (int): The maximum number of workers to use.

        Raises:
            QISKitError: if any of the job backends could not be found.
        """
        self.q_jobs = q_jobs
        self.max_workers = max_workers
        # check whether any jobs are remote
        self.online = any(qj.backend not in local_backends() for qj in q_jobs)
        self.futures = {}
        self.lock = Lock()
        # Set a default dummy callback just in case the user doesn't want
        # to pass any callback.
        self.callback = (lambda rs: ()) if callback is None else callback
        self.num_jobs = len(self.q_jobs)
        self.jobs_results = []
        if self.online:
            # verify backends across all jobs
            for q_job in q_jobs:
                if q_job.backend not in remote_backends() + local_backends():
                    raise QISKitError("Backend %s not found!" % q_job.backend)
        if self.online:
            # I/O intensive -> use ThreadedPoolExecutor
            self.executor_class = futures.ThreadPoolExecutor
        else:
            # CPU intensive -> use ProcessPoolExecutor
            self.executor_class = futures.ProcessPoolExecutor
    def test_local_backends(self):
        available_backends = local_backends()
        self.log.info(
            'The discovered local devices are: {}'.format(available_backends))

        # Some local backends should always be present.
        self.assertIn('local_qasm_simulator', available_backends)
        self.assertIn('local_unitary_simulator', available_backends)
    def test_local_backends(self):
        available_backends = local_backends()
        self.log.info('The discovered local devices are: {}'.format(
            available_backends))

        # Some local backends should always be present.
        self.assertIn('local_qasm_simulator', available_backends)
        self.assertIn('local_unitary_simulator', available_backends)
Beispiel #4
0
    def _create_qobj(self, circuits, circuit_config, backend, seed,
                     resources, shots, do_compile):
        # local and remote backends currently need different
        # compilied circuit formats
        formatted_circuits = []
        if do_compile:
            for circuit in circuits:
                formatted_circuits.append(None)
        else:
            if backend in backends.local_backends():
                for circuit in self.circuits:
                    basis = ['u1', 'u2', 'u3', 'cx', 'id']
                    unroller = Unroller
                    # TODO: No instanceof here! Refactor this class
                    if isinstance(circuit, DAGCircuit):
                        unroller = DagUnroller
                    elif isinstance(circuit, QuantumCircuit):
                        # TODO: We should remove this code path (it's redundant and slow)
                        circuit = Qasm(data=circuit.qasm()).parse()
                    unroller_instance = unroller(circuit, JsonBackend(basis))
                    compiled_circuit = unroller_instance.execute()
                    formatted_circuits.append(compiled_circuit)

            else:
                for circuit in self.circuits:
                    formatted_circuits.append(circuit.qasm(qeflag=True))

        # create circuit component of qobj
        circuit_records = []
        if circuit_config is None:
            config = {'coupling_map': None,
                      'basis_gates': 'u1,u2,u3,cx,id',
                      'layout': None,
                      'seed': seed}
            circuit_config = [config] * len(self.circuits)

        for circuit, fcircuit, name, config in zip(self.circuits,
                                                   formatted_circuits,
                                                   self.names,
                                                   circuit_config):
            record = {
                'name': name,
                'compiled_circuit': None if do_compile else fcircuit,
                'compiled_circuit_qasm': None if do_compile else fcircuit,
                'circuit': circuit,
                'config': config
            }
            circuit_records.append(record)

        return {'id': self._generate_job_id(length=10),
                'config': {
                    'max_credits': resources['max_credits'],
                    'shots': shots,
                    'backend': backend
                },
                'circuits': circuit_records}
Beispiel #5
0
    def __init__(self,
                 q_jobs,
                 callback,
                 max_workers=1,
                 token=None,
                 url=None,
                 api=None):
        """
        Args:
            q_jobs (list(QuantumJob)): List of QuantumJob objects.
            callback (fn(results)): The function that will be called when all
                jobs finish. The signature of the function must be:
                fn(results)
                results: A list of Result objects.
            max_workers (int): The maximum number of workers to use.
            token (str): Server API token
            url (str): Server URL.
            api (IBMQuantumExperience): API instance to use. If set,
                /token/ and /url/ are ignored.
        """
        self.q_jobs = q_jobs
        self.max_workers = max_workers
        # check whether any jobs are remote
        self._local_backends = backends.local_backends()
        self.online = any(qj.backend not in self._local_backends
                          for qj in q_jobs)
        self.futures = {}
        self.lock = Lock()
        # Set a default dummy callback just in case the user doesn't want
        # to pass any callback.
        self.callback = (lambda rs: ()) if callback is None else callback
        self.num_jobs = len(self.q_jobs)
        self.jobs_results = []
        if self.online:
            self._api = api if api else IBMQuantumExperience(
                token, {"url": url}, verify=True)
            self._online_backends = remote_backends(self._api)
            # Check for the existance of the backend
            for q_job in q_jobs:
                if q_job.backend not in self._online_backends + self._local_backends:
                    raise QISKitError("Backend %s not found!" % q_job.backend)

            self._api_config = {}
            self._api_config["token"] = token
            self._api_config["url"] = {"url": url}
        else:
            self._api = None
            self._online_backends = None
            self._api_config = None
        if self.online:
            # I/O intensive -> use ThreadedPoolExecutor
            self.executor_class = futures.ThreadPoolExecutor
        else:
            # CPU intensive -> use ProcessPoolExecutor
            self.executor_class = futures.ProcessPoolExecutor
Beispiel #6
0
    def _create_qobj(self, circuits, circuit_config, backend, seed, resources,
                     shots, do_compile):
        # local and remote backends currently need different
        # compilied circuit formats
        formatted_circuits = []
        if do_compile:
            for circuit in circuits:
                formatted_circuits.append(None)
        else:
            if backend in backends.local_backends():
                for circuit in self.circuits:
                    formatted_circuits.append(
                        openquantumcompiler.dag2json(circuit))
            else:
                for circuit in self.circuits:
                    formatted_circuits.append(circuit.qasm(qeflag=True))

        # create circuit component of qobj
        circuit_records = []
        if circuit_config is None:
            config = {
                'coupling_map': None,
                'basis_gates': 'u1,u2,u3,cx,id',
                'layout': None,
                'seed': seed
            }
            circuit_config = [config] * len(self.circuits)

        for circuit, fcircuit, name, config in zip(self.circuits,
                                                   formatted_circuits,
                                                   self.names, circuit_config):
            record = {
                'name': name,
                'compiled_circuit': None if do_compile else fcircuit,
                'compiled_circuit_qasm': None if do_compile else fcircuit,
                'circuit': circuit,
                'config': config
            }
            circuit_records.append(record)

        return {
            'id': self._generate_job_id(length=10),
            'config': {
                'max_credits': resources['max_credits'],
                'shots': shots,
                'backend': backend
            },
            'circuits': circuit_records
        }
    def _create_qobj(self, circuits, circuit_config, backend, seed,
                     resources, shots, do_compile):
        # local and remote backends currently need different
        # compilied circuit formats
        formatted_circuits = []
        if do_compile:
            for circuit in circuits:
                formatted_circuits.append(None)
        else:
            if backend in backends.local_backends():
                for circuit in self.circuits:
                    formatted_circuits.append(openquantumcompiler.dag2json(circuit))
            else:
                for circuit in self.circuits:
                    formatted_circuits.append(circuit.qasm(qeflag=True))

        # create circuit component of qobj
        circuit_records = []
        if circuit_config is None:
            config = {'coupling_map': None,
                      'basis_gates': 'u1,u2,u3,cx,id',
                      'layout': None,
                      'seed': seed}
            circuit_config = [config] * len(self.circuits)

        for circuit, fcircuit, name, config in zip(self.circuits,
                                                   formatted_circuits,
                                                   self.names,
                                                   circuit_config):
            record = {
                'name': name,
                'compiled_circuit': None if do_compile else fcircuit,
                'compiled_circuit_qasm': None if do_compile else fcircuit,
                'circuit': circuit,
                'config': config
            }
            circuit_records.append(record)

        return {'id': self._generate_job_id(length=10),
                'config': {
                    'max_credits': resources['max_credits'],
                    'shots': shots,
                    'backend': backend
                },
                'circuits': circuit_records}
Beispiel #8
0
def run_backend(q_job):
    """Run a program of compiled quantum circuits on a backend.

    Args:
        q_job (QuantumJob): job object

    Returns:
        Result: Result object.
    """
    backend_name = q_job.backend
    qobj = q_job.qobj
    if backend_name in local_backends():  # remove condition when api gets qobj
        for circuit in qobj['circuits']:
            if circuit['compiled_circuit'] is None:
                compiled_circuit = openquantumcompiler.compile(
                    circuit['circuit'], format='json')
                circuit['compiled_circuit'] = compiled_circuit
    backend = qiskit.backends.get_backend_instance(backend_name)
    return backend.run(q_job)
Beispiel #9
0
from qiskit import QuantumProgram
import Qconfig
from qiskit.backends import local_backends
from pprint import pprint

local_backends()

backend = 'local_qasm_simulator'
qp = QuantumProgram()
qp.set_api(Qconfig.APItoken, Qconfig.config['url'])
qr = qp.create_quantum_register('qr', 2)
cr = qp.create_classical_register('cr', 2)
qc = qp.create_circuit('Bell', [qr], [cr])

qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])

source = qp.get_qasm('Bell')
print(source)

#result = qp.execute('Bell')


circuits = ['Bell']

qobj = qp.compile(circuits, backend)

result = qp.run(qobj, wait=2, timeout=240)
Beispiel #10
0
bv.x(tmp[0])
bv.h(q)
bv.h(tmp)
bv += oracle
bv.h(q)
bv.h(tmp)

bv.measure(q, res)
print(bv.qasm())

from qiskit.tools.visualization import circuit_drawer
circuit_drawer(bv)

from qiskit import QuantumProgram
qp = QuantumProgram()
qp.add_circuit(quantum_circuit=bv, name='bv')

from qiskit import backends
print(backends.local_backends())
print(backends.remote_backends())

import Qconfig
qp.set_api(Qconfig.APItoken, Qconfig.config['url'])

result = qp.execute('bv', backend='ibmqx4', timeout=3600)

counts = result.get_counts('bv')
print(counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)