def test_two_unitary_simulator(self): """test running two circuits This test is similar to one in test_quantumprogram but doesn't use multiprocessing. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr) qc2.cx(qr[0], qr[1]) backend = UnitarySimulatorPy() qobj = compile([qc1, qc2], backend=backend) job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True)) unitary1 = job.result().get_unitary(qc1) unitary2 = job.result().get_unitary(qc2) unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5], [0.5, 0.5, -0.5, -0.5], [0.5, -0.5, -0.5, 0.5]]) unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0], [0, 1, 0, 0]]) norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1)) norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2)) self.assertAlmostEqual(norm1, 4) self.assertAlmostEqual(norm2, 4)
def test_yzy_zyz_cases(self): """yzy_to_zyz works in previously failed cases. See: https://github.com/Qiskit/qiskit-terra/issues/607 """ backend = FakeQX4BackEnd() qr = QuantumRegister(2) circ1 = QuantumCircuit(qr) circ1.cx(qr[0], qr[1]) circ1.rz(0.7, qr[1]) circ1.rx(1.570796, qr[1]) qobj1 = compile(circ1, backend) self.assertIsInstance(qobj1, Qobj) circ2 = QuantumCircuit(qr) circ2.y(qr[0]) circ2.h(qr[0]) circ2.s(qr[0]) circ2.h(qr[0]) qobj2 = compile(circ2, backend) self.assertIsInstance(qobj2, Qobj)
def test_teleport_waltz_basis_gates(self): """Test teleport gate circuits compiling to u1,u2,u3,cx""" shots = 2000 circuits = ref_algorithms.teleport_circuit() targets = ref_algorithms.teleport_counts(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_reset_deterministic(self): """Test QasmSimulator reset with for circuits with deterministic counts""" # For statevector output we can combine deterministic and non-deterministic # count output circuits shots = 100 circuits = ref_reset.reset_circuits_deterministic(final_measure=True) targets = ref_reset.reset_counts_deterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, backend_options=self.BACKEND_OPTS).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0)
def test_initialize_2(self): """Test QasmSimulator initializes""" # For statevector output we can combine deterministic and non-deterministic # count output circuits shots = 2000 circuits = ref_initialize.initialize_circuits_2(final_measure=True) targets = ref_initialize.initialize_counts_2(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, backend_options=self.BACKEND_OPTS).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_cancel(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backend_name = ('ibmq_20_tokyo' if self.using_ibmq_credentials else 'ibmqx4') backend = IBMQ.get_backend(backend_name) qobj = compile(self._qc, backend) job = backend.run(qobj) self.wait_for_initialization(job, timeout=5) can_cancel = job.cancel() self.assertTrue(can_cancel) self.assertTrue(job.status() is JobStatus.CANCELLED)
def test_fusion_verbose(self): """Test Fusion with verbose option""" circuit = self.create_statevector_circuit() shots = 100 qobj = compile([circuit], self.SIMULATOR, shots=shots, seed=1) result_verbose = self.SIMULATOR.run(qobj, backend_options={ 'fusion_enable': True, 'fusion_verbose': True, 'fusion_threshold': 1 }).result() self.is_completed(result_verbose) self.assertTrue('results' in result_verbose.as_dict(), msg="results must exist in result") self.assertTrue('metadata' in result_verbose.as_dict()['results'][0], msg="metadata must exist in results[0]") self.assertTrue('fusion_verbose' in result_verbose.as_dict()['results'][0]['metadata'], msg="fusion must work for satevector") result_nonverbose = self.SIMULATOR.run(qobj, backend_options={ 'fusion_enable': True, 'fusion_verbose': False, 'fusion_threshold': 1 }).result() self.is_completed(result_nonverbose) self.assertTrue('results' in result_nonverbose.as_dict(), msg="results must exist in result") self.assertTrue('metadata' in result_nonverbose.as_dict()['results'][0], msg="metadata must exist in results[0]") self.assertTrue( 'fusion_verbose' not in result_nonverbose.as_dict()['results'][0]['metadata'], msg="verbose must not work if fusion_verbose is False") result_default = self.SIMULATOR.run(qobj, backend_options={ 'fusion_enable': True }).result() self.is_completed(result_default) self.assertTrue('results' in result_default.as_dict(), msg="results must exist in result") self.assertTrue('metadata' in result_default.as_dict()['results'][0], msg="metadata must exist in results[0]") self.assertTrue( 'fusion_verbose' not in result_default.as_dict()['results'][0]['metadata'], msg="verbose must not work if fusion_verbose is False")
def test_one_qubit_no_operation(self): """Test one circuit, one register, in-order readout. """ qr = QuantumRegister(1) cr = ClassicalRegister(1) circ = QuantumCircuit(qr, cr) circ.measure(qr[0], cr[0]) qobj = compile(circ, self._remote_backend) result_remote = self._remote_backend.run(qobj).result() result_local = self._local_backend.run(qobj).result() self.assertDictAlmostEqual(result_remote.get_counts(circ), result_local.get_counts(circ), delta=50)
def test_builtin_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() qobj = compile(circuits, backend=self.backend) job = self.backend.run(qobj) 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)) for target, actual in zip(reference_unitaries, sim_unitaries) ] for norm in norms: self.assertAlmostEqual(norm, 8)
def main(): args = options() circuit = load_qasm_file(args.qasm, name=args.qasm) qobj = compile(circuit, backend=args.backend, shots=args.shots) with open(args.qobj, 'w') as outfile: json.dump(qobj, outfile, indent=2, sort_keys=True, default=support_npint) if args.out_qasm: with open(args.out_qasm, 'w') as outfile: outfile.write(qobj['circuits'][0]['compiled_circuit_qasm'])
def get_compiled_circuit_infos(qc, backend, max_credits, shots): result = {} print("Getting infos ... ") backend_coupling = backend.configuration()['coupling_map'] from qiskit import compile grover_compiled = compile(qc, backend=backend, coupling_map=backend_coupling, shots=shots) grover_compiled_qasm = grover_compiled.experiments[ 0].header.compiled_circuit_qasm result['n_gates'] = len(grover_compiled_qasm.split("\n")) - 4 return result
def test_tdg_gate_deterministic_minimal_basis_gates(self): """Test tdg-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0)
def test_t_gate_nondeterministic_waltz_basis_gates(self): """Test t-gate gate circuits compiling to u1,u2,u3,cx""" shots = 2000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_qobj_to_circuit_with_sim_instructions(self): """Check qobj_to_circuit result with asimulator instruction.""" backend = Aer.get_backend('qasm_simulator_py') 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 = compile(circuit, backend, pass_manager=PassManager()) out_circuit = qobj_to_circuits(qobj_in) self.assertEqual(circuit_to_dag(out_circuit[0]), dag)
def test_grovers_minimal_basis_gates(self): """Test grovers circuits compiling to u3,cx""" shots = 2000 circuits = ref_algorithms.grovers_circuit(final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_ccx_gate_nondeterministic_minimal_basis_gates(self): """Test ccx-gate gate circuits compiling to U,CX""" shots = 2000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates='U,CX') result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_ccx_gate_deterministic_waltz_basis_gates(self): """Test ccx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates='u1,u2,u3,cx') result = self.SIMULATOR.run(qobj).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0)
def test_compile_two_run(self): """Test Compiler and run.""" 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) 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_qasm_max_memory_specified(self): """test default max memory configuration""" # Test circuit shots = 100 experiments = multiprocessing.cpu_count() circuit = ref_qvolume.quantum_volume(4, depth=1, final_measure=True) qobj = compile(circuit, self.SIMULATOR, shots=shots) backend_opts = {'max_memory_mb': 128} result = self.SIMULATOR.run(qobj, backend_options=backend_opts).result() self.assertEqual(result.metadata['max_memory_mb'], 128, msg="max_memory_mb is not configured correctly.")
def test_run_async_simulator(self, qe_token, qe_url): IBMQJob._executor = futures.ThreadPoolExecutor(max_workers=2) IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.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 = 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.status() is JobStatus.RUNNING for job in job_array]) if check >= 2: self.log.info('found %d simultaneous jobs', check) break if all([job.status() is JobStatus.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(), job.status() is JobStatus.RUNNING, check, job.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.status() is JobStatus.DONE for job in job_array])) self.assertTrue(all([result.success for result in result_array])) # Ensure job ids are unique. job_ids = [job.job_id() for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
def test_circuit_multi(self): """Test circuit multi regs declared at start. """ qreg0 = QuantumRegister(2, 'q0') creg0 = ClassicalRegister(2, 'c0') qreg1 = QuantumRegister(2, 'q1') creg1 = ClassicalRegister(2, 'c1') circ = QuantumCircuit(qreg0, qreg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) 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() counts = result.get_counts(qc) target = {'01 10': 1024} backend_sim = qiskit.providers.aer.StatevectorSimulator() result = backend_sim.run(qobj_circ).result() state = result.get_statevector(circ) backend_sim = qiskit.providers.aer.UnitarySimulator() result = backend_sim.run(qobj_circ).result() unitary = result.get_unitary(circ) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(basis_state('0110', 4), state), 1.0, places=7) self.assertAlmostEqual(process_fidelity(Pauli(label='IXXI').to_matrix(), unitary), 1.0, places=7)
def test_run_async_device(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backends = IBMQ.backends(simulator=False) backend = least_busy(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 = 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() for job in job_array] num_init = sum( [status is JobStatus.INITIALIZING for status in job_status]) num_queued = sum([status is JobStatus.QUEUED for status in job_status]) num_running = sum( [status is JobStatus.RUNNING for status in job_status]) num_done = sum([status is JobStatus.DONE for status in job_status]) num_error = sum([status is 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.status() is JobStatus.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.job_id() for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
def test_cz_gate_deterministic_waltz_basis_gates(self): """Test cz-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_2q_clifford.cz_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = self.SIMULATOR.run( qobj, backend_options=self.BACKEND_OPTS).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0)
def test_retrieve_job(self, qe_token, qe_url): IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend('ibmq_qasm_simulator') qobj = compile(self._qc, backend) job = backend.run(qobj) rjob = backend.retrieve_job(job.job_id()) self.assertEqual(job.job_id(), rjob.job_id()) self.assertEqual(job.result().get_counts(), rjob.result().get_counts()) if getattr(backend.configuration(), 'allow_q_object'): self.assertEqual(job.qobj().as_dict(), qobj.as_dict()) else: self.assertEqual(job.qobj(), None)
def test_swap_gate_nondeterministic_minimal_basis_gates(self): """Test swap-gate gate circuits compiling to u3,cx""" shots = 2000 circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) qobj = compile(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = self.SIMULATOR.run( qobj, backend_options=self.BACKEND_OPTS).result() self.is_completed(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
def test_parallel_compile(self): """Trigger parallel routines in compile. """ backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] qobj = compile(qlist, backend=backend) self.assertEqual(len(qobj.experiments), 10)
def measure(qc, qr, cr, basis): if basis == 'X' or basis == 'Y': qc.h(qr) if basis == 'Y': qc.sdg(qr) qc.measure(qr, cr) global BACKEND global SHOTS log(qc.qasm()) qobj = compile(qc, backend=BACKEND, shots=SHOTS) qc.reset(qr) return qobj
def test_basic_reordering(self, qe_token, qe_url): """a simple reordering within a 2-qubit register""" sim, real = self._get_backends(qe_token, qe_url) if not sim or not real: raise unittest.SkipTest('no remote device available') qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[1]) circuit.measure(qr[1], cr[0]) shots = 2000 qobj_real = compile(circuit, real) qobj_sim = compile(circuit, sim) result_real = real.run(qobj_real).result(timeout=600) result_sim = sim.run(qobj_sim).result(timeout=600) counts_real = result_real.get_counts() counts_sim = result_sim.get_counts() self.log.info(counts_real) self.log.info(counts_sim) threshold = 0.1 * shots self.assertDictAlmostEqual(counts_real, counts_sim, threshold)
def test_atlantic_circuit(self): """Test Atlantis deterministic ry operation. """ qr = QuantumRegister(3) cr = ClassicalRegister(3) circ = QuantumCircuit(qr, cr) circ.ry(pi, qr[0]) circ.ry(pi, qr[2]) circ.measure(qr, cr) qobj = compile(circ, self._remote_backend) result_remote = self._remote_backend.run(qobj).result() result_local = self._local_backend.run(qobj).result() self.assertDictAlmostEqual(result_remote.get_counts(circ), result_local.get_counts(circ), delta=50)
def test_compile_run_remote(self, qe_token, qe_url): """Test Compiler and run remote.""" IBMQ.enable_account(qe_token, qe_url) backend = 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 = compile(qc, backend, seed=TestCompiler.seed) job = backend.run(qobj) result = job.result(timeout=20) self.assertIsInstance(result, Result)
def test_qobj_to_circuits_multiple(self): """Check that qobj_to_circuits's result with multiple circuits""" backend = Aer.get_backend('qasm_simulator_py') 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 = compile([self.circuit, circuit_b], backend, pass_manager=PassManager()) dag_list = [circuit_to_dag(x) for x in qobj_to_circuits(qobj)] self.assertEqual(dag_list, [self.dag, circuit_to_dag(circuit_b)])
print("(Local Backends)") for backend_name in available_backends({'local': True}): backend = get_backend(backend_name) print(backend.status) my_backend_name = 'local_qasm_simulator' my_backend = get_backend(my_backend_name) print("(Local QASM Simulator configuration) ") pprint.pprint(my_backend.configuration) print("(Local QASM Simulator calibration) ") pprint.pprint(my_backend.calibration) print("(Local QASM Simulator parameters) ") pprint.pprint(my_backend.parameters) # Compiling the job qobj = compile([qc1, qc2], my_backend) # Note: in the near future qobj will become an object # Runing the job sim_job = my_backend.run(QuantumJob(qobj, backend=my_backend, preformatted=True)) # Note: in the near future the quantumjob class will be removed and this will become # sim_job = my_backend.run(qobj) sim_result=sim_job.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Compile and run the Quantum Program on a real device backend