diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ea81a7ed03cc..4ab413d67783 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -27,8 +27,6 @@ Added - New EnlargeWithAncilla pass for adding ancilla qubits after a Layout selection pass (#1603). - New Unroll2Q pass for unrolling gates down to just 1q or 2q gates (#1614). -- Added a RunConfig object for configurations for run configurations to be used - in compile and circuits_to_qobj. (#1629) - Added support for register slicing when applying operations to a register (#1643). - Added in new parameter ``justify`` to the text circuit drawer to say how the circuit should be aligned. (#1725) @@ -36,7 +34,20 @@ Added (#1733) - Added in methods to remove a specific DAG edge and to see if a specific edge exists - Added parameter to the TextProgressBar to allow the output to be sent to a - different output stream + different output stream +- Added a ``RunConfig`` object for configurations related to running an + experiment (e.g. shots, memory) (#1856) +- Added a ``TranspileConfig`` object for configurations related to transforming + circuits (e.g. basis_gates, coupling_map, initial_layout) (#1856) +- Added a ``qiskit.compiler`` namespace for all functions that transpile, schedule + and assemble circuits and pulses (#1856) +- Added a ``qiskit.compiler.assemble_circuits()`` function to generate qobj from some + circuits and a RunConfig (#1856) +- Added an ``execute_circuits()`` function that takes a list of circuits along with a + TranspileConfig and RunConfig. The ``execute()`` function remains as a wrapper of this, + and later as a wrapper of ``execute_pulses()``. +- ``execute_circuits()`` and ``assemble_circuits()`` allow setting a qobj_header of type + QobjHeader to add extra information to the qobj (and thus result). Changed ------- @@ -83,6 +94,9 @@ Deprecated - Unroller bases must now be explicit, and violation raises an informative ``QiskitError`` (#1802). - The ``qiskit.tools.qcvv`` package is deprecated in favor of Qiskit Ignis (#1884). +- The ``qiskit.compile()`` function is now deprecated in favor of explicitly + using the ``qiskit.compiler.transpile()`` function to transform a circuit followed + by ``qiskit.compiler.assemble_circuits()`` to make a qobj out of it. Fixed ----- diff --git a/examples/python/hello_quantum.py b/examples/python/hello_quantum.py index b8d4dc0692fa..4a492b05d1fd 100644 --- a/examples/python/hello_quantum.py +++ b/examples/python/hello_quantum.py @@ -50,16 +50,17 @@ # Compile and run the Quantum Program on a real device backend try: least_busy_device = least_busy(IBMQ.backends(simulator=False)) - print("Running on current least busy device: ", least_busy_device) - - #running the job - job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10) - result_exp = job_exp.result() - - # Show the results - print(result_exp.get_counts(qc)) except: print("All devices are currently unavailable.") + print("Running on current least busy device: ", least_busy_device) + + #running the job + job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10) + result_exp = job_exp.result() + + # Show the results + print(result_exp.get_counts(qc)) + except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/examples/python/rippleadd.py b/examples/python/rippleadd.py index 2197d7bf49eb..daa068e5443d 100644 --- a/examples/python/rippleadd.py +++ b/examples/python/rippleadd.py @@ -13,7 +13,8 @@ """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, BasicAer +from qiskit import BasicAer +from qiskit import execute ############################################################### # Set the backend name and coupling map. @@ -76,14 +77,12 @@ def unmajority(p, a, b, c): ############################################################### # First version: not mapped -qobj = compile(qc, backend=backend, coupling_map=None, shots=1024) -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph -qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024) -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) diff --git a/examples/python/teleport.py b/examples/python/teleport.py index 5f0f3ec7c9ee..d73c52783e25 100644 --- a/examples/python/teleport.py +++ b/examples/python/teleport.py @@ -13,7 +13,8 @@ """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, BasicAer +from qiskit import BasicAer +from qiskit import execute ############################################################### # Set the backend name and coupling map. @@ -58,20 +59,14 @@ ############################################################### # First version: not mapped -initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), - ("q", 2): ("q", 2)} -qobj = compile(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) -job = backend.run(qobj) -qobj_exp = qobj.experiments[0] +initial_layout = [q[0], q[1], q[2]] +job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph -qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout) -qobj_exp = qobj.experiments[0] -qobj_exp.header.compiled_circuit_qasm = "" -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution diff --git a/examples/python/using_qiskit_terra_level_0.py b/examples/python/using_qiskit_terra_level_0.py index c585379dc2cf..9fbe8ff48ce1 100644 --- a/examples/python/using_qiskit_terra_level_0.py +++ b/examples/python/using_qiskit_terra_level_0.py @@ -68,18 +68,20 @@ try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) - print("Running on current least busy device: ", least_busy_device) + except: + print("All devices are currently unavailable.") - # running the job - job_exp = execute([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + print("Running on current least busy device: ", least_busy_device) - job_monitor(job_exp) - exp_result = job_exp.result() + # running the job + job_exp = execute([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + + job_monitor(job_exp) + exp_result = job_exp.result() + + # Show the results + print(exp_result.get_counts(qc1)) + print(exp_result.get_counts(qc2)) - # Show the results - print(exp_result.get_counts(qc1)) - print(exp_result.get_counts(qc2)) - except: - print("All devices are currently unavailable.") except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/examples/python/using_qiskit_terra_level_1.py b/examples/python/using_qiskit_terra_level_1.py index 043d13dd52ee..eea0be50275b 100644 --- a/examples/python/using_qiskit_terra_level_1.py +++ b/examples/python/using_qiskit_terra_level_1.py @@ -8,20 +8,28 @@ """ Example showing how to use Qiskit at level 1 (intermediate). -This example shows how an intermediate user interacts with Terra. It builds some circuits -and compiles them from compile parameters. It makes a qobj object which is just and container to be -run on a backend. The same qobj can run on many backends (as shown). It is the -user responsibility to make sure it can be run. This is useful when you want to compare the same -circuits on different backends or change the compile parameters. - -To control the passes and we have a pass manager for level 2 user. +This example shows how an intermediate user interacts with Terra. +It builds some circuits and transpiles them with transpile options. +It then makes a qobj object which is just a container to be run on a backend. +The same qobj can be submitted to many backends (as shown). +It is the user's responsibility to make sure it can be run (i.e. it conforms +to the restrictions of the backend, if any). +This is useful when you want to compare the same +circuit on different backends without recompiling the whole circuit, +or just want to change some runtime parameters. + +To control the passes that transform the circuit, we have a pass manager +for the level 2 user. """ import pprint, time # Import the Qiskit modules -from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError -from qiskit import compile, IBMQ, BasicAer +from qiskit import IBMQ, BasicAer +from qiskit import QiskitError +from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister +from qiskit.compiler import transpile, assemble_circuits +from qiskit.compiler import TranspileConfig, RunConfig from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor @@ -33,7 +41,7 @@ For now, there's only access to local simulator backends...""") try: - # Create a Quantum and Classical Register and giving a name. + # Create a Quantum and Classical Register and give them names. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') @@ -52,31 +60,48 @@ print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) - my_backend = BasicAer.get_backend('qasm_simulator') + qasm_simulator = BasicAer.get_backend('qasm_simulator') print("(QASM Simulator configuration) ") - pprint.pprint(my_backend.configuration()) + pprint.pprint(qasm_simulator.configuration()) print("(QASM Simulator properties) ") - pprint.pprint(my_backend.properties()) + pprint.pprint(qasm_simulator.properties()) - print("\n(IMQ Backends)") + # Compile and run the circuit on a real device backend + # See a list of available remote backends + print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) - # select least busy available device and execute. - least_busy_device = least_busy(IBMQ.backends(simulator=False)) + try: + # select least busy available device and execute. + least_busy_device = least_busy(IBMQ.backends(simulator=False)) + except: + print("All devices are currently unavailable.") + print("Running on current least busy device: ", least_busy_device) print("(with configuration) ") pprint.pprint(least_busy_device.configuration()) print("(with properties) ") pprint.pprint(least_busy_device.properties()) + # Transpile the circuits to make them compatible with the experimental backend + [qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], + transpile_config=TranspileConfig(backend=least_busy_device)) + print("Bell circuit before transpile:") + print(qc1) + print("Bell circuit after transpile:") + print(qc1_new) + print("Superposition circuit before transpile:") + print(qc2) + print("Superposition circuit after transpile:") + print(qc2_new) - # Compiling the job for the experimental backend - qobj = compile([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + # Assemble the two circuits into a runnable qobj + qobj = assemble_circuits([qc1_new, qc2_new], run_config=RunConfig(shots=1000)) - # Running the job - sim_job = my_backend.run(qobj) + # Running qobj on the simulator + sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() @@ -85,20 +110,15 @@ print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) - # Compile and run the Quantum Program on a real device backend - # See a list of available remote backends - try: - # Running the job. - exp_job = least_busy_device.run(qobj) + # Running the job. + exp_job = least_busy_device.run(qobj) - job_monitor(exp_job) - exp_result = exp_job.result() + job_monitor(exp_job) + exp_result = exp_job.result() - # Show the results - print(exp_result.get_counts(qc1)) - print(exp_result.get_counts(qc2)) - except: - print("All devices are currently unavailable.") + # Show the results + print(exp_result.get_counts(qc1)) + print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/qiskit/__init__.py b/qiskit/__init__.py index 792e1f405389..af905352a499 100644 --- a/qiskit/__init__.py +++ b/qiskit/__init__.py @@ -7,6 +7,7 @@ # pylint: disable=wrong-import-order + """Main Qiskit public functionality.""" import pkgutil @@ -21,7 +22,9 @@ from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit -from .tools.compiler import (compile, execute) +# pylint: disable=redefined-builtin +from qiskit.tools.compiler import compile # TODO remove after 0.8 +from qiskit.execute import (execute_circuits, execute) # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. @@ -38,12 +41,12 @@ # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer -# Try to import the Aer provider if the Aer element is installed. +# Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass -# Try to import the IBQM provider if the IBMQ element is installed. +# Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: diff --git a/qiskit/compiler/__init__.py b/qiskit/compiler/__init__.py new file mode 100644 index 000000000000..341e16bf212d --- /dev/null +++ b/qiskit/compiler/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Helper module for Qiskit compiler. + +""" + +from .run_config import RunConfig +from .transpile_config import TranspileConfig +from .assembler import assemble_circuits +from .transpiler import transpile diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py new file mode 100644 index 000000000000..8d9f776b4782 --- /dev/null +++ b/qiskit/compiler/assembler.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Assemble function for converting a list of circuits into a qobj""" +import uuid +import sympy +import numpy + +from qiskit.circuit.quantumcircuit import QuantumCircuit +from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader +from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional +from qiskit.compiler.run_config import RunConfig +from qiskit.qobj.utils import QobjType + + +def assemble_circuits(circuits, run_config=None, qobj_header=None, qobj_id=None): + """Assembles a list of circuits into a qobj which can be run on the backend. + + Args: + circuits (list[QuantumCircuits] or QuantumCircuit): circuits to assemble + run_config (RunConfig): RunConfig object + qobj_header (QobjHeader): header to pass to the results + qobj_id (int): identifier for the generated qobj + + Returns: + Qobj: the Qobj to be run on the backends + """ + qobj_header = qobj_header or QobjHeader() + run_config = run_config or RunConfig() + if isinstance(circuits, QuantumCircuit): + circuits = [circuits] + + userconfig = QobjConfig(**run_config.to_dict()) + experiments = [] + max_n_qubits = 0 + max_memory_slots = 0 + for circuit in circuits: + # header stuff + n_qubits = 0 + memory_slots = 0 + qubit_labels = [] + clbit_labels = [] + + qreg_sizes = [] + creg_sizes = [] + for qreg in circuit.qregs: + qreg_sizes.append([qreg.name, qreg.size]) + for j in range(qreg.size): + qubit_labels.append([qreg.name, j]) + n_qubits += qreg.size + for creg in circuit.cregs: + creg_sizes.append([creg.name, creg.size]) + for j in range(creg.size): + clbit_labels.append([creg.name, j]) + memory_slots += creg.size + + # TODO: why do we need creq_sizes and qreg_sizes in header + # TODO: we need to rethink memory_slots as they are tied to classical bit + experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels, + n_qubits=n_qubits, + qreg_sizes=qreg_sizes, + clbit_labels=clbit_labels, + memory_slots=memory_slots, + creg_sizes=creg_sizes, + name=circuit.name) + # TODO: why do we need n_qubits and memory_slots in both the header and the config + experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots) + + instructions = [] + for opt in circuit.data: + current_instruction = QobjInstruction(name=opt.name) + if opt.qargs: + qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]]) + for qubit in opt.qargs] + current_instruction.qubits = qubit_indices + if opt.cargs: + clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]]) + for clbit in opt.cargs] + current_instruction.memory = clbit_indices + + if opt.params: + params = list(map(lambda x: x.evalf(), opt.params)) + params = [sympy.matrix2numpy(x, dtype=complex) + if isinstance(x, sympy.Matrix) else x for x in params] + if len(params) == 1 and isinstance(params[0], numpy.ndarray): + # TODO: Aer expects list of rows for unitary instruction params; + # change to matrix in Aer. + params = params[0] + current_instruction.params = params + # TODO (jay): I really dont like this for snapshot. I also think we should change + # type to snap_type + if opt.name == "snapshot": + current_instruction.label = str(opt.params[0]) + current_instruction.type = str(opt.params[1]) + if opt.control: + mask = 0 + for clbit in clbit_labels: + if clbit[0] == opt.control[0].name: + mask |= (1 << clbit_labels.index(clbit)) + + current_instruction.conditional = QobjConditional(mask="0x%X" % mask, + type='equals', + val="0x%X" % opt.control[1]) + + instructions.append(current_instruction) + experiments.append(QobjExperiment(instructions=instructions, header=experimentheader, + config=experimentconfig)) + if n_qubits > max_n_qubits: + max_n_qubits = n_qubits + if memory_slots > max_memory_slots: + max_memory_slots = memory_slots + + userconfig.memory_slots = max_memory_slots + userconfig.n_qubits = max_n_qubits + + return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig, + experiments=experiments, header=qobj_header, + type=QobjType.QASM.value) diff --git a/qiskit/compiler/compile.py b/qiskit/compiler/compile.py new file mode 100644 index 000000000000..d01254cea4a1 --- /dev/null +++ b/qiskit/compiler/compile.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Helper module for simplified Qiskit usage.""" +import warnings +import logging + +from qiskit import transpiler +from qiskit.converters import circuits_to_qobj +from qiskit.compiler import RunConfig +from qiskit.qobj import QobjHeader +from qiskit.mapper import Layout + + +logger = logging.getLogger(__name__) + + +# pylint: disable=redefined-builtin +def compile(circuits, backend, + config=None, basis_gates=None, coupling_map=None, initial_layout=None, + shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None, + pass_manager=None, memory=False): + """Compile a list of circuits into a qobj. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile + backend (BaseBackend): a backend to compile for + config (dict): dictionary of parameters (e.g. noise) used by runner + basis_gates (list[str]): list of basis gates names supported by the + target. Default: ['u1','u2','u3','cx','id'] + coupling_map (list): coupling map (perhaps custom) to target in mapping + initial_layout (list): initial layout of qubits in mapping + shots (int): number of repetitions of each circuit, for sampling + max_credits (int): maximum credits to use + seed (int): random seed for simulators + seed_mapper (int): random seed for swapper mapper + qobj_id (int): identifier for the generated qobj + pass_manager (PassManager): a pass manger for the transpiler pipeline + memory (bool): if True, per-shot measurement bitstrings are returned as well + + Returns: + Qobj: the qobj to be run on the backends + + Raises: + QiskitError: if the desired options are not supported by backend + """ + if config: + warnings.warn('The `config` argument is deprecated and ' + 'does not do anything', DeprecationWarning) + + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) + + circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, + seed_mapper, pass_manager) + + # step 4: Making a qobj + run_config = RunConfig() + + if seed: + run_config.seed = seed + if shots: + run_config.shots = shots + if max_credits: + run_config.max_credits = max_credits + if memory: + run_config.memory = memory + qobj = circuits_to_qobj(circuits, qobj_header=QobjHeader(), run_config=run_config, + qobj_id=qobj_id) + + return qobj diff --git a/qiskit/compiler/models.py b/qiskit/compiler/models.py new file mode 100644 index 000000000000..3a5eaa792143 --- /dev/null +++ b/qiskit/compiler/models.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Models for RunConfig and its related components.""" + +from marshmallow.validate import Range + +from qiskit.validation import BaseSchema +from qiskit.validation.fields import Boolean, Integer + + +class TranspileConfigSchema(BaseSchema): + """Schema for TranspileConfig.""" + + # Required properties. + # None + + # Optional properties. + + +class RunConfigSchema(BaseSchema): + """Schema for RunConfig.""" + + # Required properties. + # None + + # Optional properties. + shots = Integer(validate=Range(min=1)) + max_credits = Integer(validate=Range(min=3, max=10)) # TODO: can we check the range + seed = Integer() + memory = Boolean() # set default to be False diff --git a/qiskit/qobj/run_config.py b/qiskit/compiler/run_config.py similarity index 60% rename from qiskit/qobj/run_config.py rename to qiskit/compiler/run_config.py index 2aff1cf80f75..0d0b9fcd242a 100644 --- a/qiskit/qobj/run_config.py +++ b/qiskit/compiler/run_config.py @@ -7,23 +7,8 @@ """Models for RunConfig and its related components.""" -from marshmallow.validate import Range - -from qiskit.validation import BaseModel, BaseSchema, bind_schema -from qiskit.validation.fields import Boolean, Integer - - -class RunConfigSchema(BaseSchema): - """Schema for RunConfig.""" - - # Required properties. - # None - - # Optional properties. - shots = Integer(validate=Range(min=1)) - max_credits = Integer(validate=Range(min=3, max=10)) # TODO: can we check the range - seed = Integer() - memory = Boolean() # set default to be False +from qiskit.compiler.models import RunConfigSchema +from qiskit.validation import BaseModel, bind_schema @bind_schema(RunConfigSchema) diff --git a/qiskit/compiler/transpile_config.py b/qiskit/compiler/transpile_config.py new file mode 100644 index 000000000000..8f895eee0aa4 --- /dev/null +++ b/qiskit/compiler/transpile_config.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Models for TranspileConfig and its related components.""" + +from qiskit.compiler.models import TranspileConfigSchema +from qiskit.validation import BaseModel, bind_schema + + +@bind_schema(TranspileConfigSchema) +class TranspileConfig(BaseModel): + """Model for TranspileConfig. + + Please note that this class only describes the required fields. For the + full description of the model, please check ``TranspileConfigSchema``. + + Attributes: + + """ diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py new file mode 100644 index 000000000000..941e5aa806db --- /dev/null +++ b/qiskit/compiler/transpiler.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Circuit transpile function """ +import logging + +from qiskit import transpiler +from qiskit.mapper import Layout + + +logger = logging.getLogger(__name__) + + +def transpile(circuits, transpile_config=None): + """Compile a list of circuits into a list of optimized circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile + transpile_config (TranspileConfig): configuration for the transpiler + + Returns: + circuits: the optimized circuits + """ + + # ------------ + # TODO: This is a hack while we are still using the old transpiler. + initial_layout = getattr(transpile_config, 'initial_layout', None) + basis_gates = getattr(transpile_config, 'basis_gates', None) + coupling_map = getattr(transpile_config, 'coupling_map', None) + seed_mapper = getattr(transpile_config, 'seed_mapper', None) + + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) + + pass_manager = None + backend = transpile_config.backend + new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, + initial_layout, seed_mapper, pass_manager) + # --------- + + # THE IDEAL CODE HERE WILL BE. + # 1 set up the pass_manager using transpile_config options + # pass_manager = PassManager(TranspileConig) + # run the passes + # new_circuits = pass_manager.run(circuits) + return new_circuits diff --git a/qiskit/converters/circuits_to_qobj.py b/qiskit/converters/circuits_to_qobj.py index 5dffc16840dd..ebaa7ecd9ddd 100644 --- a/qiskit/converters/circuits_to_qobj.py +++ b/qiskit/converters/circuits_to_qobj.py @@ -6,19 +6,14 @@ # the LICENSE.txt file in the root directory of this source tree. """Compile function for converting a list of circuits to the qobj""" -import uuid import warnings -import sympy -import numpy -from qiskit.circuit.quantumcircuit import QuantumCircuit -from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader -from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional -from qiskit.qobj.run_config import RunConfig -from qiskit.qobj.utils import QobjType +from qiskit.qobj import QobjHeader +from qiskit.compiler.run_config import RunConfig +from qiskit.compiler import assemble_circuits -def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, +def circuits_to_qobj(circuits, qobj_header=None, run_config=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, @@ -27,10 +22,10 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile - user_qobj_header (QobjHeader): header to pass to the results + qobj_header (QobjHeader): header to pass to the results run_config (RunConfig): RunConfig object - qobj_id (int): identifier for the generated qobj + qobj_id (int): TODO: delete after qiskit-terra 0.8 backend_name (str): TODO: delete after qiskit-terra 0.8 config (dict): TODO: delete after qiskit-terra 0.8 shots (int): TODO: delete after qiskit-terra 0.8 @@ -43,14 +38,16 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, Returns: Qobj: the Qobj to be run on the backends """ - user_qobj_header = user_qobj_header or QobjHeader() + warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. ' + 'Use qiskit.compiler.assemble_circuits() to serialize circuits into a qobj.', + DeprecationWarning) + + qobj_header = qobj_header or QobjHeader() run_config = run_config or RunConfig() - if isinstance(circuits, QuantumCircuit): - circuits = [circuits] if backend_name: warnings.warn('backend_name is not required anymore', DeprecationWarning) - user_qobj_header.backend_name = backend_name + qobj_header.backend_name = backend_name if config: warnings.warn('config is not used anymore. Set all configs in ' 'run_config.', DeprecationWarning) @@ -70,90 +67,9 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, if max_credits: warnings.warn('max_credits is not used anymore. Set it via run_config', DeprecationWarning) run_config.max_credits = max_credits + if qobj_id: + warnings.warn('qobj_id is not used anymore', DeprecationWarning) - userconfig = QobjConfig(**run_config.to_dict()) - experiments = [] - max_n_qubits = 0 - max_memory_slots = 0 - for circuit in circuits: - # header stuff - n_qubits = 0 - memory_slots = 0 - qubit_labels = [] - clbit_labels = [] - - qreg_sizes = [] - creg_sizes = [] - for qreg in circuit.qregs: - qreg_sizes.append([qreg.name, qreg.size]) - for j in range(qreg.size): - qubit_labels.append([qreg.name, j]) - n_qubits += qreg.size - for creg in circuit.cregs: - creg_sizes.append([creg.name, creg.size]) - for j in range(creg.size): - clbit_labels.append([creg.name, j]) - memory_slots += creg.size - - # TODO: why do we need creq_sizes and qreg_sizes in header - # TODO: we need to rethink memory_slots as they are tied to classical bit - experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels, - n_qubits=n_qubits, - qreg_sizes=qreg_sizes, - clbit_labels=clbit_labels, - memory_slots=memory_slots, - creg_sizes=creg_sizes, - name=circuit.name) - # TODO: why do we need n_qubits and memory_slots in both the header and the config - experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots) - - instructions = [] - for opt in circuit.data: - current_instruction = QobjInstruction(name=opt.name) - if opt.qargs: - qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]]) - for qubit in opt.qargs] - current_instruction.qubits = qubit_indices - if opt.cargs: - clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]]) - for clbit in opt.cargs] - current_instruction.memory = clbit_indices - - if opt.params: - params = list(map(lambda x: x.evalf(), opt.params)) - params = [sympy.matrix2numpy(x, dtype=complex) - if isinstance(x, sympy.Matrix) else x for x in params] - if len(params) == 1 and isinstance(params[0], numpy.ndarray): - # TODO: Aer expects list of rows for unitary instruction params; - # change to matrix in Aer. - params = params[0] - current_instruction.params = params - # TODO: I really dont like this for snapshot. I also think we should change - # type to snap_type - if opt.name == "snapshot": - current_instruction.label = str(opt.params[0]) - current_instruction.type = str(opt.params[1]) - if opt.control: - mask = 0 - for clbit in clbit_labels: - if clbit[0] == opt.control[0].name: - mask |= (1 << clbit_labels.index(clbit)) - - current_instruction.conditional = QobjConditional(mask="0x%X" % mask, - type='equals', - val="0x%X" % opt.control[1]) - - instructions.append(current_instruction) - experiments.append(QobjExperiment(instructions=instructions, header=experimentheader, - config=experimentconfig)) - if n_qubits > max_n_qubits: - max_n_qubits = n_qubits - if memory_slots > max_memory_slots: - max_memory_slots = memory_slots - - userconfig.memory_slots = max_memory_slots - userconfig.n_qubits = max_n_qubits + qobj = assemble_circuits(circuits, qobj_header, run_config) - return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig, - experiments=experiments, header=user_qobj_header, - type=QobjType.QASM.value) + return qobj diff --git a/qiskit/execute.py b/qiskit/execute.py new file mode 100644 index 000000000000..c33153d51d16 --- /dev/null +++ b/qiskit/execute.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +""" +Helper module for simplified Qiskit usage. + +This module includes + execute_circuits: compile and run a list of quantum circuits. + execute: simplified usage of either execute_circuits or execute_schedules + +In general we recommend using the SDK functions directly. However, to get something +running quickly we have provider this wrapper module. +""" + +import logging +import warnings + +from qiskit.compiler import assemble_circuits, transpile +from qiskit.compiler import RunConfig, TranspileConfig +from qiskit.qobj import QobjHeader + +logger = logging.getLogger(__name__) + + +def execute(circuits, backend, qobj_header=None, config=None, basis_gates=None, + coupling_map=None, initial_layout=None, shots=1024, max_credits=10, + seed=None, qobj_id=None, seed_mapper=None, pass_manager=None, + memory=False, **kwargs): + """Executes a set of circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute + backend (BaseBackend): a backend to execute the circuits on + qobj_header (QobjHeader): user input to go into the header + config (dict): dictionary of parameters (e.g. noise) used by runner + basis_gates (list[str]): list of basis gate names supported by the + target. Default: ['u1','u2','u3','cx','id'] + coupling_map (list): coupling map (perhaps custom) to target in mapping + initial_layout (list): initial layout of qubits in mapping + shots (int): number of repetitions of each circuit, for sampling + max_credits (int): maximum credits to use + seed (int): random seed for simulators + seed_mapper (int): random seed for swapper mapper + qobj_id (int): identifier for the generated qobj + pass_manager (PassManager): a pass manger for the transpiler pipeline + memory (bool): if True, per-shot measurement bitstrings are returned as well. + kwargs: extra arguments used by AER for running configurable backends. + Refer to the backend documentation for details on these arguments + + Returns: + BaseJob: returns job instance derived from BaseJob + """ + + transpile_config = TranspileConfig() + run_config = RunConfig() + + if config: + warnings.warn('config is deprecated in terra 0.8', DeprecationWarning) + if qobj_id: + warnings.warn('qobj_id is deprecated in terra 0.8', DeprecationWarning) + if basis_gates: + transpile_config.basis_gate = basis_gates + if coupling_map: + transpile_config.coupling_map = coupling_map + if initial_layout: + transpile_config.initial_layout = initial_layout + if seed_mapper: + transpile_config.seed_mapper = seed_mapper + if shots: + run_config.shots = shots + if max_credits: + run_config.max_credits = max_credits + if seed: + run_config.seed = seed + if memory: + run_config.memory = memory + if pass_manager: + warnings.warn('pass_manager in the execute function is deprecated in terra 0.8.', + DeprecationWarning) + + job = execute_circuits(circuits, backend, qobj_header=qobj_header, + run_config=run_config, + transpile_config=transpile_config, **kwargs) + + return job + + +def execute_circuits(circuits, backend, qobj_header=None, + transpile_config=None, run_config=None, **kwargs): + """Executes a list of circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute + backend (BaseBackend): a backend to execute the circuits on + qobj_header (QobjHeader): User input to go in the header + transpile_config (TranspileConfig): Configurations for the transpiler + run_config (RunConfig): Run Configuration + kwargs: extra arguments used by AER for running configurable backends. + Refer to the backend documentation for details on these arguments + + Returns: + BaseJob: returns job instance derived from BaseJob + """ + + # TODO: a hack, remove when backend is not needed in transpile + # ------ + transpile_config = transpile_config or TranspileConfig() + transpile_config.backend = backend + # ------ + + # filling in the header with the backend name the qobj was run on + qobj_header = qobj_header or QobjHeader() + qobj_header.backend_name = backend.name() + + # default values + if not run_config: + # TODO remove max_credits from the default when it is not + # required by by the backend. + run_config = RunConfig(shots=1024, max_credits=10, memory=False) + + # transpiling the circuits using the transpiler_config + new_circuits = transpile(circuits, transpile_config=transpile_config) + + # assembling the circuits into a qobj to be run on the backend + qobj = assemble_circuits(new_circuits, qobj_header=qobj_header, + run_config=run_config) + + # executing the circuits on the backend and returning the job + return backend.run(qobj, **kwargs) diff --git a/qiskit/qobj/__init__.py b/qiskit/qobj/__init__.py index 4a720488d321..aaed5b6fe57b 100644 --- a/qiskit/qobj/__init__.py +++ b/qiskit/qobj/__init__.py @@ -11,6 +11,5 @@ from .models import (QobjConfig, QobjExperiment, QobjInstruction, QobjHeader, QobjExperimentHeader, QobjConditional, QobjExperimentConfig) from .exceptions import QobjValidationError -from .run_config import RunConfig from ._validation import validate_qobj_against_schema diff --git a/qiskit/qobj/qobj.py b/qiskit/qobj/qobj.py index b070a1d68524..bc9639e66fd4 100644 --- a/qiskit/qobj/qobj.py +++ b/qiskit/qobj/qobj.py @@ -20,9 +20,9 @@ """Current version of the Qobj schema. Qobj schema versions: -* 1.1.0: Qiskit 0.8 -* 1.0.0: Qiskit 0.6 -* 0.0.1: Qiskit 0.5.x format (pre-schemas). +* 1.1.0: Qiskit Terra 0.8 +* 1.0.0: Qiskit Terra 0.6 +* 0.0.1: Qiskit Terra 0.5.x format (pre-schemas). """ diff --git a/qiskit/test/providers/backend.py b/qiskit/test/providers/backend.py index 05f6b7be6680..0884ae4ca7dc 100644 --- a/qiskit/test/providers/backend.py +++ b/qiskit/test/providers/backend.py @@ -9,7 +9,7 @@ from unittest import SkipTest -from qiskit.tools.compiler import compile # pylint: disable=redefined-builtin +from qiskit import execute from ..base import QiskitTestCase from ..reference_circuits import ReferenceCircuits @@ -63,8 +63,7 @@ def test_status(self): def test_run_circuit(self): """Test running a single circuit.""" - qobj = compile(self.circuit, self.backend) - job = self.backend.run(qobj) + job = execute(self.circuit, self.backend) result = job.result() self.assertEqual(result.success, True) return result diff --git a/qiskit/tools/__init__.py b/qiskit/tools/__init__.py index bee51f5b11f8..b86265c5d333 100644 --- a/qiskit/tools/__init__.py +++ b/qiskit/tools/__init__.py @@ -16,4 +16,4 @@ """ from .parallel import parallel_map -from .compiler import (compile, execute) +from .compiler import compile diff --git a/qiskit/tools/compiler.py b/qiskit/tools/compiler.py index b4ec3352282d..b07f796073c1 100644 --- a/qiskit/tools/compiler.py +++ b/qiskit/tools/compiler.py @@ -5,17 +5,14 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -"""Helper module for simplified Qiskit usage.""" +"""Helper module for simplified Qiskit usage. THIS WILL BE REMOVED IN AFTER 0.8.""" import warnings import logging +from qiskit.compiler import assemble_circuits, RunConfig from qiskit import transpiler -from qiskit.converters import circuits_to_qobj -from qiskit.qobj import RunConfig -from qiskit.qobj import QobjHeader from qiskit.mapper import Layout - logger = logging.getLogger(__name__) @@ -48,64 +45,32 @@ def compile(circuits, backend, Raises: QiskitError: if the desired options are not supported by backend """ - if config: - warnings.warn('The `config` argument is deprecated and ' - 'does not do anything', DeprecationWarning) - - if initial_layout is not None and not isinstance(initial_layout, Layout): - initial_layout = Layout(initial_layout) - - circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, - seed_mapper, pass_manager) + warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. ' + 'Please use qiskit.transpile() to transform circuits ' + 'and qiskit.assemble_circuits() to produce qobj.', + DeprecationWarning) - # step 4: Making a qobj run_config = RunConfig() - if seed: - run_config.seed = seed + if config: + warnings.warn('config is not used anymore. Set all configs in ' + 'run_config.', DeprecationWarning) if shots: run_config.shots = shots if max_credits: run_config.max_credits = max_credits + if seed: + run_config.seed = seed if memory: run_config.memory = memory - qobj = circuits_to_qobj(circuits, user_qobj_header=QobjHeader(), run_config=run_config, - qobj_id=qobj_id) - - return qobj - -def execute(circuits, backend, config=None, basis_gates=None, coupling_map=None, - initial_layout=None, shots=1024, max_credits=10, seed=None, - qobj_id=None, seed_mapper=None, pass_manager=None, - memory=False, **kwargs): - """Executes a set of circuits. - - Args: - circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute - backend (BaseBackend): a backend to execute the circuits on - config (dict): dictionary of parameters (e.g. noise) used by runner - basis_gates (list[str]): list of basis gate names supported by the - target. Default: ['u1','u2','u3','cx','id'] - coupling_map (list): coupling map (perhaps custom) to target in mapping - initial_layout (list): initial layout of qubits in mapping - shots (int): number of repetitions of each circuit, for sampling - max_credits (int): maximum credits to use - seed (int): random seed for simulators - seed_mapper (int): random seed for swapper mapper - qobj_id (int): identifier for the generated qobj - pass_manager (PassManager): a pass manger for the transpiler pipeline - memory (bool): if True, per-shot measurement bitstrings are returned as well. - kwargs: extra arguments used by AER for running configurable backends. - Refer to the backend documentation for details on these arguments + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) - Returns: - BaseJob: returns job instance derived from BaseJob - """ + new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, + initial_layout, seed_mapper, pass_manager) - qobj = compile(circuits, backend, - config, basis_gates, coupling_map, initial_layout, - shots, max_credits, seed, qobj_id, seed_mapper, - pass_manager, memory) + qobj = assemble_circuits(new_circuits, qobj_header=None, run_config=run_config, + qobj_id=qobj_id) - return backend.run(qobj, **kwargs) + return qobj diff --git a/test/python/aer_provider_integration_test/test_aer_qobj_headers.py b/test/python/aer_provider_integration_test/test_aer_qobj_headers.py index 82516e0ddeae..a66fad7d13f2 100644 --- a/test/python/aer_provider_integration_test/test_aer_qobj_headers.py +++ b/test/python/aer_provider_integration_test/test_aer_qobj_headers.py @@ -5,7 +5,6 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=redefined-builtin """Tests for all BasicAer simulators.""" @@ -13,7 +12,8 @@ import qiskit from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile +from qiskit.compiler import transpile, assemble_circuits +from qiskit.compiler import TranspileConfig, RunConfig from qiskit.qobj import QobjHeader from qiskit.test import QiskitTestCase, requires_aer_provider @@ -35,7 +35,8 @@ def test_qobj_headers_in_result(self): custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}} for backend in qiskit.providers.aer.Aer.backends(): with self.subTest(backend=backend): - qobj = compile(self.qc1, backend) + qc1_new = transpile(self.qc1, TranspileConfig(backend=backend)) + qobj = assemble_circuits(qc1_new, RunConfig(shots=1000)) # Update the Qobj header. qobj.header = QobjHeader.from_dict(custom_qobj_header) @@ -52,7 +53,8 @@ def test_job_qobj(self): """Test job.qobj().""" for backend in qiskit.providers.aer.Aer.backends(): with self.subTest(backend=backend): - qobj = compile(self.qc1, backend) + qc1_new = transpile(self.qc1, TranspileConfig(backend=backend)) + qobj = assemble_circuits(qc1_new, RunConfig(shots=1000)) job = backend.run(qobj) self.assertEqual(job.qobj(), qobj) diff --git a/test/python/aer_provider_integration_test/test_multi_registers_convention.py b/test/python/aer_provider_integration_test/test_multi_registers_convention.py index 4287e164dcc4..67ac0b191c47 100644 --- a/test/python/aer_provider_integration_test/test_multi_registers_convention.py +++ b/test/python/aer_provider_integration_test/test_multi_registers_convention.py @@ -5,13 +5,12 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=redefined-builtin """Test Qiskit's QuantumCircuit class for multiple registers.""" import qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile +from qiskit import execute from qiskit.quantum_info import state_fidelity, process_fidelity, Pauli, basis_state from qiskit.test import QiskitTestCase, requires_aer_provider @@ -38,20 +37,18 @@ def test_circuit_multi(self): qc = circ + meas backend_sim = qiskit.providers.aer.QasmSimulator() - qobj_qc = compile(qc, backend_sim, seed_mapper=34342) - qobj_circ = compile(circ, backend_sim, seed_mapper=3438) - result = backend_sim.run(qobj_qc).result() + result = execute(qc, backend_sim, seed_mapper=34342).result() counts = result.get_counts(qc) target = {'01 10': 1024} backend_sim = qiskit.providers.aer.StatevectorSimulator() - result = backend_sim.run(qobj_circ).result() + result = execute(circ, backend_sim, seed_mapper=3438).result() state = result.get_statevector(circ) backend_sim = qiskit.providers.aer.UnitarySimulator() - result = backend_sim.run(qobj_circ).result() + result = execute(circ, backend_sim, seed_mapper=3438).result() unitary = result.get_unitary(circ) self.assertEqual(counts, target) diff --git a/test/python/aer_provider_integration_test/test_qasm_simulator.py b/test/python/aer_provider_integration_test/test_qasm_simulator.py index 070de4f688ae..0b5b4e2fc8c9 100644 --- a/test/python/aer_provider_integration_test/test_qasm_simulator.py +++ b/test/python/aer_provider_integration_test/test_qasm_simulator.py @@ -5,14 +5,14 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=missing-docstring,redefined-builtin +"""Test Aer qasm simulator""" import unittest import numpy as np import qiskit from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit -from qiskit import compile +from qiskit import execute from qiskit.test import QiskitTestCase, requires_aer_provider, Path @@ -24,20 +24,18 @@ def setUp(self): self.seed = 88 self.backend = qiskit.providers.aer.QasmSimulator() qasm_filename = self._get_resource_path('example.qasm', Path.QASMS) - compiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) - compiled_circuit.name = 'test' - self.qobj = compile(compiled_circuit, backend=self.backend) + self.circuit = QuantumCircuit.from_qasm_file(qasm_filename) + self.circuit.name = 'test' def test_qasm_simulator_single_shot(self): """Test single shot run.""" shots = 1 - self.qobj.config.shots = shots - result = self.backend.run(self.qobj).result() + result = execute(self.circuit, self.backend, shots=shots).result() self.assertEqual(result.success, True) def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" - result = self.backend.run(self.qobj).result() + result = execute(self.circuit, self.backend).result() shots = 1024 threshold = 0.04 * shots counts = result.get_counts('test') @@ -48,6 +46,7 @@ def test_qasm_simulator(self): self.assertDictAlmostEqual(counts, target, threshold) def test_if_statement(self): + """Test simulator handles conditionals correctly""" shots = 100 qr = QuantumRegister(3, 'qr') cr = ClassicalRegister(3, 'cr') @@ -70,10 +69,10 @@ def test_if_statement(self): circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) - qobj = compile([circuit_if_true, circuit_if_false], - backend=self.backend, shots=shots, seed=self.seed) + job = execute([circuit_if_true, circuit_if_false], + backend=self.backend, shots=shots, seed=self.seed) - result = self.backend.run(qobj).result() + result = job.result() counts_if_true = result.get_counts(circuit_if_true) counts_if_false = result.get_counts(circuit_if_false) self.assertEqual(counts_if_true, {'111': 100}) @@ -101,8 +100,8 @@ def test_teleport(self): circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) - qobj = compile(circuit, backend=self.backend, shots=shots, seed=self.seed) - results = self.backend.run(qobj).result() + job = execute(circuit, backend=self.backend, shots=shots, seed=self.seed) + results = job.result() data = results.get_counts('teleport') alice = { '00': data['0 0 0'] + data['1 0 0'], @@ -127,6 +126,7 @@ def test_teleport(self): self.assertLess(error, 0.05) def test_memory(self): + """test simulator returns per-shot measurements in memory field""" qr = QuantumRegister(4, 'qr') cr0 = ClassicalRegister(2, 'cr0') cr1 = ClassicalRegister(2, 'cr1') @@ -140,8 +140,8 @@ def test_memory(self): circ.measure(qr[3], cr1[1]) shots = 50 - qobj = compile(circ, backend=self.backend, shots=shots, memory=True) - result = self.backend.run(qobj).result() + job = execute(circ, backend=self.backend, shots=shots, memory=True) + result = job.result() memory = result.get_memory() self.assertEqual(len(memory), shots) for mem in memory: diff --git a/test/python/aer_provider_integration_test/test_unitary_simulator.py b/test/python/aer_provider_integration_test/test_unitary_simulator.py index d48940a2582b..5bd7409d5d4d 100644 --- a/test/python/aer_provider_integration_test/test_unitary_simulator.py +++ b/test/python/aer_provider_integration_test/test_unitary_simulator.py @@ -5,14 +5,14 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=missing-docstring,redefined-builtin +# pylint: disable=missing-docstring import unittest import numpy as np import qiskit +from qiskit import execute from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit -from qiskit import compile from qiskit.test import QiskitTestCase, requires_aer_provider @@ -26,8 +26,7 @@ def setUp(self): def test_aer_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() - qobj = compile(circuits, backend=self.backend) - job = self.backend.run(qobj) + job = execute(circuits, backend=self.backend) sim_unitaries = [job.result().get_unitary(circ) for circ in circuits] reference_unitaries = self._reference_unitaries() norms = [np.trace(np.dot(np.transpose(np.conj(target)), actual)) diff --git a/test/python/basicaer/test_basicaer_integration.py b/test/python/basicaer/test_basicaer_integration.py index 7e89db565d17..f7e2c1e7aa76 100644 --- a/test/python/basicaer/test_basicaer_integration.py +++ b/test/python/basicaer/test_basicaer_integration.py @@ -5,13 +5,13 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -"""BasicAer provider integration tests (compile and run).""" +"""BasicAer provider integration tests.""" import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, execute # pylint: disable=redefined-builtin +from qiskit import execute from qiskit.result import Result from qiskit.test import QiskitTestCase @@ -36,7 +36,7 @@ def test_builtin_simulator_result_fields(self): self.assertEqual(self._result1.status, 'COMPLETED') self.assertEqual(self._result1.results[0].status, 'DONE') - def test_compile_run(self): + def test_basicaer_execute(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') @@ -45,11 +45,11 @@ def test_compile_run(self): qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) - qobj = compile(qc, self.backend) - result = self.backend.run(qobj).result() + job = execute(qc, self.backend) + result = job.result() self.assertIsInstance(result, Result) - def test_compile_two_run(self): + def test_basicaer_execute_two(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') @@ -59,35 +59,9 @@ def test_compile_two_run(self): qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) - qobj = compile([qc, qc_extra], self.backend) - result = self.backend.run(qobj).result() - self.assertIsInstance(result, Result) - - def test_execute(self): - """Test Execute.""" - qubit_reg = QuantumRegister(2) - clbit_reg = ClassicalRegister(2) - qc = QuantumCircuit(qubit_reg, clbit_reg) - qc.h(qubit_reg[0]) - qc.cx(qubit_reg[0], qubit_reg[1]) - qc.measure(qubit_reg, clbit_reg) - job = execute(qc, self.backend) - results = job.result() - self.assertIsInstance(results, Result) - - def test_execute_two(self): - """Test execute two.""" - qubit_reg = QuantumRegister(2) - clbit_reg = ClassicalRegister(2) - qc = QuantumCircuit(qubit_reg, clbit_reg) - qc.h(qubit_reg[0]) - qc.cx(qubit_reg[0], qubit_reg[1]) - qc.measure(qubit_reg, clbit_reg) - qc_extra = QuantumCircuit(qubit_reg, clbit_reg) - qc_extra.measure(qubit_reg, clbit_reg) job = execute([qc, qc_extra], self.backend) - results = job.result() - self.assertIsInstance(results, Result) + result = job.result() + self.assertIsInstance(result, Result) if __name__ == '__main__': diff --git a/test/python/basicaer/test_basicaer_qobj_headers.py b/test/python/basicaer/test_basicaer_qobj_headers.py index 9deabaf5fa7a..992f587eb7fb 100644 --- a/test/python/basicaer/test_basicaer_qobj_headers.py +++ b/test/python/basicaer/test_basicaer_qobj_headers.py @@ -9,7 +9,8 @@ from qiskit import BasicAer from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile # pylint: disable=redefined-builtin +from qiskit.compiler import transpile, TranspileConfig +from qiskit.compiler import assemble_circuits, RunConfig from qiskit.qobj import QobjHeader from qiskit.test import QiskitTestCase @@ -31,7 +32,8 @@ def test_qobj_headers_in_result(self): for backend in BasicAer.backends(): with self.subTest(backend=backend): - qobj = compile(self.qc1, backend) + new_circ = transpile(self.qc1, TranspileConfig(backend=backend)) + qobj = assemble_circuits(new_circ, RunConfig(shots=1024)) # Update the Qobj header. qobj.header = QobjHeader.from_dict(custom_qobj_header) @@ -40,14 +42,12 @@ def test_qobj_headers_in_result(self): result = backend.run(qobj).result() self.assertEqual(result.header.to_dict(), custom_qobj_header) - self.assertEqual(result.results[0].header.some_field, - 'extra info') + self.assertEqual(result.results[0].header.some_field, 'extra info') def test_job_qobj(self): """Test job.qobj().""" for backend in BasicAer.backends(): with self.subTest(backend=backend): - qobj = compile(self.qc1, backend) - + qobj = assemble_circuits(self.qc1, TranspileConfig(backend=backend)) job = backend.run(qobj) self.assertEqual(job.qobj(), qobj) diff --git a/test/python/basicaer/test_multi_registers_convention.py b/test/python/basicaer/test_multi_registers_convention.py index 6946dac7bd29..32492d6f63ea 100644 --- a/test/python/basicaer/test_multi_registers_convention.py +++ b/test/python/basicaer/test_multi_registers_convention.py @@ -5,11 +5,10 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -"""Test Qiskit's QuantumCircuit class for multiple registers.""" +"""Test executing multiple-register circuits on BasicAer.""" -from qiskit import BasicAer +from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile # pylint: disable=redefined-builtin from qiskit.quantum_info import Pauli, basis_state, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase @@ -34,20 +33,18 @@ def test_circuit_multi(self): qc = circ + meas backend_sim = BasicAer.get_backend('qasm_simulator') - qobj_qc = compile(qc, backend_sim, seed_mapper=34342) - qobj_circ = compile(circ, backend_sim, seed_mapper=3438) - result = backend_sim.run(qobj_qc).result() + result = execute(qc, backend_sim, seed_mapper=34342).result() counts = result.get_counts(qc) target = {'01 10': 1024} backend_sim = BasicAer.get_backend('statevector_simulator') - result = backend_sim.run(qobj_circ).result() + result = execute(circ, backend_sim, seed_mapper=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend('unitary_simulator') - result = backend_sim.run(qobj_circ).result() + result = execute(circ, backend_sim, seed_mapper=3438).result() unitary = result.get_unitary(circ) self.assertEqual(counts, target) diff --git a/test/python/basicaer/test_qasm_simulator.py b/test/python/basicaer/test_qasm_simulator.py index 41fb2dcc39fb..a156caa355bc 100644 --- a/test/python/basicaer/test_qasm_simulator.py +++ b/test/python/basicaer/test_qasm_simulator.py @@ -11,8 +11,10 @@ import numpy as np +from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile # pylint: disable=redefined-builtin +from qiskit.compiler import transpile, TranspileConfig +from qiskit.compiler import assemble_circuits, RunConfig from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.test import Path from qiskit.test import providers @@ -28,9 +30,10 @@ def setUp(self): self.seed = 88 qasm_filename = self._get_resource_path('example.qasm', Path.QASMS) - compiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) - compiled_circuit.name = 'test' - self.qobj = compile(compiled_circuit, backend=self.backend) + transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) + transpiled_circuit.name = 'test' + transpiled_circuit = transpile(transpiled_circuit, TranspileConfig(backend=self.backend)) + self.qobj = assemble_circuits(transpiled_circuit, RunConfig(shots=1000)) def test_qasm_simulator_single_shot(self): """Test single shot run.""" @@ -75,10 +78,10 @@ def test_if_statement(self): circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) - qobj = compile([circuit_if_true, circuit_if_false], - backend=self.backend, shots=shots, seed=self.seed) + job = execute([circuit_if_true, circuit_if_false], + backend=self.backend, shots=shots, seed=self.seed) - result = self.backend.run(qobj).result() + result = job.result() counts_if_true = result.get_counts(circuit_if_true) counts_if_false = result.get_counts(circuit_if_false) self.assertEqual(counts_if_true, {'111': 100}) @@ -105,8 +108,8 @@ def test_teleport(self): circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) - qobj = compile(circuit, backend=self.backend, shots=shots, seed=self.seed) - results = self.backend.run(qobj).result() + job = execute(circuit, backend=self.backend, shots=shots, seed=self.seed) + results = job.result() data = results.get_counts('teleport') alice = { '00': data['0 0 0'] + data['1 0 0'], @@ -145,8 +148,8 @@ def test_memory(self): circ.measure(qr[3], cr1[1]) shots = 50 - qobj = compile(circ, backend=self.backend, shots=shots, memory=True) - result = self.backend.run(qobj).result() + job = execute(circ, backend=self.backend, shots=shots, memory=True) + result = job.result() memory = result.get_memory() self.assertEqual(len(memory), shots) for mem in memory: diff --git a/test/python/basicaer/test_unitary_simulator.py b/test/python/basicaer/test_unitary_simulator.py index 738d0402227f..5eb79d9aa650 100644 --- a/test/python/basicaer/test_unitary_simulator.py +++ b/test/python/basicaer/test_unitary_simulator.py @@ -11,8 +11,8 @@ import numpy as np +from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile # pylint: disable=redefined-builtin from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.test import ReferenceCircuits from qiskit.test import providers @@ -27,8 +27,7 @@ class BasicAerUnitarySimulatorPyTest(providers.BackendTestCase): def test_basicaer_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() - qobj = compile(circuits, backend=self.backend) - job = self.backend.run(qobj) + job = execute(circuits, backend=self.backend) sim_unitaries = [job.result().get_unitary(circ) for circ in circuits] reference_unitaries = self._reference_unitaries() norms = [np.trace(np.dot(np.transpose(np.conj(target)), actual)) diff --git a/test/python/circuit/test_circuit_multi_registers.py b/test/python/circuit/test_circuit_multi_registers.py index c5c4dca5e475..4c6cdade7e19 100644 --- a/test/python/circuit/test_circuit_multi_registers.py +++ b/test/python/circuit/test_circuit_multi_registers.py @@ -5,17 +5,10 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=unused-import -# pylint: disable=redefined-builtin """Test Qiskit's QuantumCircuit class for multiple registers.""" -import os -import tempfile -import unittest - from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import QiskitError from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.test import QiskitTestCase diff --git a/test/python/compiler/test_assembler.py b/test/python/compiler/test_assembler.py new file mode 100644 index 000000000000..375f99fb10eb --- /dev/null +++ b/test/python/compiler/test_assembler.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Assembler Test.""" + +import numpy as np +import unittest + +from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit +from qiskit.compiler import assemble_circuits +from qiskit.compiler import RunConfig +from qiskit.qobj import Qobj +from qiskit.test import QiskitTestCase + + +class TestAssembler(QiskitTestCase): + """Tests for assembling circuits to qobj.""" + + def test_assemble_single_circuit(self): + """Test assembling a single circuit. + """ + q = QuantumRegister(2, name='q') + c = ClassicalRegister(2, name='c') + circ = QuantumCircuit(q, c, name='circ') + circ.h(q[0]) + circ.cx(q[0], q[1]) + circ.measure(q, c) + + run_config = RunConfig(shots=2000, memory=True) + qobj = assemble_circuits(circ, run_config=run_config) + self.assertIsInstance(qobj, Qobj) + self.assertEqual(qobj.config.shots, 2000) + self.assertEqual(qobj.config.memory, True) + self.assertEqual(len(qobj.experiments), 1) + self.assertEqual(qobj.experiments[0].instructions[1].name, 'cx') + + def test_assemble_multiple_circuits(self): + """Test assembling multiple circuits, all should have the same config. + """ + q0 = QuantumRegister(2, name='q0') + c0 = ClassicalRegister(2, name='c0') + circ0 = QuantumCircuit(q0, c0, name='circ0') + circ0.h(q0[0]) + circ0.cx(q0[0], q0[1]) + circ0.measure(q0, c0) + + q1 = QuantumRegister(3, name='q1') + c1 = ClassicalRegister(3, name='c1') + circ1 = QuantumCircuit(q1, c1, name='circ0') + circ1.h(q1[0]) + circ1.cx(q1[0], q1[1]) + circ1.cx(q1[0], q1[2]) + circ1.measure(q1, c1) + + run_config = RunConfig(shots=100, memory=False, seed=6) + qobj = assemble_circuits([circ0, circ1], run_config=run_config) + self.assertIsInstance(qobj, Qobj) + self.assertEqual(qobj.config.seed, 6) + self.assertEqual(len(qobj.experiments), 2) + self.assertEqual(qobj.experiments[1].config.n_qubits, 3) + self.assertEqual(len(qobj.experiments), 2) + self.assertEqual(len(qobj.experiments[1].instructions), 6) + + def test_assemble_no_run_config(self): + """Test assembling with no run_config, relying on default. + """ + q = QuantumRegister(2, name='q') + c = ClassicalRegister(2, name='c') + circ = QuantumCircuit(q, c, name='circ') + circ.h(q[0]) + circ.cx(q[0], q[1]) + circ.measure(q, c) + + qobj = assemble_circuits(circ) + self.assertIsInstance(qobj, Qobj) + self.assertIsNone(getattr(qobj.config, 'shots', None)) + + def test_assemble_initialize(self): + """Test assembling a circuit with an initialize. + """ + q = QuantumRegister(2, name='q') + circ = QuantumCircuit(q, name='circ') + circ.initialize([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], q[:]) + + qobj = assemble_circuits(circ) + self.assertIsInstance(qobj, Qobj) + self.assertEqual(qobj.experiments[0].instructions[0].name, 'init') + np.testing.assert_almost_equal(qobj.experiments[0].instructions[0].params, + [0.7071067811865, 0, 0, 0.707106781186]) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/test/python/tools/test_compiler.py b/test/python/compiler/test_compiler.py similarity index 100% rename from test/python/tools/test_compiler.py rename to test/python/compiler/test_compiler.py diff --git a/test/python/converters/test_qobj_to_circuits.py b/test/python/converters/test_qobj_to_circuits.py index b3fbcc3be40a..b66c62484375 100644 --- a/test/python/converters/test_qobj_to_circuits.py +++ b/test/python/converters/test_qobj_to_circuits.py @@ -5,17 +5,16 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=redefined-builtin # pylint: disable=unused-import """Tests for the converters.""" import unittest -from qiskit.converters import qobj_to_circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer -from qiskit import compile +from qiskit.compiler import assemble_circuits +from qiskit.converters import qobj_to_circuits from qiskit.qobj import Qobj, QobjConfig, QobjHeader from qiskit.transpiler import PassManager @@ -37,14 +36,12 @@ def setUp(self): def test_qobj_to_circuits_single(self): """Check that qobj_to_circuits's result matches the qobj ini.""" - backend = BasicAer.get_backend('qasm_simulator') - qobj_in = compile(self.circuit, backend, pass_manager=PassManager()) + qobj_in = assemble_circuits(self.circuit) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), self.dag) def test_qobj_to_circuits_multiple(self): """Check that qobj_to_circuits's result with multiple circuits""" - backend = BasicAer.get_backend('qasm_simulator') qreg1 = QuantumRegister(2) qreg2 = QuantumRegister(3) creg1 = ClassicalRegister(2) @@ -54,13 +51,12 @@ def test_qobj_to_circuits_multiple(self): circuit_b.h(qreg2) circuit_b.measure(qreg1, creg1) circuit_b.measure(qreg2[0], creg2[1]) - qobj = compile([self.circuit, circuit_b], backend, pass_manager=PassManager()) + qobj = assemble_circuits([self.circuit, circuit_b]) dag_list = [circuit_to_dag(x) for x in qobj_to_circuits(qobj)] self.assertEqual(dag_list, [self.dag, circuit_to_dag(circuit_b)]) def test_qobj_to_circuit_with_parameters(self): """Check qobj_to_circuit result with a gate that uses parameters.""" - backend = BasicAer.get_backend('qasm_simulator') qreg1 = QuantumRegister(2) qreg2 = QuantumRegister(3) creg1 = ClassicalRegister(2) @@ -71,14 +67,13 @@ def test_qobj_to_circuit_with_parameters(self): circuit_b.u2(0.2, 0.57, qreg2[1]) circuit_b.measure(qreg1, creg1) circuit_b.measure(qreg2[0], creg2[1]) - qobj = compile(circuit_b, backend, pass_manager=PassManager()) + qobj = assemble_circuits(circuit_b) out_circuit = qobj_to_circuits(qobj) self.assertEqual(circuit_to_dag(out_circuit[0]), circuit_to_dag(circuit_b)) def test_qobj_to_circuit_with_sim_instructions(self): """Check qobj_to_circuit result with asimulator instruction.""" - backend = BasicAer.get_backend('qasm_simulator') qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) @@ -86,7 +81,7 @@ def test_qobj_to_circuit_with_sim_instructions(self): circuit.snapshot(1) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) - qobj_in = compile(circuit, backend, pass_manager=PassManager()) + qobj_in = assemble_circuits(circuit) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), dag) @@ -101,14 +96,12 @@ def test_qobj_to_circuits_with_nothing(self): def test_qobj_to_circuits_single_no_qasm(self): """Check that qobj_to_circuits's result matches the qobj ini.""" - backend = BasicAer.get_backend('qasm_simulator') - qobj_in = compile(self.circuit, backend, pass_manager=PassManager()) + qobj_in = assemble_circuits(self.circuit) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), self.dag) def test_qobj_to_circuits_multiple_no_qasm(self): """Check that qobj_to_circuits's result with multiple circuits""" - backend = BasicAer.get_backend('qasm_simulator') qreg1 = QuantumRegister(2) qreg2 = QuantumRegister(3) creg1 = ClassicalRegister(2) @@ -118,8 +111,7 @@ def test_qobj_to_circuits_multiple_no_qasm(self): circuit_b.h(qreg2) circuit_b.measure(qreg1, creg1) circuit_b.measure(qreg2[0], creg2[1]) - qobj = compile([self.circuit, circuit_b], backend, - pass_manager=PassManager()) + qobj = assemble_circuits([self.circuit, circuit_b]) dag_list = [circuit_to_dag(x) for x in qobj_to_circuits(qobj)] self.assertEqual(dag_list, [self.dag, circuit_to_dag(circuit_b)]) diff --git a/test/python/notebooks/test_pbar_status.ipynb b/test/python/notebooks/test_pbar_status.ipynb index dad08bb3b763..7e54a646bc91 100644 --- a/test/python/notebooks/test_pbar_status.ipynb +++ b/test/python/notebooks/test_pbar_status.ipynb @@ -3,7 +3,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import os\n", @@ -16,10 +18,14 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ - "from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute, compile\n", + "from qiskit import BasicAer, execute\n", + "from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit\n", + "from qiskit.compiler import transpile, TranspileConfig\n", "from qiskit.tools.parallel import parallel_map\n", "from qiskit.tools.monitor import job_monitor\n", "from qiskit.tools.events import TextProgressBar\n", @@ -29,7 +35,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "sim_backend = BasicAer.get_backend('qasm_simulator')" @@ -38,7 +46,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import time\n", @@ -57,7 +67,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "HTMLProgressBar()\n", @@ -74,7 +86,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "%%qiskit_progress_bar\n", @@ -91,7 +105,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "TextProgressBar()\n", @@ -108,7 +124,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "%%qiskit_progress_bar -t text\n", @@ -119,13 +137,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Check compiler spawns progress bar" + "## Check transpile spawns progress bar" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "q = QuantumRegister(2)\n", @@ -137,7 +157,7 @@ "qc.measure(q, c)\n", "\n", "HTMLProgressBar()\n", - "qobj = compile([qc]*20, backend=sim_backend)" + "qobj = transpile([qc]*20, TranspileConfig(backend=sim_backend))" ] }, { @@ -150,7 +170,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "%%qiskit_job_status\n", @@ -175,7 +197,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "job_sim2 = execute([qc]*10, backend=sim_backend)\n", @@ -185,7 +209,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "job_sim3 = execute([qc]*10, backend=sim_backend)\n", @@ -195,7 +221,9 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [] } @@ -217,7 +245,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.0" + "version": "3.6.3" }, "nteract": { "version": "0.12.3" diff --git a/test/python/qobj/test_qobj.py b/test/python/qobj/test_qobj.py index 208cdcbcbe1e..11234a8607a4 100644 --- a/test/python/qobj/test_qobj.py +++ b/test/python/qobj/test_qobj.py @@ -5,7 +5,6 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -# pylint: disable=redefined-builtin """Qobj tests.""" @@ -14,7 +13,8 @@ import jsonschema from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, BasicAer +from qiskit import BasicAer +from qiskit.compiler import assemble_circuits, RunConfig from qiskit.qobj.exceptions import SchemaValidationError from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction @@ -118,7 +118,7 @@ def test_change_qobj_after_compile(self): qc2.measure(qr, cr) circuits = [qc1, qc2] backend = BasicAer.get_backend('qasm_simulator') - qobj1 = compile(circuits, backend=backend, shots=1024, seed=88) + qobj1 = assemble_circuits(circuits, RunConfig(backend=backend, shots=1024, seed=88)) qobj1.experiments[0].config.shots = 50 qobj1.experiments[1].config.shots = 1 self.assertTrue(qobj1.experiments[0].config.shots == 50) diff --git a/test/python/qobj/test_qobj_identifiers.py b/test/python/qobj/test_qobj_identifiers.py index 2d3951fecb60..60cbd94d89f4 100644 --- a/test/python/qobj/test_qobj_identifiers.py +++ b/test/python/qobj/test_qobj_identifiers.py @@ -11,8 +11,8 @@ import unittest -from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit import compile, BasicAer +from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister +from qiskit.compiler import assemble_circuits from qiskit.test import QiskitTestCase @@ -30,22 +30,19 @@ def setUp(self): self.circuits = [qc] def test_builtin_qasm_simulator_py(self): - backend = BasicAer.get_backend('qasm_simulator') - qobj = compile(self.circuits, backend=backend) + qobj = assemble_circuits(self.circuits) exp = qobj.experiments[0] self.assertIn(self.qr_name, map(lambda x: x[0], exp.header.qubit_labels)) self.assertIn(self.cr_name, map(lambda x: x[0], exp.header.clbit_labels)) def test_builtin_qasm_simulator(self): - backend = BasicAer.get_backend('qasm_simulator') - qobj = compile(self.circuits, backend=backend) + qobj = assemble_circuits(self.circuits) exp = qobj.experiments[0] self.assertIn(self.qr_name, map(lambda x: x[0], exp.header.qubit_labels)) self.assertIn(self.cr_name, map(lambda x: x[0], exp.header.clbit_labels)) def test_builtin_unitary_simulator_py(self): - backend = BasicAer.get_backend('unitary_simulator') - qobj = compile(self.circuits, backend=backend) + qobj = assemble_circuits(self.circuits) exp = qobj.experiments[0] self.assertIn(self.qr_name, map(lambda x: x[0], exp.header.qubit_labels)) self.assertIn(self.cr_name, map(lambda x: x[0], exp.header.clbit_labels)) diff --git a/test/python/transpiler/test_mappers.py b/test/python/transpiler/test_mappers.py index 9f4bc458bd80..bb81b20df831 100644 --- a/test/python/transpiler/test_mappers.py +++ b/test/python/transpiler/test_mappers.py @@ -61,14 +61,15 @@ def test_a_common_test(self): ``` """ -# pylint: disable=redefined-builtin,attribute-defined-outside-init +# pylint: disable=attribute-defined-outside-init import unittest import pickle import sys import os -from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer, compile +from qiskit import execute +from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer from qiskit.transpiler import PassManager, transpile from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap from qiskit.mapper import CouplingMap, Layout @@ -114,13 +115,12 @@ def generate_ground_truth(self, transpiled_result, filename): (self.create_backend()). That's saved in a pickle in filename. Args: - transpiled_result (DAGCircuit): The DAGCircuit to compile and run. + transpiled_result (DAGCircuit): The DAGCircuit to execute. filename (string): Where the pickle is saved. """ sim_backend = self.create_backend() - qobj = compile(transpiled_result, sim_backend, seed=self.seed, shots=self.shots, - seed_mapper=self.seed_mapper) - job = sim_backend.run(qobj) + job = execute(transpiled_result, sim_backend, seed=self.seed, shots=self.shots, + seed_mapper=self.seed_mapper) self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta) with open(filename, "wb") as output_file: diff --git a/test/python/transpiler/test_transpile.py b/test/python/transpiler/test_transpile.py index 09ab71c4db8f..f6c04eb4cd8f 100644 --- a/test/python/transpiler/test_transpile.py +++ b/test/python/transpiler/test_transpile.py @@ -12,10 +12,10 @@ from qiskit import QuantumRegister, QuantumCircuit from qiskit import compile, BasicAer from qiskit.transpiler import PassManager, transpile_dag, transpile -from qiskit.tools.compiler import circuits_to_qobj +from qiskit.compiler import assemble_circuits from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase -from qiskit.qobj.run_config import RunConfig +from qiskit.compiler import RunConfig class TestTranspile(QiskitTestCase): @@ -68,5 +68,5 @@ def test_pass_manager_none(self): qobj = compile(circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates) run_config = RunConfig(shots=1024, max_credits=10) - qobj2 = circuits_to_qobj(circuit2, qobj_id=qobj.qobj_id, run_config=run_config) + qobj2 = assemble_circuits(circuit2, qobj_id=qobj.qobj_id, run_config=run_config) self.assertEqual(qobj, qobj2)