def test_run_async_simulator(self): IBMQJob._executor = futures.ThreadPoolExecutor(max_workers=2) backend = self._provider.get_backend('ibmq_qasm_simulator') self.log.info('submitting to backend %s', backend.name) num_qubits = 16 qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(num_qubits, 'cr') qc = QuantumCircuit(qr, cr) for i in range(num_qubits - 1): qc.cx(qr[i], qr[i + 1]) qc.measure(qr, cr) qobj = transpiler.compile([qc] * 10, backend) num_jobs = 5 job_array = [backend.run(qobj) for _ in range(num_jobs)] found_async_jobs = False timeout = 30 start_time = time.time() while not found_async_jobs: check = sum([job.running for job in job_array]) if check >= 2: self.log.info('found %d simultaneous jobs', check) break if all([job.done for job in job_array]): # done too soon? don't generate error self.log.warning('all jobs completed before simultaneous jobs ' 'could be detected') break for job in job_array: self.log.info('%s %s %s %s', job.status['status'], job.running, check, job.id) self.log.info('-' * 20 + ' ' + str(time.time() - start_time)) if time.time() - start_time > timeout: raise TimeoutError('failed to see multiple running jobs after ' '{0} s'.format(timeout)) time.sleep(0.2) result_array = [job.result() for job in job_array] self.log.info('got back all job results') # Ensure all jobs have finished. self.assertTrue(all([job.done for job in job_array])) self.assertTrue( all([ result.get_status() == 'COMPLETED' for result in result_array ])) # Ensure job ids are unique. job_ids = [job.id for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
def test_compile_circuits_diff_registers(self): """Compile list of circuits with different qreg names. """ backend = FakeBackEnd() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) qobj = transpiler.compile(circuits, backend) self.assertIsInstance(qobj, Qobj)
def test_run_async_device(self): backends = self._provider.available_backends({'simulator': False}) backend = lowest_pending_jobs(backends) self.log.info('submitting to backend %s', backend.name) num_qubits = 5 qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(num_qubits, 'cr') qc = QuantumCircuit(qr, cr) for i in range(num_qubits - 1): qc.cx(qr[i], qr[i + 1]) qc.measure(qr, cr) qobj = transpiler.compile(qc, backend) num_jobs = 3 job_array = [backend.run(qobj) for _ in range(num_jobs)] time.sleep(3) # give time for jobs to start (better way?) job_status = [job.status['status'] for job in job_array] num_init = sum( [status == JobStatus.INITIALIZING for status in job_status]) num_queued = sum([status == JobStatus.QUEUED for status in job_status]) num_running = sum( [status == JobStatus.RUNNING for status in job_status]) num_done = sum([status == JobStatus.DONE for status in job_status]) num_error = sum([status == JobStatus.ERROR for status in job_status]) self.log.info('number of currently initializing jobs: %d/%d', num_init, num_jobs) self.log.info('number of currently queued jobs: %d/%d', num_queued, num_jobs) self.log.info('number of currently running jobs: %d/%d', num_running, num_jobs) self.log.info('number of currently done jobs: %d/%d', num_done, num_jobs) self.log.info('number of errored jobs: %d/%d', num_error, num_jobs) self.assertTrue(num_jobs - num_error - num_done > 0) # Wait for all the results. result_array = [job.result() for job in job_array] # Ensure all jobs have finished. self.assertTrue(all([job.done for job in job_array])) self.assertTrue( all([ result.get_status() == 'COMPLETED' for result in result_array ])) # Ensure job ids are unique. job_ids = [job.id for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
def test_cancel(self): if not self.using_ibmq_credentials: self.skipTest('job cancellation currently only available on hubs') backends = [ backend for backend in self._provider.available_backends() if not backend.configuration['simulator'] ] self.log.info('devices: %s', [b.name for b in backends]) backend = backends[0] self.log.info('using backend: %s', backend.name) num_qubits = 5 qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(num_qubits, 'cr') qc = QuantumCircuit(qr, cr) for i in range(num_qubits - 1): qc.cx(qr[i], qr[i + 1]) qc.measure(qr, cr) qobj = transpiler.compile(qc, backend) num_jobs = 3 job_array = [backend.run(qobj) for _ in range(num_jobs)] success = False self.log.info('jobs submitted: %s', num_jobs) while any([ job.status['status'] == JobStatus.INITIALIZING for job in job_array ]): self.log.info('jobs initializing') time.sleep(1) for job in job_array: job.cancel() while not success: job_status = [job.status for job in job_array] for status in job_status: self.log.info(status) if any([ status['status'] == JobStatus.CANCELLED for status in job_status ]): success = True if all( [status['status'] == JobStatus.DONE for status in job_status]): raise IBMQJobError( 'all jobs completed before any could be cancelled') self.log.info('-' * 20) time.sleep(2) self.assertTrue(success)
def test_compile_run(self): """Test Compiler and run. If all correct some should exists. """ backend = get_backend('local_qasm_simulator') qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) result = backend.run(qobj).result() self.assertIsInstance(result, Result)
def test_compile_run_remote(self, qe_token, qe_url): """Test Compiler and run remote. If all correct some should exists. """ register(qe_token, qe_url) backend = available_backends({'local': False, 'simulator': True})[0] backend = get_backend(backend) qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend, seed=TestCompiler.seed) job = backend.run(qobj) result = job.result(timeout=20) self.assertIsInstance(result, Result)
def test_compile(self): """Test Compiler. If all correct some should exists. """ backend = qiskit.Aer.get_backend('local_qasm_simulator') qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) # FIXME should validate the Qobj when defined self.assertIsInstance(qobj, Qobj)
def test_compile(self): """Test Compiler. If all correct some should exists. """ backend = get_backend('local_qasm_simulator') qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) # FIXME should test against the qobj when defined self.assertEqual(len(qobj), 3)
def test_compile_run_remote(self, qe_token, qe_url): """Test Compiler and run remote. If all correct some should exists. """ qiskit.IBMQ.use_account(qe_token, qe_url) backend = qiskit.IBMQ.get_backend(local=False, simulator=True) qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend, seed=TestCompiler.seed) job = backend.run(qobj) result = job.result(timeout=20) self.assertIsInstance(result, Result)
def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs. """ backend = FakeBackEnd() qr = QuantumRegister(3, name='qr') qr2 = QuantumRegister(1, name='qr2') qr3 = QuantumRegister(4, name='qr3') cr = ClassicalRegister(3, name='cr') qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) try: qobj = transpiler.compile(qc, backend) except QISKitError: qobj = None self.assertIsInstance(qobj, Qobj)
def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs. """ backend = FakeBackEnd() q = qiskit.QuantumRegister(3, name='qr') q2 = qiskit.QuantumRegister(1, name='qr2') q3 = qiskit.QuantumRegister(4, name='qr3') c = qiskit.ClassicalRegister(3, name='cr') qc = qiskit.QuantumCircuit(q, q2, q3, c) qc.h(q[0]) qc.cx(q[0], q2[0]) qc.cx(q[1], q3[2]) qc.measure(q, c) try: qobj = transpiler.compile(qc, backend) except QISKitError: qobj = None self.assertIsInstance(qobj, dict)
def test_compile_remote(self, qe_token, qe_url): """Test Compiler remote. If all correct some should exists. """ qiskit.IBMQ.use_account(qe_token, qe_url) backend = least_busy(qiskit.IBMQ.backends()) qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) # FIXME should validate the Qobj when defined self.assertIsInstance(qobj, Qobj)
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, hpc=None, skip_transpiler=False): """Compile a list of circuits into a qobj. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend or str): a backend to compile for config (dict): dictionary of parameters (e.g. noise) used by runner basis_gates (str): comma-separated basis gate set to compile to 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 qobj_id (int): identifier for the generated qobj hpc (dict): HPC simulator parameters skip_transpiler (bool): If True, bypass most of the compilation process and creates a qobj with minimal check nor translation Returns: Qobj: the qobj to be run on the backends """ # pylint: disable=redefined-builtin if isinstance(backend, str): backend = _DEFAULT_PROVIDER.get_backend(backend) pass_manager = None # default pass manager which executes predetermined passes if skip_transpiler: # empty pass manager which does nothing pass_manager = transpiler.PassManager() return transpiler.compile(circuits, backend, config, basis_gates, coupling_map, initial_layout, shots, max_credits, seed, qobj_id, hpc, pass_manager)
def test_compile_two_run_remote(self, QE_TOKEN, QE_URL, hub=None, group=None, project=None): """Test Compiler and run two circuits. If all correct some should exists. """ register(QE_TOKEN, QE_URL, hub, group, project) backend = available_backends({'local': False, 'simulator': True})[0] backend = get_backend(backend) qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) qobj = transpiler.compile([qc, qc_extra], backend) job = backend.run(qobj) result = job.result() self.assertIsInstance(result, Result)
def test_execute_one_circuit_simulator_online(self, qe_token, qe_url): """Test execute_one_circuit_simulator_online. If all correct should return correct counts. """ provider = IBMQProvider(qe_token, qe_url) backend = provider.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qobj = transpiler.compile(qc, backend, seed=73846087) shots = qobj.config.shots job = backend.run(qobj) result = job.result() counts = result.get_counts(qc) target = {'0': shots / 2, '1': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold)
def test_compile_remote(self, QE_TOKEN, QE_URL, hub=None, group=None, project=None): """Test Compiler remote. If all correct some should exists. """ register(QE_TOKEN, QE_URL, hub, group, project) backend = least_busy(available_backends()) backend = get_backend(backend) qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) # FIXME should validate the Qobj when defined self.assertIsInstance(qobj, Qobj)
def test_mapping_already_satisfied(self): """Test compiler doesn't change circuit already matching backend coupling """ backend = FakeBackEnd() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[1]) qc.x(qr[2]) qc.x(qr[3]) qc.x(qr[4]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[3]) qc.cx(qr[3], qr[4]) qc.cx(qr[3], qr[14]) qc.measure(qr, cr) qobj = transpiler.compile(qc, backend) compiled_ops = qobj.experiments[0].instructions for operation in compiled_ops: if operation.name == 'cx': self.assertIn(operation.qubits, backend.configuration()['coupling_map'])
def test_compile_two_remote(self, qe_token, qe_url): """Test Compiler remote on two circuits. If all correct some should exists. """ register(qe_token, qe_url) backend = least_busy(available_backends()) backend = get_backend(backend) qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) qobj = transpiler.compile([qc, qc_extra], backend) # FIXME should validate the Qobj when defined self.assertIsInstance(qobj, Qobj)
def test_mapping_already_satisfied(self): """Test compiler doesn't change circuit already matching backend coupling """ backend = FakeBackEnd() q = qiskit.QuantumRegister(16) c = qiskit.ClassicalRegister(16) qc = qiskit.QuantumCircuit(q, c) qc.h(q[1]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.cx(q[1], q[2]) qc.cx(q[2], q[3]) qc.cx(q[3], q[4]) qc.cx(q[3], q[14]) qc.measure(q, c) qobj = transpiler.compile(qc, backend) compiled_ops = qobj['circuits'][0]['compiled_circuit']['operations'] for op in compiled_ops: if op['name'] == 'cx': self.assertIn(op['qubits'], backend.configuration['coupling_map'])
def test_run_simulator(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr, name='hadamard') qc.h(qr) qc.measure(qr, cr) qobj = transpiler.compile([self._qc, qc], backend) shots = qobj.config.shots job = backend.run(qobj) result = job.result() counts_qx1 = result.get_counts(result.get_names()[0]) counts_qx2 = result.get_counts('hadamard') counts_ex1 = {'00': shots / 2, '11': shots / 2} counts_ex2 = { '00': shots / 4, '11': shots / 4, '10': shots / 4, '01': shots / 4 } states1 = counts_qx1.keys() | counts_ex1.keys() states2 = counts_qx2.keys() | counts_ex2.keys() # contingency table ctable1 = numpy.array([[counts_qx1.get(key, 0) for key in states1], [counts_ex1.get(key, 0) for key in states1]]) ctable2 = numpy.array([[counts_qx2.get(key, 0) for key in states2], [counts_ex2.get(key, 0) for key in states2]]) self.log.info('states1: %s', str(states1)) self.log.info('states2: %s', str(states2)) self.log.info('ctable1: %s', str(ctable1)) self.log.info('ctable2: %s', str(ctable2)) contingency1 = chi2_contingency(ctable1) contingency2 = chi2_contingency(ctable2) self.log.info('chi2_contingency1: %s', str(contingency1)) self.log.info('chi2_contingency2: %s', str(contingency2)) self.assertGreater(contingency1[1], 0.01) self.assertGreater(contingency2[1], 0.01)
def test_compile_run_remote(self, QE_TOKEN, QE_URL, hub=None, group=None, project=None): """Test Compiler and run remote. If all correct some should exists. """ provider = IBMQProvider(QE_TOKEN, QE_URL, hub, group, project) backend = provider.available_backends({'simulator': True})[0] qubit_reg = qiskit.QuantumRegister(2, name='q') clbit_reg = qiskit.ClassicalRegister(2, name='c') qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qobj = transpiler.compile(qc, backend) job = backend.run(qobj) result = job.result(timeout=20) self.assertIsInstance(result, Result)
def test_execute_several_circuits_simulator_online(self, qe_token, qe_url): """Test execute_several_circuits_simulator_online. If all correct should return correct counts. """ IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(2) cr = ClassicalRegister(2) qcr1 = QuantumCircuit(qr, cr) qcr2 = QuantumCircuit(qr, cr) qcr1.h(qr) qcr2.h(qr[0]) qcr2.cx(qr[0], qr[1]) qcr1.measure(qr[0], cr[0]) qcr1.measure(qr[1], cr[1]) qcr2.measure(qr[0], cr[0]) qcr2.measure(qr[1], cr[1]) shots = 1024 qobj = transpiler.compile([qcr1, qcr2], backend, seed=73846087, shots=shots) job = backend.run(qobj) result = job.result() counts1 = result.get_counts(qcr1) counts2 = result.get_counts(qcr2) target1 = { '00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4 } target2 = {'00': shots / 2, '11': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts1, target1, threshold) self.assertDictAlmostEqual(counts2, target2, threshold)
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, hpc=None, skip_transpiler=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 (str): comma-separated basis gate set to compile to 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 qobj_id (int): identifier for the generated qobj hpc (dict): HPC simulator parameters skip_transpiler (bool): skip most of the compile steps and produce qobj directly Returns: Qobj: the qobj to be run on the backends Raises: TranspilerError: in case of bad compile options, e.g. the hpc options. """ pass_manager = None # default pass manager which executes predetermined passes if skip_transpiler: # empty pass manager which does nothing pass_manager = PassManager() qobj_standard = transpiler.compile(circuits, backend, config, basis_gates, coupling_map, initial_layout, shots, max_credits, seed, qobj_id, hpc, pass_manager) return qobj_standard
def test_mapping_correction(self): """Test mapping works in previous failed case. """ backend = FakeBackEnd() q = qiskit.QuantumRegister(name='qr', size=11) c = qiskit.ClassicalRegister(name='qc', size=11) circuit = qiskit.QuantumCircuit(q, c) circuit.u3(1.564784764685993, -1.2378965763410095, 2.9746763177861713, q[3]) circuit.u3(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, q[5]) circuit.cx(q[5], q[3]) circuit.u1(0.856768317675967, q[3]) circuit.u3(-3.3911273825190915, 0.0, 0.0, q[5]) circuit.cx(q[3], q[5]) circuit.u3(2.159209321625547, 0.0, 0.0, q[5]) circuit.cx(q[5], q[3]) circuit.u3(0.30949966910232335, 1.1706201763833217, 1.738408691990081, q[3]) circuit.u3(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, q[5]) circuit.u3(1.330181833806101, 0.6003162754946363, -3.181264980452862, q[7]) circuit.u3(0.4885914820775024, 3.133297443244865, -2.794457469189904, q[8]) circuit.cx(q[8], q[7]) circuit.u1(2.2196187596178616, q[7]) circuit.u3(-3.152367609631023, 0.0, 0.0, q[8]) circuit.cx(q[7], q[8]) circuit.u3(1.2646005789809263, 0.0, 0.0, q[8]) circuit.cx(q[8], q[7]) circuit.u3(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, q[7]) circuit.u3(0.9267400575390405, 2.0526277839695153, 2.034202361069533, q[8]) circuit.u3(2.550304293455634, 3.8250017126569698, -2.1351609599720054, q[1]) circuit.u3(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, q[4]) circuit.cx(q[4], q[1]) circuit.u1(2.1899329069137394, q[1]) circuit.u3(-1.8371715243173294, 0.0, 0.0, q[4]) circuit.cx(q[1], q[4]) circuit.u3(0.4717053496327104, 0.0, 0.0, q[4]) circuit.cx(q[4], q[1]) circuit.u3(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, q[1]) circuit.u3(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, q[4]) circuit.u3(2.4204244021892807, -2.211701932616922, 3.8297006565735883, q[10]) circuit.u3(0.36660280497727255, 3.273119149343493, -1.8003362351299388, q[6]) circuit.cx(q[6], q[10]) circuit.u1(1.067395863586385, q[10]) circuit.u3(-0.7044917541291232, 0.0, 0.0, q[6]) circuit.cx(q[10], q[6]) circuit.u3(2.1830003849921527, 0.0, 0.0, q[6]) circuit.cx(q[6], q[10]) circuit.u3(2.1538343756723917, 2.2653381826084606, -3.550087952059485, q[10]) circuit.u3(1.307627685019188, -0.44686656993522567, -2.3238098554327418, q[6]) circuit.u3(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, q[9]) circuit.u3(2.1665254613904126, -1.281337664694577, -1.2424905413631209, q[0]) circuit.cx(q[0], q[9]) circuit.u1(2.6209599970201007, q[9]) circuit.u3(0.04680566321901303, 0.0, 0.0, q[0]) circuit.cx(q[9], q[0]) circuit.u3(1.7728411151289603, 0.0, 0.0, q[0]) circuit.cx(q[0], q[9]) circuit.u3(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, q[9]) circuit.u3(1.7369112924273789, -4.239660866163805, 1.0623389015296005, q[0]) circuit.barrier(q) circuit.measure(q, c) try: qobj = transpiler.compile(circuit, backend) except QISKitError: qobj = None self.assertIsInstance(qobj, dict)
def test_get_backend_name(self): backend_name = 'ibmq_qasm_simulator' backend = self._provider.get_backend(backend_name) qobj = transpiler.compile(self._qc, backend) job = backend.run(qobj) self.assertTrue(job.backend_name == backend_name)
def test_job_id(self): backend = self._provider.get_backend('ibmq_qasm_simulator') qobj = transpiler.compile(self._qc, backend) job = backend.run(qobj) self.log.info('job_id: %s', job.id) self.assertTrue(job.id is not None)
def test_qobject_enabled_job(self): """Job should be an instance of IBMQJob.""" qobj = transpiler.compile(self._qc, self._backend) job = self._backend.run(qobj) self.assertIsInstance(job, IBMQJob)
# 0. build circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(2) c = ClassicalRegister(2) circ = QuantumCircuit(q, c) circ.cx(q[0], q[1]) circ.cx(q[0], q[1]) circ.cx(q[0], q[1]) circ.cx(q[0], q[1]) circ.measure(q, c) # draw circuit from qiskit.tools.visualization import plot_circuit plot_circuit(circ) # 1. standard compile -- standard qiskit passes, when no PassManager given from qiskit import transpiler, load_qasm_string qobj_standard = transpiler.compile(circ, backend_device) compiled_standard = load_qasm_string( qobj_standard['circuits'][0]['compiled_circuit_qasm']) plot_circuit(compiled_standard) # 2. custom compile -- customize PassManager to run specific circuit transformations from qiskit.transpiler.passes import CXCancellation pm = transpiler.PassManager() pm.add_pass(CXCancellation()) qobj_custom = transpiler.compile(circ, backend_device, pass_manager=pm) compiled_custom = load_qasm_string( qobj_custom['circuits'][0]['compiled_circuit_qasm']) plot_circuit(compiled_custom)
def get_controlled_circuit(circuit, ctl_qubit, tgt_circuit=None, use_basis_gates=True): """ Construct the controlled version of a given circuit. Args: circuit (QuantumCircuit) : the base circuit ctl_qubit (indexed QuantumRegister) : the control qubit to use tgt_circuit (QuantumCircuit) : the target controlled circuit to be modified in-place use_basis_gates (bool) : boolean flag to indicate whether or not only basis gates should be used Return: a QuantumCircuit object with the base circuit being controlled by ctl_qubit """ if tgt_circuit is not None: qc = tgt_circuit else: qc = QuantumCircuit() # get all the qubits and clbits qregs = circuit.get_qregs() qubits = [] for name in qregs: if not qc.has_register(qregs[name]): qc.add(qregs[name]) qubits.extend(qregs[name]) cregs = circuit.get_cregs() clbits = [] for name in cregs: if not qc.has_register(cregs[name]): qc.add(cregs[name]) clbits.extend(cregs[name]) # get all operations from compiled circuit ops = transpiler.compile(circuit, get_aer_backend('qasm_simulator'), basis_gates='u1,u2,u3,cx,id' )['circuits'][0]['compiled_circuit']['operations'] # process all basis gates to add control if not qc.has_register(ctl_qubit[0]): qc.add(ctl_qubit[0]) for op in ops: if op['name'] == 'id': apply_cu3(qc, 0, 0, 0, ctl_qubit, qubits[op['qubits'][0]], use_basis_gates=use_basis_gates) elif op['name'] == 'u1': apply_cu1(qc, *op['params'], ctl_qubit, qubits[op['qubits'][0]], use_basis_gates=use_basis_gates) elif op['name'] == 'u2': apply_cu3(qc, np.pi / 2, *op['params'], ctl_qubit, qubits[op['qubits'][0]], use_basis_gates=use_basis_gates) elif op['name'] == 'u3': apply_cu3(qc, *op['params'], ctl_qubit, qubits[op['qubits'][0]], use_basis_gates=use_basis_gates) elif op['name'] == 'cx': apply_ccx(qc, ctl_qubit, *[qubits[i] for i in op['qubits']], use_basis_gates=use_basis_gates) elif op['name'] == 'measure': qc.measure(qubits[op['qubits'][0]], clbits[op['clbits'][0]]) else: raise RuntimeError('Unexpected operation {}.'.format(op['name'])) return qc