def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling_map = [[1, 0]] basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] backend = BasicAer.get_backend('qasm_simulator') circuit2 = transpile(circuit, backend, coupling_map=coupling_map, basis_gates=basis_gates, pass_manager=None) qobj = compile(circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates) run_config = RunConfig(shots=1024, max_credits=10) qobj2 = assemble_circuits(circuit2, qobj_id=qobj.qobj_id, run_config=run_config) self.assertEqual(qobj, qobj2)
def _compile_wrapper(circuits, backend, backend_config, compile_config, run_config): transpiled_circuits = transpiler.transpile(circuits, backend, **backend_config, **compile_config) qobj = assemble_circuits(transpiled_circuits, run_config=run_config) return qobj, transpiled_circuits
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_job_qobj(self): """Test job.qobj().""" for backend in BasicAer.backends(): with self.subTest(backend=backend): qobj = assemble_circuits(self.qc1, TranspileConfig(backend=backend)) job = backend.run(qobj) self.assertEqual(job.qobj(), qobj)
def test_builtin_unitary_simulator_py(self): 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_qobj_to_circuits_with_initialize(self): """Check qobj_to_circuit's result with initialize.""" q = QuantumRegister(2, name='q') circ = QuantumCircuit(q, name='circ') circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) dag = circuit_to_dag(circ) qobj = assemble_circuits(circ) out_circuit = qobj_to_circuits(qobj)[0] self.assertEqual(circuit_to_dag(out_circuit), dag)
def test_initialize_2(self): """Test StatevectorSimulator initialize""" circuits = ref_initialize.initialize_circuits_2(final_measure=False) targets = ref_initialize.initialize_statevector_2() qobj = assemble_circuits(circuits, run_config=RunConfig(shots=1)) sim_job = StatevectorSimulator().run(qobj) result = sim_job.result() self.is_completed(result) self.compare_statevector(result, circuits, targets)
def test_job_qobj(self): """Test job.qobj().""" for backend in qiskit.providers.aer.Aer.backends(): with self.subTest(backend=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)
def test_compile_quantum_circuit(self): """Test instantiating gate with variable parmeters""" theta = sympy.Symbol('θ') qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend('qasm_simulator') qc_aer = transpile(qc, backend) qobj = assemble_circuits(qc_aer) self.assertIn(theta, qobj.experiments[0].instructions[0].params)
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 """ 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) run_config = RunConfig() 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 new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, seed_mapper, pass_manager) qobj = assemble_circuits(new_circuits, qobj_header=None, run_config=run_config, qobj_id=qobj_id) return qobj
def setUp(self): super(TestBasicAerQasmSimulator, self).setUp() self.seed = 88 qasm_filename = self._get_resource_path('example.qasm', Path.QASMS) 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_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])
def test_qobj_to_circuit_with_sim_instructions(self): """Check qobj_to_circuit result with asimulator instruction.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.snapshot(1) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) qobj_in = assemble_circuits(circuit) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), dag)
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_qobj_to_circuits_multiple(self): """Check that qobj_to_circuits's result with multiple circuits""" qreg1 = QuantumRegister(2) qreg2 = QuantumRegister(3) creg1 = ClassicalRegister(2) creg2 = ClassicalRegister(2) circuit_b = QuantumCircuit(qreg1, qreg2, creg1, creg2) circuit_b.x(qreg1) circuit_b.h(qreg2) circuit_b.measure(qreg1, creg1) circuit_b.measure(qreg2[0], creg2[1]) 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.""" qreg1 = QuantumRegister(2) qreg2 = QuantumRegister(3) creg1 = ClassicalRegister(2) creg2 = ClassicalRegister(2) circuit_b = QuantumCircuit(qreg1, qreg2, creg1, creg2) circuit_b.x(qreg1) circuit_b.h(qreg2) circuit_b.u2(0.2, 0.57, qreg2[1]) circuit_b.measure(qreg1, creg1) circuit_b.measure(qreg2[0], creg2[1]) 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 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)
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_qobj_headers_in_result(self): """Test that the qobj headers are passed onto the results.""" 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): 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) # Update the Qobj.experiment header. qobj.experiments[0].header.some_field = 'extra info' result = backend.run(qobj).result() self.assertEqual(result.header.to_dict(), custom_qobj_header) self.assertEqual(result.results[0].header.some_field, 'extra info')
def test_circuit_generation(self): """Test creating a series of circuits parametrically""" theta = sympy.Symbol('θ') qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend('qasm_simulator') qc_aer = transpile(qc, backend) # generate list of circuits circs = [] theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(qc_aer.assign_variables({theta: theta_i})) qobj = assemble_circuits(circs) for index, theta_i in enumerate(theta_list): self.assertEqual(qobj.experiments[index].instructions[0].params[0], theta_i)
def test_convert_to_bfunc_plus_conditional(self): """Verify assemble_circuits converts conditionals from QASM to Qobj.""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) qobj = assemble_circuits(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, 'bfunc') self.assertEqual(bfunc_op.mask, '0x1') self.assertEqual(bfunc_op.val, '0x1') self.assertEqual(bfunc_op.relation, '==') self.assertTrue(hasattr(h_op, 'conditional')) self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_opaque_inst(self): """Test opaque instruction is assembled as-is""" opaque_inst = Instruction(name='my_inst', num_qubits=4, num_clbits=2, params=[0.5, 0.4]) q = QuantumRegister(6, name='q') c = ClassicalRegister(4, name='c') circ = QuantumCircuit(q, c, name='circ') circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) qobj = assemble_circuits(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(len(qobj.experiments[0].instructions), 1) self.assertEqual(qobj.experiments[0].instructions[0].name, 'my_inst') self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3]) self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0]) self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_change_qobj_after_compile(self): """Test modifying Qobj parameters after compile.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[0], qr[2]) qc2.h(qr) qc1.measure(qr, cr) qc2.measure(qr, cr) circuits = [qc1, qc2] backend = BasicAer.get_backend('qasm_simulator') 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) self.assertTrue(qobj1.experiments[1].config.shots == 1) self.assertTrue(qobj1.config.shots == 1024)
def test_resize_value_to_register(self): """Verify assemble_circuits converts the value provided on the classical creg to its mapped location on the device register.""" qr = QuantumRegister(1) cr1 = ClassicalRegister(2) cr2 = ClassicalRegister(2) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) qc.h(qr[0]).c_if(cr2, 2) qobj = assemble_circuits(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, 'bfunc') self.assertEqual(bfunc_op.mask, '0xC') self.assertEqual(bfunc_op.val, '0x8') self.assertEqual(bfunc_op.relation, '==') self.assertTrue(hasattr(h_op, 'conditional')) self.assertEqual(bfunc_op.register, h_op.conditional)
def test_measure_to_registers_when_conditionals(self): """Verify assemble_circuits maps all measure ops on to a register slot for a circuit containing conditionals.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr1, cr2) qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) qobj = assemble_circuits(qc) first_measure, second_measure = [ op for op in qobj.experiments[0].instructions if op.name == 'measure' ] self.assertTrue(hasattr(first_measure, 'register')) self.assertEqual(first_measure.register, first_measure.memory) self.assertTrue(hasattr(second_measure, 'register')) self.assertEqual(second_measure.register, second_measure.memory)
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, coupling_map=None, seed=None, memory=None): """Convert a list of circuits into a qobj. Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile qobj_header (QobjHeader): header to pass to the results run_config (RunConfig): RunConfig object 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 max_credits (int): TODO: delete after qiskit-terra 0.8 basis_gates (str): TODO: delete after qiskit-terra 0.8 coupling_map (list): TODO: delete after qiskit-terra 0.8 seed (int): TODO: delete after qiskit-terra 0.8 memory (bool): TODO: delete after qiskit-terra 0.8 Returns: Qobj: the Qobj to be run on the backends """ 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 backend_name: warnings.warn('backend_name is not required anymore', DeprecationWarning) qobj_header.backend_name = backend_name if config: warnings.warn( 'config is not used anymore. Set all configs in ' 'run_config.', DeprecationWarning) if shots: warnings.warn('shots is not used anymore. Set it via run_config.', DeprecationWarning) run_config.shots = shots if basis_gates: warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning) if coupling_map: warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning) if seed: warnings.warn('seed is not used anymore. Set it via run_config', DeprecationWarning) run_config.seed = seed if memory: warnings.warn('memory is not used anymore. Set it via run_config', DeprecationWarning) run_config.memory = memory 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) qobj = assemble_circuits(circuits, qobj_header, run_config) return qobj
# 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) # Assemble the two circuits into a runnable qobj qobj = assemble_circuits([qc1_new, qc2_new], run_config=RunConfig(shots=1000)) # Running qobj on the simulator sim_job = qasm_simulator.run(qobj) # Getting the result sim_result = sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. exp_job = least_busy_device.run(qobj) job_monitor(exp_job)
def test_qobj_to_circuits_single_no_qasm(self): """Check that qobj_to_circuits's result matches the qobj ini.""" qobj_in = assemble_circuits(self.circuit) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), self.dag)