def test_sympy(self): desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4), 1 / math.sqrt(4) * complex(0, 1)] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = wrapper.execute(qc, 'local_statevector_simulator') result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def setUp(self): qr = QuantumRegister(2, name="qr2") cr = ClassicalRegister(2, name=None) qc = QuantumCircuit(qr, cr, name="qc10") qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qr_name = qr.name self.cr_name = cr.name self.circuits = [qc]
def qc_approx_sim(x, t1, t2): theta1 = x - t1; theta2 = x - t2; q = QuantumRegister(2, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q, c) qc.h( q[0] ) qc.h( q[1] ) qc.u3(t1, 0.0, 0.0, q[0]); qc.u3(t2, 0.0, 0.0, q[1]); qc.barrier( q ) #qc.measure(q,c) qc.measure( q[0], c[0] ) qc.measure( q[1], c[1] ) job = execute(qc, backend, shots=1024) rslt = job.result() #counts = rslt.get_counts(qc) #print(counts) outputstate = rslt.get_statevector( qc, decimals=13 ) #print(outputstate) qval = outputstate; return qval;
def test_single_qubit(self): desired_vector = [1/math.sqrt(3), math.sqrt(2)/math.sqrt(3)] qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) job = wrapper.execute(qc, 'local_statevector_simulator') result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_deterministic_state(self): desired_vector = [0, 1, 0, 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = wrapper.execute(qc, 'local_statevector_simulator') result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_cancel(self): """Test the cancelation of jobs. Since only Jobs that are still in the executor queue pending to be executed can be cancelled, this test launches a lot of jobs, passing if some of them can be cancelled. """ # Force the number of workers to 1, as only Jobs that are still in # the executor queue can be canceled. if sys.platform == 'darwin': LocalJob._executor = futures.ThreadPoolExecutor(max_workers=1) else: LocalJob._executor = futures.ProcessPoolExecutor(max_workers=1) backend = self._provider.get_backend('local_qasm_simulator_py') num_qubits = 5 qr = QuantumRegister(num_qubits, 'q') cr = ClassicalRegister(num_qubits, 'c') qc = QuantumCircuit(qr, cr) for i in range(num_qubits-1): qc.cx(qr[i], qr[i+1]) qc.measure(qr, cr) qobj = qiskit._compiler.compile(qc, backend) quantum_job = QuantumJob(qobj, backend, preformatted=True) num_jobs = 10 timeout = 10 start_time = time.time() self.log.info('testing with simulator: %s', backend.name) job_array = [backend.run(quantum_job) for _ in range(num_jobs)] for job in job_array: job.cancel() found_cancelled = False while not found_cancelled: check = sum([job.cancelled for job in job_array]) if check >= 1: self.log.info('found %d cancelled jobs', check) found_cancelled = True if all([job.done for job in job_array]): self.log.warning('all jobs completed before simultaneous jobs ' 'could be detected') break for job in job_array: self.log.info('%s %s %s', job.status['status'], job.cancelled, check) self.log.info('{0} {1:0.2f}'.format('-'*20, 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(1) # Wait for all the jobs to finish. _ = [job.result() for job in job_array if not job.cancelled]
def test_gate_x(self): shots = 100 qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr, name='test_gate_x') qc.x(qr[0]) qc.measure(qr, cr) qobj = qiskit._compiler.compile([qc], pq_simulator, shots=shots) q_job = QuantumJob(qobj, pq_simulator, preformatted=True, resources={'max_credits': qobj['config']['max_credits']}) job = pq_simulator.run(q_job) result_pq = job.result(timeout=30) self.assertEqual(result_pq.get_counts(result_pq.get_names()[0]), {'1': shots})
def test_run_async(self): if sys.platform == 'darwin': LocalJob._executor = futures.ThreadPoolExecutor(max_workers=2) else: LocalJob._executor = futures.ProcessPoolExecutor(max_workers=2) try: backend = self._provider.get_backend('local_qasm_simulator_cpp') except KeyError: backend = self._provider.get_backend('local_qasm_simulator_py') num_qubits = 15 qr = QuantumRegister(num_qubits, 'q') cr = ClassicalRegister(num_qubits, 'c') qc = QuantumCircuit(qr, cr) for i in range(num_qubits-1): qc.cx(qr[i], qr[i+1]) qc.measure(qr, cr) qobj = qiskit._compiler.compile(qc, backend) quantum_job = QuantumJob(qobj, backend, preformatted=True) num_jobs = 5 job_array = [backend.run(quantum_job) for _ in range(num_jobs)] found_async_jobs = False timeout = 30 start_time = time.time() self.log.info('testing with simulator: %s', backend.name) 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) found_async_jobs = True if all([job.done for job in job_array]): self.log.warning('all jobs completed before simultaneous jobs ' 'could be detected') break for job in job_array: self.log.info('%s %s %s', job.status['status'], job.running, check) self.log.info('%s %.4f', '-'*20, 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(1) # Wait for all the jobs to finish. # TODO: this causes the test to wait until the 15 qubit jobs are # finished, which might take long (hence the @slow_test). Waiting for # the result is needed as otherwise the jobs would still be running # once the test is completed, causing failures in subsequent tests as # the executor's queue might be overloaded. _ = [job.result() for job in job_array]
def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') with open(self.qasm_filename, 'r') as qasm_file: self.qasm_text = qasm_file.read() self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse() self.qasm_be = qiskit.unroll.CircuitBackend(['u1', 'u2', 'u3', 'id', 'cx']) self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast, self.qasm_be).execute() qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qc = qc # create qobj compiled_circuit1 = qiskit._compiler.compile_circuit(self.qc, format='json') compiled_circuit2 = qiskit._compiler.compile_circuit(self.qasm_circ, format='json') self.qobj = {'id': 'test_qobj', 'config': { 'max_credits': 3, 'shots': 2000, 'backend_name': 'local_qasm_simulator_cpp', 'seed': 1111 }, 'circuits': [ { 'name': 'test_circuit1', 'compiled_circuit': compiled_circuit1, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, }, { 'name': 'test_circuit2', 'compiled_circuit': compiled_circuit2, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, } ]} # Simulator backend try: self.backend = QasmSimulatorCpp() except FileNotFoundError as fnferr: raise unittest.SkipTest( 'cannot find {} in path'.format(fnferr)) self.q_job = QuantumJob(self.qobj, backend=self.backend, preformatted=True)
def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.s = QuantumRegister(3, "s") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.s, self.c) self.c_header = 80 # lenght of the header
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 = qiskit._compiler.compile([qc]*10, backend) quantum_job = QuantumJob(qobj, backend, preformatted=True) num_jobs = 5 job_array = [backend.run(quantum_job) 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.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.job_id for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
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 = qiskit._compiler.compile(qc, backend) quantum_job = QuantumJob(qobj, backend, preformatted=True) num_jobs = 3 job_array = [backend.run(quantum_job) 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.job_id for job in job_array] self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
def setUp(self): self.seed = 88 self.qasmFileName = os.path.join(qiskit.__path__[0], '../test/python/qasm/example.qasm') with open(self.qasmFileName, 'r') as qasm_file: self.qasm_text = qasm_file.read() qr = QuantumRegister('q', 2) cr = ClassicalRegister('c', 2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qc = qc # create qobj compiled_circuit1 = openquantumcompiler.compile(self.qc.qasm(), format='json') compiled_circuit2 = openquantumcompiler.compile(self.qasm_text, format='json') self.qobj = {'id': 'test_qobj', 'config': { 'max_credits': 3, 'shots': 100, 'backend': 'local_qasm_simulator', 'seed': 1111 }, 'circuits': [ { 'name': 'test_circuit1', 'compiled_circuit': compiled_circuit1, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, }, { 'name': 'test_circuit2', 'compiled_circuit': compiled_circuit2, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, } ] } self.q_job = QuantumJob(self.qobj, backend='local_qasm_cpp_simulator', preformatted=True)
def test_random_3qubit(self): desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = wrapper.execute(qc, 'local_statevector_simulator') result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
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 setUpClass(cls, QE_TOKEN, QE_URL, hub=None, group=None, project=None): # pylint: disable=arguments-differ super().setUpClass() # create QuantumCircuit qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) cls._qc = qc cls._provider = LocalProvider(QE_TOKEN, QE_URL, hub, group, project)
def setUp(self): self.seed = 88 self.qasmFileName = self._get_resource_path('qasm/example.qasm') with open(self.qasmFileName, 'r') as qasm_file: self.qasm_text = qasm_file.read() # create QuantumCircuit qr = QuantumRegister('q', 2) cr = ClassicalRegister('c', 2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qc = qc # create qobj compiled_circuit1 = openquantumcompiler.compile(self.qc.qasm()) compiled_circuit2 = openquantumcompiler.compile(self.qasm_text) self.qobj = {'id': 'test_qobj', 'config': { 'max_credits': 3, 'shots': 100, 'backend': 'local_qasm_simulator', }, 'circuits': [ { 'name': 'test_circuit1', 'compiled_circuit': compiled_circuit1, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None }, { 'name': 'test_circuit2', 'compiled_circuit': compiled_circuit2, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None } ] }
def test_cancel(self): if not self._using_hub: self.skipTest('job cancellation currently only available on hubs') backends = self._provider.available_backends({'simulator': False}) 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 = qiskit._compiler.compile(qc, backend) quantum_job = QuantumJob(qobj, backend, preformatted=True) num_jobs = 3 job_array = [backend.run(quantum_job) 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 __init__(self, basis=None): """Setup this backend. basis is a list of operation name strings. """ super().__init__(basis) self.creg = None self.cval = None if basis: self.basis = basis else: self.basis = ["cx", "u1", "u2", "u3"] self.gates = {} self.listen = True self.in_gate = "" self.circuit = QuantumCircuit()
def __init__(self,x,y,print_info=False): #quantum register, classical register, quantum circuit. self.print_info=print_info self.q = QuantumRegister(1) self.c = ClassicalRegister(1) self.qc = QuantumCircuit(self.q, self.c) self.qc.cry = cry self.qc.x_bus = x_bus self.qc.cnx = cnx self.qc.any_x = any_x self.qc.bus_or = bus_or #the dimensions of the bord self.x=x self.y=y #To keep track of what is in each cell, no entanglement etc. #Provides a graphic of the game state. self.cells = np.empty((x,y),dtype=object) self.cells[:]='' #Initially game is empty. self.game_full = False self.moves = []
def test_combiner(self): desired_vector = [1, 0] qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") qc1 = QuantumCircuit(qr, cr) qc1.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc2 = QuantumCircuit(qr, cr) qc2.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) job = wrapper.execute(qc1+qc2, 'local_statevector_simulator') result = job.result() quantum_state = result.get_statevector() fidelity = state_fidelity(quantum_state, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_entangle(self): shots = 100 N = 5 qr = QuantumRegister(N) cr = ClassicalRegister(N) qc = QuantumCircuit(qr, cr, name='test_entangle') qc.h(qr[0]) for i in range(1, N): qc.cx(qr[0], qr[i]) qc.measure(qr, cr) qobj = qiskit._compiler.compile([qc], pq_simulator, shots=shots) timeout = 30 q_job = QuantumJob(qobj, pq_simulator, preformatted=True, resources={'max_credits': qobj['config']['max_credits']}) job = pq_simulator.run(q_job) result = job.result(timeout=timeout) counts = result.get_counts(result.get_names()[0]) self.log.info(counts) for key, _ in counts.items(): with self.subTest(key=key): self.assertTrue(key in ['0' * N, '1' * N])
class TestStandard3Q(StandardExtensionTest): """Standard Extension Test. Gates with three Qubits""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.s = QuantumRegister(3, "s") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.s, self.c) self.c_header = 80 # lenght of the header def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2],s[0],s[1],s[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ccx_reg_reg_reg(self): qasm_txt = 'ccx q[0],r[0],s[0];\nccx q[1],r[1],s[1];\nccx q[2],r[2],s[2];' instruction_set = self.circuit.ccx(self.q, self.r, self.s) self.assertStmtsType(instruction_set.instructions, ToffoliGate) self.assertQasm(qasm_txt) def test_ccx_reg_reg_inv(self): qasm_txt = 'ccx q[0],r[0],s[0];\nccx q[1],r[1],s[1];\nccx q[2],r[2],s[2];' instruction_set = self.circuit.ccx(self.q, self.r, self.s).inverse() self.assertStmtsType(instruction_set.instructions, ToffoliGate) self.assertQasm(qasm_txt) def test_cswap_reg_reg_reg(self): qasm_txt = 'cswap q[0],r[0],s[0];\n' \ 'cswap q[1],r[1],s[1];\n' \ 'cswap q[2],r[2],s[2];' instruction_set = self.circuit.cswap(self.q, self.r, self.s) self.assertStmtsType(instruction_set.instructions, FredkinGate) self.assertQasm(qasm_txt) def test_cswap_reg_reg_inv(self): qasm_txt = 'cswap q[0],r[0],s[0];\n' \ 'cswap q[1],r[1],s[1];\n' \ 'cswap q[2],r[2],s[2];' instruction_set = self.circuit.cswap(self.q, self.r, self.s).inverse() self.assertStmtsType(instruction_set.instructions, FredkinGate) self.assertQasm(qasm_txt)
class TestStandard2Q(StandardExtensionTest): """Standard Extension Test. Gates with two Qubits""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.c) self.c_header = 69 # lenght of the header def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_reg_bit(self): self.circuit.barrier(self.q, self.r[0]) qasm_txt = 'barrier q[0],q[1],q[2],r[0];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ch_reg_reg(self): qasm_txt = 'ch q[0],r[0];\nch q[1],r[1];\nch q[2],r[2];' instruction_set = self.circuit.ch(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_reg_inv(self): qasm_txt = 'ch q[0],r[0];\nch q[1],r[1];\nch q[2],r[2];' instruction_set = self.circuit.ch(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_bit(self): qasm_txt = 'ch q[0],r[1];\nch q[1],r[1];\nch q[2],r[1];' instruction_set = self.circuit.ch(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_bit_inv(self): qasm_txt = 'ch q[0],r[1];\nch q[1],r[1];\nch q[2],r[1];' instruction_set = self.circuit.ch(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_bit_reg(self): qasm_txt = 'ch q[1],r[0];\nch q[1],r[1];\nch q[1],r[2];' instruction_set = self.circuit.ch(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_bit_reg_inv(self): qasm_txt = 'ch q[1],r[0];\nch q[1],r[1];\nch q[1],r[2];' instruction_set = self.circuit.ch(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_crz_reg_reg(self): qasm_txt = 'crz(1) q[0],r[0];\ncrz(1) q[1],r[1];\ncrz(1) q[2],r[2];' instruction_set = self.circuit.crz(1, self.q, self.r) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_reg_inv(self): qasm_txt = 'crz(-1) q[0],r[0];\ncrz(-1) q[1],r[1];\ncrz(-1) q[2],r[2];' instruction_set = self.circuit.crz(1, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_bit(self): qasm_txt = 'crz(1) q[0],r[1];\ncrz(1) q[1],r[1];\ncrz(1) q[2],r[1];' instruction_set = self.circuit.crz(1, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_bit_inv(self): qasm_txt = 'crz(-1) q[0],r[1];\ncrz(-1) q[1],r[1];\ncrz(-1) q[2],r[1];' instruction_set = self.circuit.crz(1, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_bit_reg(self): qasm_txt = 'crz(1) q[1],r[0];\ncrz(1) q[1],r[1];\ncrz(1) q[1],r[2];' instruction_set = self.circuit.crz(1, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_bit_reg_inv(self): qasm_txt = 'crz(-1) q[1],r[0];\ncrz(-1) q[1],r[1];\ncrz(-1) q[1],r[2];' instruction_set = self.circuit.crz(1, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_cu1_reg_reg(self): qasm_txt = 'cu1(1) q[0],r[0];\ncu1(1) q[1],r[1];\ncu1(1) q[2],r[2];' instruction_set = self.circuit.cu1(1, self.q, self.r) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_reg_inv(self): qasm_txt = 'cu1(-1) q[0],r[0];\ncu1(-1) q[1],r[1];\ncu1(-1) q[2],r[2];' instruction_set = self.circuit.cu1(1, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_bit(self): qasm_txt = 'cu1(1) q[0],r[1];\ncu1(1) q[1],r[1];\ncu1(1) q[2],r[1];' instruction_set = self.circuit.cu1(1, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_bit_inv(self): qasm_txt = 'cu1(-1) q[0],r[1];\ncu1(-1) q[1],r[1];\ncu1(-1) q[2],r[1];' instruction_set = self.circuit.cu1(1, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_bit_reg(self): qasm_txt = 'cu1(1) q[1],r[0];\ncu1(1) q[1],r[1];\ncu1(1) q[1],r[2];' instruction_set = self.circuit.cu1(1, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_bit_reg_inv(self): qasm_txt = 'cu1(-1) q[1],r[0];\ncu1(-1) q[1],r[1];\ncu1(-1) q[1],r[2];' instruction_set = self.circuit.cu1(1, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu3_reg_reg(self): qasm_txt = 'cu3(1,2,3) q[0],r[0];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[2],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_reg_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[0],r[0];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[2],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_bit(self): qasm_txt = 'cu3(1,2,3) q[0],r[1];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[2],r[1];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_bit_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[0],r[1];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[2],r[1];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_bit_reg(self): qasm_txt = 'cu3(1,2,3) q[1],r[0];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[1],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_bit_reg_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[1],r[0];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[1],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cx_reg_reg(self): qasm_txt = 'cx q[0],r[0];\ncx q[1],r[1];\ncx q[2],r[2];' instruction_set = self.circuit.cx(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_reg_inv(self): qasm_txt = 'cx q[0],r[0];\ncx q[1],r[1];\ncx q[2],r[2];' instruction_set = self.circuit.cx(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_bit(self): qasm_txt = 'cx q[0],r[1];\ncx q[1],r[1];\ncx q[2],r[1];' instruction_set = self.circuit.cx(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_bit_inv(self): qasm_txt = 'cx q[0],r[1];\ncx q[1],r[1];\ncx q[2],r[1];' instruction_set = self.circuit.cx(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_bit_reg(self): qasm_txt = 'cx q[1],r[0];\ncx q[1],r[1];\ncx q[1],r[2];' instruction_set = self.circuit.cx(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_bit_reg_inv(self): qasm_txt = 'cx q[1],r[0];\ncx q[1],r[1];\ncx q[1],r[2];' instruction_set = self.circuit.cx(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cxbase_reg_reg(self): qasm_txt = 'CX q[0],r[0];\nCX q[1],r[1];\nCX q[2],r[2];' instruction_set = self.circuit.cx_base(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_reg_inv(self): qasm_txt = 'CX q[0],r[0];\nCX q[1],r[1];\nCX q[2],r[2];' instruction_set = self.circuit.cx_base(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_bit(self): qasm_txt = 'CX q[0],r[1];\nCX q[1],r[1];\nCX q[2],r[1];' instruction_set = self.circuit.cx_base(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_bit_inv(self): qasm_txt = 'CX q[0],r[1];\nCX q[1],r[1];\nCX q[2],r[1];' instruction_set = self.circuit.cx_base(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_bit_reg(self): qasm_txt = 'CX q[1],r[0];\nCX q[1],r[1];\nCX q[1],r[2];' instruction_set = self.circuit.cx_base(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_bit_reg_inv(self): qasm_txt = 'CX q[1],r[0];\nCX q[1],r[1];\nCX q[1],r[2];' instruction_set = self.circuit.cx_base(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cy_reg_reg(self): qasm_txt = 'cy q[0],r[0];\ncy q[1],r[1];\ncy q[2],r[2];' instruction_set = self.circuit.cy(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_reg_inv(self): qasm_txt = 'cy q[0],r[0];\ncy q[1],r[1];\ncy q[2],r[2];' instruction_set = self.circuit.cy(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_bit(self): qasm_txt = 'cy q[0],r[1];\ncy q[1],r[1];\ncy q[2],r[1];' instruction_set = self.circuit.cy(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_bit_inv(self): qasm_txt = 'cy q[0],r[1];\ncy q[1],r[1];\ncy q[2],r[1];' instruction_set = self.circuit.cy(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_bit_reg(self): qasm_txt = 'cy q[1],r[0];\ncy q[1],r[1];\ncy q[1],r[2];' instruction_set = self.circuit.cy(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_bit_reg_inv(self): qasm_txt = 'cy q[1],r[0];\ncy q[1],r[1];\ncy q[1],r[2];' instruction_set = self.circuit.cy(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cz_reg_reg(self): qasm_txt = 'cz q[0],r[0];\ncz q[1],r[1];\ncz q[2],r[2];' instruction_set = self.circuit.cz(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_reg_inv(self): qasm_txt = 'cz q[0],r[0];\ncz q[1],r[1];\ncz q[2],r[2];' instruction_set = self.circuit.cz(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_bit(self): qasm_txt = 'cz q[0],r[1];\ncz q[1],r[1];\ncz q[2],r[1];' instruction_set = self.circuit.cz(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_bit_inv(self): qasm_txt = 'cz q[0],r[1];\ncz q[1],r[1];\ncz q[2],r[1];' instruction_set = self.circuit.cz(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_bit_reg(self): qasm_txt = 'cz q[1],r[0];\ncz q[1],r[1];\ncz q[1],r[2];' instruction_set = self.circuit.cz(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_bit_reg_inv(self): qasm_txt = 'cz q[1],r[0];\ncz q[1],r[1];\ncz q[1],r[2];' instruction_set = self.circuit.cz(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_swap_reg_reg(self): qasm_txt = 'swap q[0],r[0];\nswap q[1],r[1];\nswap q[2],r[2];' instruction_set = self.circuit.swap(self.q, self.r) self.assertStmtsType(instruction_set.instructions, SwapGate) self.assertQasm(qasm_txt) def test_swap_reg_reg_inv(self): qasm_txt = 'swap q[0],r[0];\nswap q[1],r[1];\nswap q[2],r[2];' instruction_set = self.circuit.swap(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, SwapGate) self.assertQasm(qasm_txt)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(3, 'q') creg_c = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.x(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) circuit.h(qreg_q[2]) circuit.cswap(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[2], creg_c[2])
def test_evaluate_single_pauli_statevector(self): """ evaluate single pauli statevector test """ # X op = WeightedPauliOperator.from_list([Pauli.from_label('X')]) qr = QuantumRegister(1, name='q') wave_function = QuantumCircuit(qr) # + 1 eigenstate wave_function.h(qr[0]) circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(1.0, actual_value[0].real, places=5) # - 1 eigenstate wave_function = QuantumCircuit(qr) wave_function.x(qr[0]) wave_function.h(qr[0]) circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(-1.0, actual_value[0].real, places=5) # Y op = WeightedPauliOperator.from_list([Pauli.from_label('Y')]) qr = QuantumRegister(1, name='q') wave_function = QuantumCircuit(qr) # + 1 eigenstate wave_function.h(qr[0]) wave_function.s(qr[0]) circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(1.0, actual_value[0].real, places=5) # - 1 eigenstate wave_function = QuantumCircuit(qr) wave_function.x(qr[0]) wave_function.h(qr[0]) wave_function.s(qr[0]) circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(-1.0, actual_value[0].real, places=5) # Z op = WeightedPauliOperator.from_list([Pauli.from_label('Z')]) qr = QuantumRegister(1, name='q') wave_function = QuantumCircuit(qr) # + 1 eigenstate circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(1.0, actual_value[0].real, places=5) # - 1 eigenstate wave_function = QuantumCircuit(qr) wave_function.x(qr[0]) circuits = op.construct_evaluation_circuit(wave_function=wave_function, statevector_mode=True) result = self.quantum_instance_statevector.execute(circuits) actual_value = op.evaluate_with_result(result=result, statevector_mode=True) self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)
def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.h(input_qubit[2]) # number=38 prog.cz(input_qubit[0],input_qubit[2]) # number=39 prog.h(input_qubit[2]) # number=40 prog.h(input_qubit[2]) # number=59 prog.cz(input_qubit[0],input_qubit[2]) # number=60 prog.h(input_qubit[2]) # number=61 prog.h(input_qubit[2]) # number=42 prog.cz(input_qubit[0],input_qubit[2]) # number=43 prog.h(input_qubit[2]) # number=44 prog.h(input_qubit[2]) # number=48 prog.cz(input_qubit[0],input_qubit[2]) # number=49 prog.h(input_qubit[2]) # number=50 prog.cx(input_qubit[0],input_qubit[2]) # number=54 prog.x(input_qubit[2]) # number=55 prog.h(input_qubit[2]) # number=62 prog.cz(input_qubit[0],input_qubit[2]) # number=63 prog.h(input_qubit[2]) # number=64 prog.cx(input_qubit[0],input_qubit[2]) # number=47 prog.cx(input_qubit[0],input_qubit[2]) # number=37 prog.h(input_qubit[2]) # number=51 prog.cz(input_qubit[0],input_qubit[2]) # number=52 prog.h(input_qubit[2]) # number=53 prog.h(input_qubit[2]) # number=25 prog.cz(input_qubit[0],input_qubit[2]) # number=26 prog.h(input_qubit[2]) # number=27 prog.h(input_qubit[1]) # number=7 prog.cz(input_qubit[2],input_qubit[1]) # number=8 prog.rx(0.17592918860102857,input_qubit[2]) # number=34 prog.rx(-0.3989822670059037,input_qubit[1]) # number=30 prog.h(input_qubit[1]) # number=9 prog.h(input_qubit[1]) # number=18 prog.rx(2.3310617489636263,input_qubit[2]) # number=58 prog.cz(input_qubit[2],input_qubit[1]) # number=19 prog.h(input_qubit[1]) # number=20 prog.y(input_qubit[1]) # number=14 prog.h(input_qubit[1]) # number=22 prog.cz(input_qubit[2],input_qubit[1]) # number=23 prog.rx(-0.9173450548482197,input_qubit[1]) # number=57 prog.h(input_qubit[1]) # number=24 prog.z(input_qubit[2]) # number=3 prog.z(input_qubit[1]) # number=41 prog.x(input_qubit[1]) # number=17 prog.y(input_qubit[2]) # number=5 prog.x(input_qubit[2]) # number=21 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog
""" Example use of the initialize gate to prepare arbitrary pure states. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Simulators ############################################################### # Make a quantum circuit for state initialization. ############################################################### qr = QuantumRegister(4, "qr") cr = ClassicalRegister(4, 'cr') circuit = QuantumCircuit(qr, cr, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0) ] circuit.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.measure(qr[3], cr[3])
def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc
def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.x(input_qubit[2]) # number=2 prog.cx(input_qubit[2],input_qubit[1]) # number=4 prog.z(input_qubit[2]) # number=3 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") target = QuantumRegister(1, "qt") prog = QuantumCircuit(input_qubit, target) # inverse last one (can be omitted if using O_f^\pm) prog.x(target) # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[1]) # number=1 prog.h(target) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append(oracle.to_gate(), [input_qubit[i] for i in range(n)] + [target]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure prog.y(input_qubit[1]) # number=2 prog.y(input_qubit[1]) # number=4 prog.y(input_qubit[1]) # number=3 prog.rx(2.0860175219836226, input_qubit[1]) # number=7 prog.cx(input_qubit[1], input_qubit[0]) # number=13 prog.x(input_qubit[0]) # number=14 prog.cx(input_qubit[1], input_qubit[0]) # number=15 prog.x(input_qubit[0]) # number=6 prog.h(input_qubit[0]) # number=10 prog.cz(input_qubit[1], input_qubit[0]) # number=11 prog.h(input_qubit[0]) # number=12 prog.cx(input_qubit[1], input_qubit[0]) # number=9 # circuit end return prog
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=15 prog.cz(input_qubit[0], input_qubit[3]) # number=16 prog.h(input_qubit[3]) # number=17 prog.h(input_qubit[3]) # number=39 prog.cz(input_qubit[0], input_qubit[3]) # number=40 prog.h(input_qubit[3]) # number=41 prog.x(input_qubit[3]) # number=37 prog.cx(input_qubit[0], input_qubit[3]) # number=38 prog.h(input_qubit[3]) # number=20 prog.cz(input_qubit[0], input_qubit[3]) # number=21 prog.h(input_qubit[3]) # number=22 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.z(input_qubit[3]) # number=33 prog.h(input_qubit[0]) # number=5 prog.x(input_qubit[3]) # number=32 oracle = build_oracle(n - 1, f) prog.append(oracle.to_gate(), [input_qubit[i] for i in range(n - 1)] + [input_qubit[n - 1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[1]) # number=29 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 prog.h(input_qubit[0]) # number=23 prog.rx(0.6063273821428302, input_qubit[3]) # number=34 prog.rx(-2.0106192982974678, input_qubit[3]) # number=35 prog.cz(input_qubit[2], input_qubit[0]) # number=24 prog.h(input_qubit[0]) # number=25 prog.y(input_qubit[2]) # number=30 prog.cx(input_qubit[2], input_qubit[0]) # number=11 prog.cx(input_qubit[2], input_qubit[0]) # number=18 prog.h(input_qubit[0]) # number=26 prog.x(input_qubit[2]) # number=31 prog.cz(input_qubit[2], input_qubit[0]) # number=27 prog.h(input_qubit[0]) # number=28 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[4]) # number=21 prog.h(input_qubit[0]) # number=43 prog.cz(input_qubit[4], input_qubit[0]) # number=44 prog.h(input_qubit[0]) # number=45 prog.cx(input_qubit[4], input_qubit[0]) # number=46 prog.cx(input_qubit[4], input_qubit[0]) # number=49 prog.z(input_qubit[4]) # number=50 prog.cx(input_qubit[4], input_qubit[0]) # number=51 prog.cx(input_qubit[4], input_qubit[0]) # number=48 prog.h(input_qubit[0]) # number=37 prog.cz(input_qubit[4], input_qubit[0]) # number=38 prog.h(input_qubit[0]) # number=39 Zf = build_oracle(n, f) repeat = floor(sqrt(2**n) * pi / 4) for i in range(repeat): prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)]) prog.h(input_qubit[0]) # number=1 prog.rx(-1.0430087609918113, input_qubit[4]) # number=36 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.cx(input_qubit[1], input_qubit[0]) # number=40 prog.x(input_qubit[0]) # number=41 prog.cx(input_qubit[1], input_qubit[0]) # number=42 prog.x(input_qubit[1]) # number=10 prog.rx(-0.06597344572538572, input_qubit[3]) # number=27 prog.cx(input_qubit[0], input_qubit[2]) # number=22 prog.x(input_qubit[2]) # number=23 prog.h(input_qubit[2]) # number=28 prog.cz(input_qubit[0], input_qubit[2]) # number=29 prog.h(input_qubit[2]) # number=30 prog.x(input_qubit[3]) # number=12 if n >= 2: prog.mcu1(pi, input_qubit[1:], input_qubit[0]) prog.x(input_qubit[0]) # number=13 prog.x(input_qubit[1]) # number=14 prog.x(input_qubit[2]) # number=15 prog.x(input_qubit[3]) # number=16 prog.h(input_qubit[4]) # number=35 prog.h(input_qubit[0]) # number=17 prog.rx(2.4912829742967055, input_qubit[2]) # number=26 prog.h(input_qubit[1]) # number=18 prog.h(input_qubit[2]) # number=19 prog.h(input_qubit[2]) # number=25 prog.h(input_qubit[3]) # number=20 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
def make_circuit(n:int) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.z(input_qubit[3]) # number=5 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) prog.swap(input_qubit[2],input_qubit[0]) # number=6 prog.swap(input_qubit[2],input_qubit[0]) # number=7 # circuit end return prog
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.cx(input_qubit[0],input_qubit[3]) # number=12 prog.x(input_qubit[3]) # number=13 prog.h(input_qubit[3]) # number=28 prog.cz(input_qubit[0],input_qubit[3]) # number=29 prog.h(input_qubit[3]) # number=30 prog.z(input_qubit[3]) # number=10 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.rx(2.708052867394402,input_qubit[1]) # number=11 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.y(input_qubit[2]) # number=16 prog.cx(input_qubit[1],input_qubit[0]) # number=19 prog.h(input_qubit[3]) # number=25 prog.z(input_qubit[1]) # number=20 prog.z(input_qubit[3]) # number=31 prog.h(input_qubit[0]) # number=22 prog.cz(input_qubit[1],input_qubit[0]) # number=23 prog.y(input_qubit[1]) # number=36 prog.h(input_qubit[0]) # number=24 prog.z(input_qubit[2]) # number=15 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.y(input_qubit[2]) # number=18 prog.h(input_qubit[0]) # number=9 prog.h(input_qubit[0]) # number=32 prog.cz(input_qubit[1],input_qubit[0]) # number=33 prog.h(input_qubit[0]) # number=34 prog.x(input_qubit[2]) # number=35 prog.cx(input_qubit[1],input_qubit[0]) # number=27 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
def trial_circuit_computational(n, state, meas_string = None, measurement = True): """Trial function for classical optimization problems. n = number of qubits state = a bit string for the state prepared. meas_string = the pauli to be measured measurement = true/false if measurement is to be done """ q = QuantumRegister("q", n) c = ClassicalRegister("c", n) trial_circuit = QuantumCircuit(q, c) if meas_string is None: meas_string = [None for x in range(n)] if len(state) == n: for j in range(n): if state[n-j-1] == "1": trial_circuit.x(q[j]) trial_circuit.barrier(q) for j in range(n): if meas_string[j] == 'X': trial_circuit.h(q[j]) elif meas_string[j] == 'Y': trial_circuit.s(q[j]).inverse() trial_circuit.h(q[j]) if measurement: for j in range(n): trial_circuit.measure(q[j], c[j]) return trial_circuit
def test_user_style(self): """Tests loading a user style""" circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi/2, 4) circuit.u1(pi/2, 4) circuit.cz(5, 6) circuit.cu1(pi/2, 5, 6) circuit.cp(pi/2, 5, 6) circuit.y(5) circuit.rx(pi/3, 5) circuit.rzx(pi/2, 5, 6) circuit.u2(pi/2, pi/2, 5) circuit.barrier(5, 6) circuit.reset(5) self.circuit_drawer(circuit, style={'name': 'user_style'}, filename='user_style.png')
def test3_qlm_backend_run_2_circuit(self): """ Here two circuits run into a QLM QPU by using the QLMBacked object. """ nbqubits = 2 qreg = QuantumRegister(nbqubits) creg = ClassicalRegister(nbqubits) qiskit_circuit_1 = QuantumCircuit(qreg, creg) qiskit_circuit_1.h(qreg[0]) qiskit_circuit_1.cx(qreg[0], qreg[1]) qiskit_circuit_1.measure(qreg, creg) qiskit_circuit_2 = QuantumCircuit(qreg, creg) qiskit_circuit_2.h(qreg[0]) qiskit_circuit_2.h(qreg[1]) qiskit_circuit_2.measure(qreg, creg) backend = QiskitConnector() | PyLinalg() qiskit_circuits = [] qiskit_circuits.append(qiskit_circuit_1) qiskit_circuits.append(qiskit_circuit_2) qobj = assemble(qiskit_circuits) result = backend.run(qobj).result() LOGGER.debug( "\nQPUToBackend test with a list of QLM jobs sent into a QLM qpu:") LOGGER.debug(result.results) self.assertEqual(2, len(result.results))
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=16 prog.cz(input_qubit[0],input_qubit[3]) # number=17 prog.h(input_qubit[3]) # number=18 prog.x(input_qubit[3]) # number=14 prog.h(input_qubit[3]) # number=32 prog.cz(input_qubit[0],input_qubit[3]) # number=33 prog.h(input_qubit[3]) # number=34 prog.rx(-1.928937889304133,input_qubit[1]) # number=35 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[3]) # number=12 prog.h(input_qubit[3]) # number=36 prog.cz(input_qubit[2],input_qubit[3]) # number=37 prog.h(input_qubit[3]) # number=38 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=24 prog.cz(input_qubit[3],input_qubit[2]) # number=25 prog.h(input_qubit[2]) # number=26 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[2]) # number=42 prog.cz(input_qubit[0],input_qubit[2]) # number=43 prog.h(input_qubit[2]) # number=44 prog.cx(input_qubit[0],input_qubit[2]) # number=39 prog.x(input_qubit[2]) # number=40 prog.cx(input_qubit[0],input_qubit[2]) # number=41 prog.cx(input_qubit[0],input_qubit[2]) # number=31 prog.h(input_qubit[0]) # number=9 prog.y(input_qubit[2]) # number=10 prog.y(input_qubit[2]) # number=11 prog.x(input_qubit[1]) # number=20 prog.x(input_qubit[1]) # number=21 prog.x(input_qubit[3]) # number=27 prog.x(input_qubit[3]) # number=28 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 20 21:07:00 2019 @author: hnorlen """ from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 5: Three-qubit coin toss") print("---------------------------") qc = QuantumCircuit(3, 3) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts)) qc.barrier([0, 1, 2]) qc.reset([0, 1, 2]) qc.h(0)
def _define(self): """W Gate definition.""" q = QuantumRegister(1, "q") qc = QuantumCircuit(q) qc.data = [(HGate(), [q[0]], []), (SGate(), [q[0]], [])] self.definition = qc
def create_circuit(parameters=None, x=None, pad=True): n_params=len(parameters) beta = parameters[0] theta1 = parameters[1:int((n_params+1)/2)] theta2 = parameters[int((n_params+1)/2):int(n_params)] control = QuantumRegister(1, 'control') data = QuantumRegister(2, 'data') temp = QuantumRegister(2, 'temp') c = ClassicalRegister(1) qc = QuantumCircuit(control, data, temp, c) S = get_Sx(ang=x, x=None, pad=True, circuit=True) R = R_gate(beta, circuit=True) sig=sigma(pad, circuit=True) G1 = linear_operator(theta1, pad=True, circuit=True) G2 = linear_operator(theta2, pad=True, circuit=True) qc.compose(R, qubits=control, inplace=True) qc.compose(S, qubits=data, inplace=True) qc.barrier() qc.cswap(control, data[0], temp[0]) qc.cswap(control, data[1], temp[1]) qc.barrier() qc.compose(G1, qubits=data, inplace=True) qc.compose(G2, qubits=temp, inplace=True) qc.barrier() qc.cswap(control, data[1], temp[1]) qc.cswap(control, data[0], temp[0]) qc.barrier() qc.compose(sig, qubits=data, inplace=True) qc.barrier() qc.measure(data[0], c) return qc
def test_simplification(self): """ Test Hamiltonians produce same result after simplification by constructor """ q = QuantumRegister(2, name='q') qc = QuantumCircuit(q) qc.rx(10.9891251356965, 0) qc.rx(6.286692023269373, 1) qc.rz(7.848801398269382, 0) qc.rz(9.42477796076938, 1) qc.cx(0, 1) def eval_op(op): from qiskit import execute backend = BasicAer.get_backend('qasm_simulator') evaluation_circuits = op.construct_evaluation_circuit(qc, False) job = execute(evaluation_circuits, backend, shots=1024) return op.evaluate_with_result(job.result(), False) pauli_string = [[1.0, Pauli.from_label('XX')], [-1.0, Pauli.from_label('YY')], [-1.0, Pauli.from_label('ZZ')]] wpo = WeightedPauliOperator(pauli_string) expectation_value, _ = eval_op(wpo) self.assertAlmostEqual(expectation_value, -3.0, places=2) # Half each coefficient value but double up (6 Paulis total) pauli_string = [[0.5, Pauli.from_label('XX')], [-0.5, Pauli.from_label('YY')], [-0.5, Pauli.from_label('ZZ')]] pauli_string *= 2 wpo2 = WeightedPauliOperator(pauli_string) expectation_value, _ = eval_op(wpo2) self.assertAlmostEqual(expectation_value, -3.0, places=2)
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.cx(input_qubit[0],input_qubit[3]) # number=13 prog.cx(input_qubit[0],input_qubit[3]) # number=17 prog.x(input_qubit[3]) # number=18 prog.rx(-3.1101767270538954,input_qubit[1]) # number=27 prog.cx(input_qubit[0],input_qubit[3]) # number=19 prog.cx(input_qubit[0],input_qubit[3]) # number=15 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[3]) # number=12 prog.h(input_qubit[1]) # number=26 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.x(input_qubit[3]) # number=29 prog.h(input_qubit[2]) # number=7 prog.cx(input_qubit[3],input_qubit[0]) # number=20 prog.h(input_qubit[0]) # number=32 prog.cz(input_qubit[3],input_qubit[0]) # number=33 prog.h(input_qubit[0]) # number=34 prog.cx(input_qubit[3],input_qubit[0]) # number=41 prog.z(input_qubit[3]) # number=42 prog.cx(input_qubit[3],input_qubit[0]) # number=43 prog.h(input_qubit[0]) # number=38 prog.cz(input_qubit[3],input_qubit[0]) # number=39 prog.h(input_qubit[0]) # number=40 prog.cx(input_qubit[3],input_qubit[0]) # number=22 prog.h(input_qubit[3]) # number=8 prog.cx(input_qubit[3],input_qubit[0]) # number=35 prog.z(input_qubit[3]) # number=36 prog.cx(input_qubit[3],input_qubit[0]) # number=37 prog.h(input_qubit[0]) # number=9 prog.y(input_qubit[2]) # number=10 prog.y(input_qubit[2]) # number=11 prog.x(input_qubit[1]) # number=30 prog.x(input_qubit[1]) # number=31 # circuit end return prog
def add_circuits(self, n_circuits, do_measure=True, basis=None, basis_weights=None): """Adds circuits to program. Generates a circuit with a random number of operations in `basis`. Also adds a random number of measurements in [1,nQubits] to end of circuit. Args: n_circuits (int): Number of circuits to add. do_measure (bool): Whether to add measurements. basis (list(str) or None): List of op names. If None, basis is randomly chosen with unique ops in (2,7) basis_weights (list(float) or None): List of weights corresponding to indices in `basis`. Raises: AttributeError: if operation is not recognized. """ if basis is None: basis = list(random.sample(self.op_signature.keys(), random.randint(2, 7))) basis_weights = [1./len(basis)] * len(basis) if basis_weights is not None: assert len(basis) == len(basis_weights) uop_basis = basis[:] if basis_weights: uop_basis_weights = basis_weights[:] else: uop_basis_weights = None # remove barrier from uop basis if it is specified if 'barrier' in uop_basis: ind = uop_basis.index('barrier') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # remove measure from uop basis if it is specified if 'measure' in uop_basis: ind = uop_basis.index('measure') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # self.basis_gates = uop_basis self.basis_gates = basis self.circuit_name_list = [] # TODO: replace choices with random.choices() when python 3.6 is # required. self.n_qubit_list = choices( range(self.min_qubits, self.max_qubits + 1), k=n_circuits) self.depth_list = choices( range(self.min_depth, self.max_depth + 1), k=n_circuits) for i_circuit in range(n_circuits): n_qubits = self.n_qubit_list[i_circuit] if self.min_regs_exceeds_nqubits(uop_basis, n_qubits): # no gate operation from this circuit can fit in the available # number of qubits. continue depth_cnt = self.depth_list[i_circuit] reg_pop = numpy.arange(1, n_qubits+1) register_weights = reg_pop[::-1].astype(float) register_weights /= register_weights.sum() max_registers = numpy.random.choice(reg_pop, p=register_weights) reg_weight = numpy.ones(max_registers) / float(max_registers) reg_sizes = rand_register_sizes(n_qubits, reg_weight) n_registers = len(reg_sizes) circuit = QuantumCircuit() for i_size, size in enumerate(reg_sizes): cr_name = 'cr' + str(i_size) qr_name = 'qr' + str(i_size) creg = ClassicalRegister(size, cr_name) qreg = QuantumRegister(size, qr_name) circuit.add(qreg, creg) while depth_cnt > 0: # TODO: replace choices with random.choices() when python 3.6 # is required. op_name = choices(basis, weights=basis_weights)[0] if hasattr(circuit, op_name): operator = getattr(circuit, op_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(op_name)) n_regs = self.op_signature[op_name]['nregs'] n_params = self.op_signature[op_name]['nparams'] if n_regs == 0: # this is a barrier or measure n_regs = random.randint(1, n_qubits) if n_qubits >= n_regs: # warning: assumes op function signature specifies # op parameters before qubits op_args = [] if n_params: op_args = [random.random() for _ in range(n_params)] if op_name == 'measure': # if measure occurs here, assume it's to do a conditional # randomly select a register to measure ireg = random.randint(0, n_registers-1) qr_name = 'qr' + str(ireg) cr_name = 'cr' + str(ireg) qreg = circuit.regs[qr_name] creg = circuit.regs[cr_name] for qind in range(qreg.size): operator(qreg[qind], creg[qind]) ifval = random.randint(0, (1 << qreg.size) - 1) # TODO: replace choices with random.choices() when # python 3.6 is required. uop_name = choices(uop_basis, weights=uop_basis_weights)[0] if hasattr(circuit, uop_name): uop = getattr(circuit, uop_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(uop_name)) unregs = self.op_signature[uop_name]['nregs'] unparams = self.op_signature[uop_name]['nparams'] if unregs == 0: # this is a barrier or measure unregs = random.randint(1, n_qubits) if qreg.size >= unregs: qind_list = random.sample(range(qreg.size), unregs) uop_args = [] if unparams: uop_args = [random.random() for _ in range(unparams)] uop_args.extend([qreg[qind] for qind in qind_list]) uop(*uop_args).c_if(creg, ifval) depth_cnt -= 1 elif op_name == 'barrier': ireg = random.randint(0, n_registers-1) qr_name = 'qr' + str(ireg) qreg = circuit.regs[qr_name] bar_args = [(qreg, mi) for mi in range(qreg.size)] operator(*bar_args) else: # select random register ireg = random.randint(0, n_registers-1) qr_name = 'qr' + str(ireg) qreg = circuit.regs[qr_name] if qreg.size >= n_regs: qind_list = random.sample(range(qreg.size), n_regs) op_args.extend([qreg[qind] for qind in qind_list]) operator(*op_args) depth_cnt -= 1 else: break nmeasure = random.randint(1, n_qubits) m_list = random.sample(range(nmeasure), nmeasure) if do_measure: for qind in m_list: rind = 0 # register index cumtot = 0 while qind >= cumtot + circuit.regs['qr' + str(rind)].size: cumtot += circuit.regs['qr' + str(rind)].size rind += 1 qrind = int(qind - cumtot) qreg = circuit.regs['qr'+str(rind)] creg = circuit.regs['cr'+str(rind)] circuit.measure(qreg[qrind], creg[qrind]) self.circuit_list.append(circuit)
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=20 prog.cz(input_qubit[0], input_qubit[3]) # number=21 prog.h(input_qubit[3]) # number=22 prog.x(input_qubit[3]) # number=13 prog.h(input_qubit[3]) # number=23 prog.cz(input_qubit[0], input_qubit[3]) # number=24 prog.h(input_qubit[3]) # number=25 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 prog.y(input_qubit[2]) # number=18 prog.cx(input_qubit[3], input_qubit[0]) # number=40 prog.z(input_qubit[3]) # number=41 prog.h(input_qubit[0]) # number=43 prog.cz(input_qubit[3], input_qubit[0]) # number=44 prog.h(input_qubit[0]) # number=45 oracle = build_oracle(n - 1, f) prog.append(oracle.to_gate(), [input_qubit[i] for i in range(n - 1)] + [input_qubit[n - 1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 prog.h(input_qubit[0]) # number=33 prog.cz(input_qubit[2], input_qubit[0]) # number=34 prog.h(input_qubit[0]) # number=35 prog.h(input_qubit[1]) # number=19 prog.h(input_qubit[0]) # number=15 prog.cz(input_qubit[2], input_qubit[0]) # number=16 prog.h(input_qubit[0]) # number=17 prog.rx(1.6838936623241292, input_qubit[2]) # number=36 prog.y(input_qubit[1]) # number=26 prog.y(input_qubit[1]) # number=27 prog.swap(input_qubit[1], input_qubit[0]) # number=29 prog.swap(input_qubit[1], input_qubit[0]) # number=30 prog.x(input_qubit[0]) # number=31 prog.cx(input_qubit[1], input_qubit[0]) # number=37 prog.x(input_qubit[0]) # number=38 prog.cx(input_qubit[1], input_qubit[0]) # number=39 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
class TestStandard1Q(StandardExtensionTest): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.c) self.c_header = 69 # lenght of the header def test_barrier(self): self.circuit.barrier(self.q[1]) qasm_txt = 'barrier q[1];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.barrier, self.c[0]) self.assertRaises(QISKitError, c.barrier, self.c) self.assertRaises(QISKitError, c.barrier, (self.q, 3)) self.assertRaises(QISKitError, c.barrier, (self.q, 'a')) self.assertRaises(QISKitError, c.barrier, 0) def test_barrier_reg(self): self.circuit.barrier(self.q) qasm_txt = 'barrier q[0],q[1],q[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ccx(self): self.circuit.ccx(self.q[0], self.q[1], self.q[2]) qasm_txt = 'ccx q[0],q[1],q[2];' self.assertResult(ToffoliGate, qasm_txt, qasm_txt) def test_ccx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ccx, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.ccx, self.q[0], self.q[0], self.q[2]) self.assertRaises(QISKitError, c.ccx, 0, self.q[0], self.q[2]) self.assertRaises(QISKitError, c.ccx, (self.q, 3), self.q[1], self.q[2]) self.assertRaises(QISKitError, c.ccx, self.c, self.q, self.q) self.assertRaises(QISKitError, c.ccx, 'a', self.q[1], self.q[2]) def test_ch(self): self.circuit.ch(self.q[0], self.q[1]) qasm_txt = 'ch q[0],q[1];' self.assertResult(CHGate, qasm_txt, qasm_txt) def test_ch_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ch, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.ch, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.ch, 0, self.q[0]) self.assertRaises(QISKitError, c.ch, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.ch, self.c, self.q) self.assertRaises(QISKitError, c.ch, 'a', self.q[1]) def test_crz(self): self.circuit.crz(1, self.q[0], self.q[1]) self.assertResult(CrzGate, 'crz(1) q[0],q[1];', 'crz(-1) q[0],q[1];') def test_crz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.crz, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.crz, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.crz, 0, 0, self.q[0]) # TODO self.assertRaises(QISKitError, c.crz, self.q[2], self.q[1], self.q[0]) self.assertRaises(QISKitError, c.crz, 0, self.q[1], self.c[2]) self.assertRaises(QISKitError, c.crz, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.crz, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.crz, 'a', self.q[1], self.q[2]) def test_cswap(self): self.circuit.cswap(self.q[0], self.q[1], self.q[2]) qasm_txt = 'cx q[2],q[1];\nccx q[0],q[1],q[2];\ncx q[2],q[1];' self.assertResult(FredkinGate, qasm_txt, qasm_txt) def test_cswap_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cswap, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cswap, self.q[1], self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cswap, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cswap, self.c[0], self.c[1], self.q[0]) self.assertRaises(QISKitError, c.cswap, self.q[0], self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, 0, self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, (self.q, 3), self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, self.c, self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, 'a', self.q[1], self.q[2]) def test_cu1(self): self.circuit.cu1(1, self.q[1], self.q[2]) self.assertResult(Cu1Gate, 'cu1(1) q[1],q[2];', 'cu1(-1) q[1],q[2];') def test_cu1_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cu1, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cu1, 1, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu1, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.cu1, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, 0, self.q[0]) # TODO self.assertRaises(QISKitError, c.cu1, self.q[2], self.q[1], self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, self.q[1], self.c[2]) self.assertRaises(QISKitError, c.cu1, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.cu1, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.cu1, 'a', self.q[1], self.q[2]) def test_cu3(self): self.circuit.cu3(1, 2, 3, self.q[1], self.q[2]) self.assertResult(Cu3Gate, 'cu3(1,2,3) q[1],q[2];', 'cu3(-1,-3,-2) q[1],q[2];') def test_cu3_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cu3, 0, 0, self.q[0], self.q[1], self.c[2]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, 0, self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.cu3, 0, 0, 'a', self.q[1], self.q[2]) def test_cx(self): self.circuit.cx(self.q[1], self.q[2]) qasm_txt = 'cx q[1],q[2];' self.assertResult(CnotGate, qasm_txt, qasm_txt) def test_cx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cx, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cx, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cx, 0, self.q[0]) self.assertRaises(QISKitError, c.cx, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cx, self.c, self.q) self.assertRaises(QISKitError, c.cx, 'a', self.q[1]) def test_cxbase(self): qasm_txt = 'CX q[1],q[2];' self.circuit.cx_base(self.q[1], self.q[2]) self.assertResult(CXBase, qasm_txt, qasm_txt) def test_cxbase_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cx_base, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cx_base, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cx_base, 0, self.q[0]) self.assertRaises(QISKitError, c.cx_base, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cx_base, self.c, self.q) self.assertRaises(QISKitError, c.cx_base, 'a', self.q[1]) def test_cy(self): qasm_txt = 'cy q[1],q[2];' self.circuit.cy(self.q[1], self.q[2]) self.assertResult(CyGate, qasm_txt, qasm_txt) def test_cy_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cy, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cy, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cy, 0, self.q[0]) self.assertRaises(QISKitError, c.cy, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cy, self.c, self.q) self.assertRaises(QISKitError, c.cy, 'a', self.q[1]) def test_cz(self): qasm_txt = 'cz q[1],q[2];' self.circuit.cz(self.q[1], self.q[2]) self.assertResult(CzGate, qasm_txt, qasm_txt) def test_cz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cz, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cz, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cz, 0, self.q[0]) self.assertRaises(QISKitError, c.cz, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cz, self.c, self.q) self.assertRaises(QISKitError, c.cz, 'a', self.q[1]) def test_h(self): qasm_txt = 'h q[1];' self.circuit.h(self.q[1]) self.assertResult(HGate, qasm_txt, qasm_txt) def test_h_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.h, self.c[0]) self.assertRaises(QISKitError, c.h, self.c) self.assertRaises(QISKitError, c.h, (self.q, 3)) self.assertRaises(QISKitError, c.h, (self.q, 'a')) self.assertRaises(QISKitError, c.h, 0) def test_h_reg(self): qasm_txt = 'h q[0];\nh q[1];\nh q[2];' instruction_set = self.circuit.h(self.q) self.assertStmtsType(instruction_set.instructions, HGate) self.assertQasm(qasm_txt) def test_h_reg_inv(self): qasm_txt = 'h q[0];\nh q[1];\nh q[2];' instruction_set = self.circuit.h(self.q).inverse() self.assertStmtsType(instruction_set.instructions, HGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_iden(self): self.circuit.iden(self.q[1]) self.assertResult(IdGate, 'id q[1];', 'id q[1];') def test_iden_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.iden, self.c[0]) self.assertRaises(QISKitError, c.iden, self.c) self.assertRaises(QISKitError, c.iden, (self.q, 3)) self.assertRaises(QISKitError, c.iden, (self.q, 'a')) self.assertRaises(QISKitError, c.iden, 0) def test_iden_reg(self): qasm_txt = 'id q[0];\nid q[1];\nid q[2];' instruction_set = self.circuit.iden(self.q) self.assertStmtsType(instruction_set.instructions, IdGate) self.assertQasm(qasm_txt) def test_iden_reg_inv(self): qasm_txt = 'id q[0];\nid q[1];\nid q[2];' instruction_set = self.circuit.iden(self.q).inverse() self.assertStmtsType(instruction_set.instructions, IdGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 25) def test_rx(self): self.circuit.rx(1, self.q[1]) self.assertResult(RXGate, 'rx(1) q[1];', 'rx(-1) q[1];') def test_rx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.rx, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.rx, self.q[1], 0) self.assertRaises(QISKitError, c.rx, 0, self.c[0]) self.assertRaises(QISKitError, c.rx, 0, 0) # TODO self.assertRaises(QISKitError, c.rx, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.rx, 0, (self.q, 3)) self.assertRaises(QISKitError, c.rx, 0, self.c) # TODO self.assertRaises(QISKitError, c.rx, 'a', self.q[1]) self.assertRaises(QISKitError, c.rx, 0, 'a') def test_rx_reg(self): qasm_txt = 'rx(1) q[0];\nrx(1) q[1];\nrx(1) q[2];' instruction_set = self.circuit.rx(1, self.q) self.assertStmtsType(instruction_set.instructions, RXGate) self.assertQasm(qasm_txt) def test_rx_reg_inv(self): qasm_txt = 'rx(-1) q[0];\nrx(-1) q[1];\nrx(-1) q[2];' instruction_set = self.circuit.rx(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RXGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_rx_pi(self): c = self.circuit c.rx(pi / 2, self.q[1]) self.assertResult(RXGate, 'rx(pi/2) q[1];', 'rx(-pi/2) q[1];') def test_ry(self): self.circuit.ry(1, self.q[1]) self.assertResult(RYGate, 'ry(1) q[1];', 'ry(-1) q[1];') def test_ry_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ry, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.ry, self.q[1], 0) self.assertRaises(QISKitError, c.ry, 0, self.c[0]) self.assertRaises(QISKitError, c.ry, 0, 0) # TODO self.assertRaises(QISKitError, c.ry, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.ry, 0, (self.q, 3)) self.assertRaises(QISKitError, c.ry, 0, self.c) # TODO self.assertRaises(QISKitError, c.ry, 'a', self.q[1]) self.assertRaises(QISKitError, c.ry, 0, 'a') def test_ry_reg(self): qasm_txt = 'ry(1) q[0];\nry(1) q[1];\nry(1) q[2];' instruction_set = self.circuit.ry(1, self.q) self.assertStmtsType(instruction_set.instructions, RYGate) self.assertQasm(qasm_txt) def test_ry_reg_inv(self): qasm_txt = 'ry(-1) q[0];\nry(-1) q[1];\nry(-1) q[2];' instruction_set = self.circuit.ry(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RYGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_ry_pi(self): c = self.circuit c.ry(pi / 2, self.q[1]) self.assertResult(RYGate, 'ry(pi/2) q[1];', 'ry(-pi/2) q[1];') def test_rz(self): self.circuit.rz(1, self.q[1]) self.assertResult(RZGate, 'rz(1) q[1];', 'rz(-1) q[1];') def test_rz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.rz, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.rz, self.q[1], 0) self.assertRaises(QISKitError, c.rz, 0, self.c[0]) self.assertRaises(QISKitError, c.rz, 0, 0) # TODO self.assertRaises(QISKitError, c.rz, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.rz, 0, (self.q, 3)) self.assertRaises(QISKitError, c.rz, 0, self.c) # TODO self.assertRaises(QISKitError, c.rz, 'a', self.q[1]) self.assertRaises(QISKitError, c.rz, 0, 'a') def test_rz_reg(self): qasm_txt = 'rz(1) q[0];\nrz(1) q[1];\nrz(1) q[2];' instruction_set = self.circuit.rz(1, self.q) self.assertStmtsType(instruction_set.instructions, RZGate) self.assertQasm(qasm_txt) def test_rz_reg_inv(self): qasm_txt = 'rz(-1) q[0];\nrz(-1) q[1];\nrz(-1) q[2];' instruction_set = self.circuit.rz(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RZGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_rz_pi(self): c = self.circuit c.rz(pi / 2, self.q[1]) self.assertResult(RZGate, 'rz(pi/2) q[1];', 'rz(-pi/2) q[1];') def test_s(self): self.circuit.s(self.q[1]) self.assertResult(SGate, 's q[1];', 'sdg q[1];') def test_s_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.s, self.c[0]) self.assertRaises(QISKitError, c.s, self.c) self.assertRaises(QISKitError, c.s, (self.q, 3)) self.assertRaises(QISKitError, c.s, (self.q, 'a')) self.assertRaises(QISKitError, c.s, 0) def test_s_reg(self): qasm_txt = 's q[0];\ns q[1];\ns q[2];' instruction_set = self.circuit.s(self.q) self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt) def test_s_reg_inv(self): qasm_txt = 'sdg q[0];\nsdg q[1];\nsdg q[2];' instruction_set = self.circuit.s(self.q).inverse() self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 28) def test_sdg(self): self.circuit.sdg(self.q[1]) self.assertResult(SGate, 'sdg q[1];', 's q[1];') def test_sdg_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.sdg, self.c[0]) self.assertRaises(QISKitError, c.sdg, self.c) self.assertRaises(QISKitError, c.sdg, (self.q, 3)) self.assertRaises(QISKitError, c.sdg, (self.q, 'a')) self.assertRaises(QISKitError, c.sdg, 0) def test_sdg_reg(self): qasm_txt = 'sdg q[0];\nsdg q[1];\nsdg q[2];' instruction_set = self.circuit.sdg(self.q) self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt) def test_sdg_reg_inv(self): qasm_txt = 's q[0];\ns q[1];\ns q[2];' instruction_set = self.circuit.sdg(self.q).inverse() self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_swap(self): self.circuit.swap(self.q[1], self.q[2]) self.assertResult(SwapGate, 'swap q[1],q[2];', 'swap q[1],q[2];') def test_swap_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.swap, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.swap, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.swap, 0, self.q[0]) self.assertRaises(QISKitError, c.swap, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.swap, self.c, self.q) self.assertRaises(QISKitError, c.swap, 'a', self.q[1]) self.assertRaises(QISKitError, c.swap, self.q, self.r[1]) self.assertRaises(QISKitError, c.swap, self.q[1], self.r) def test_t(self): c = self.circuit self.assertRaises(QISKitError, c.t, self.c[0]) # TODO self.assertRaises(QISKitError, c.t, 1) c.t(self.q[1]) self.assertResult(TGate, 't q[1];', 'tdg q[1];') def test_t_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.t, self.c[0]) self.assertRaises(QISKitError, c.t, self.c) self.assertRaises(QISKitError, c.t, (self.q, 3)) self.assertRaises(QISKitError, c.t, (self.q, 'a')) self.assertRaises(QISKitError, c.t, 0) def test_t_reg(self): qasm_txt = 't q[0];\nt q[1];\nt q[2];' instruction_set = self.circuit.t(self.q) self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt) def test_t_reg_inv(self): qasm_txt = 'tdg q[0];\ntdg q[1];\ntdg q[2];' instruction_set = self.circuit.t(self.q).inverse() self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 28) def test_tdg(self): c = self.circuit self.assertRaises(QISKitError, c.tdg, self.c[0]) # TODO self.assertRaises(QISKitError, c.tdg, 1) c.tdg(self.q[1]) self.assertResult(TGate, 'tdg q[1];', 't q[1];') def test_tdg_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.tdg, self.c[0]) self.assertRaises(QISKitError, c.tdg, self.c) self.assertRaises(QISKitError, c.tdg, (self.q, 3)) self.assertRaises(QISKitError, c.tdg, (self.q, 'a')) self.assertRaises(QISKitError, c.tdg, 0) def test_tdg_reg(self): qasm_txt = 'tdg q[0];\ntdg q[1];\ntdg q[2];' instruction_set = self.circuit.tdg(self.q) self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt) def test_tdg_reg_inv(self): qasm_txt = 't q[0];\nt q[1];\nt q[2];' instruction_set = self.circuit.tdg(self.q).inverse() self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_u1(self): self.circuit.u1(1, self.q[1]) self.assertResult(U1Gate, 'u1(1) q[1];', 'u1(-1) q[1];') def test_u1_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u1, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u1, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u1, self.q[1], 0) self.assertRaises(QISKitError, c.u1, 0, self.c[0]) self.assertRaises(QISKitError, c.u1, 0, 0) # TODO self.assertRaises(QISKitError, c.u1, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u1, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u1, 0, self.c) # TODO self.assertRaises(QISKitError, c.u1, 'a', self.q[1]) self.assertRaises(QISKitError, c.u1, 0, 'a') def test_u1_reg(self): qasm_txt = 'u1(1) q[0];\nu1(1) q[1];\nu1(1) q[2];' instruction_set = self.circuit.u1(1, self.q) self.assertStmtsType(instruction_set.instructions, U1Gate) self.assertQasm(qasm_txt) def test_u1_reg_inv(self): qasm_txt = 'u1(-1) q[0];\nu1(-1) q[1];\nu1(-1) q[2];' instruction_set = self.circuit.u1(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U1Gate) self.assertQasm(qasm_txt) def test_u1_pi(self): c = self.circuit c.u1(pi / 2, self.q[1]) self.assertResult(U1Gate, 'u1(pi/2) q[1];', 'u1(-pi/2) q[1];') def test_u2(self): self.circuit.u2(1, 2, self.q[1]) self.assertResult(U2Gate, 'u2(1,2) q[1];', 'u2(-pi - 2,-1 + pi) q[1];') def test_u2_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u2, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u2, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u2, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u2, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u2, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u2, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u2, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u2, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u2, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u2, 0, 0, 'a') def test_u2_reg(self): qasm_txt = 'u2(1,2) q[0];\nu2(1,2) q[1];\nu2(1,2) q[2];' instruction_set = self.circuit.u2(1, 2, self.q) self.assertStmtsType(instruction_set.instructions, U2Gate) self.assertQasm(qasm_txt) def test_u2_reg_inv(self): qasm_txt = 'u2(-pi - 2,-1 + pi) q[0];\nu2(-pi - 2,-1 + pi) q[1];\nu2(-pi - 2,-1 + pi) q[2];' instruction_set = self.circuit.u2(1, 2, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U2Gate) self.assertQasm(qasm_txt) def test_u2_pi(self): c = self.circuit c.u2(pi / 2, 0.3 * pi, self.q[1]) self.assertResult(U2Gate, 'u2(pi/2,0.3*pi) q[1];', 'u2(-1.3*pi,pi/2) q[1];') def test_u3(self): self.circuit.u3(1, 2, 3, self.q[1]) self.assertResult(U3Gate, 'u3(1,2,3) q[1];', 'u3(-1,-3,-2) q[1];') def test_u3_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u3, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u3, 0, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u3, 0, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u3, 0, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u3, 0, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u3, 0, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u3, 0, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, 'a') def test_u3_reg(self): qasm_txt = 'u3(1,2,3) q[0];\nu3(1,2,3) q[1];\nu3(1,2,3) q[2];' instruction_set = self.circuit.u3(1, 2, 3, self.q) self.assertStmtsType(instruction_set.instructions, U3Gate) self.assertQasm(qasm_txt) def test_u3_reg_inv(self): qasm_txt = 'u3(-1,-3,-2) q[0];\nu3(-1,-3,-2) q[1];\nu3(-1,-3,-2) q[2];' instruction_set = self.circuit.u3(1, 2, 3, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U3Gate) self.assertQasm(qasm_txt) def test_u3_pi(self): c = self.circuit c.u3(pi, pi / 2, 0.3 * pi, self.q[1]) self.assertResult(U3Gate, 'u3(pi,pi/2,0.3*pi) q[1];', 'u3(-pi,-0.3*pi,-pi/2) q[1];') def test_ubase(self): self.circuit.u_base(1, 2, 3, self.q[1]) self.assertResult(UBase, 'U(1,2,3) q[1];', 'U(-1,-3,-2) q[1];') def test_ubase_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u_base, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u_base, 0, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u_base, 0, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u_base, 0, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, 'a') def test_ubase_reg(self): qasm_txt = 'U(1,2,3) q[0];\nU(1,2,3) q[1];\nU(1,2,3) q[2];' instruction_set = self.circuit.u_base(1, 2, 3, self.q) self.assertStmtsType(instruction_set.instructions, UBase) self.assertQasm(qasm_txt) def test_ubase_reg_inv(self): qasm_txt = 'U(-1,-3,-2) q[0];\nU(-1,-3,-2) q[1];\nU(-1,-3,-2) q[2];' instruction_set = self.circuit.u_base(1, 2, 3, self.q).inverse() self.assertStmtsType(instruction_set.instructions, UBase) self.assertQasm(qasm_txt) def test_ubase_pi(self): c = self.circuit c.u_base(pi, pi / 2, 0.3 * pi, self.q[1]) self.assertResult(UBase, 'U(pi,pi/2,0.3*pi) q[1];', 'U(-pi,-0.3*pi,-pi/2) q[1];') def test_x(self): self.circuit.x(self.q[1]) self.assertResult(XGate, 'x q[1];', 'x q[1];') def test_x_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.x, self.c[0]) self.assertRaises(QISKitError, c.x, self.c) self.assertRaises(QISKitError, c.x, (self.q, 3)) self.assertRaises(QISKitError, c.x, (self.q, 'a')) self.assertRaises(QISKitError, c.x, 0) def test_x_reg(self): qasm_txt = 'x q[0];\nx q[1];\nx q[2];' instruction_set = self.circuit.x(self.q) self.assertStmtsType(instruction_set.instructions, XGate) self.assertQasm(qasm_txt) def test_x_reg_inv(self): qasm_txt = 'x q[0];\nx q[1];\nx q[2];' instruction_set = self.circuit.x(self.q).inverse() self.assertStmtsType(instruction_set.instructions, XGate) self.assertQasm(qasm_txt) def test_y(self): self.circuit.y(self.q[1]) self.assertResult(YGate, 'y q[1];', 'y q[1];') def test_y_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.y, self.c[0]) self.assertRaises(QISKitError, c.y, self.c) self.assertRaises(QISKitError, c.y, (self.q, 3)) self.assertRaises(QISKitError, c.y, (self.q, 'a')) self.assertRaises(QISKitError, c.y, 0) def test_y_reg(self): qasm_txt = 'y q[0];\ny q[1];\ny q[2];' instruction_set = self.circuit.y(self.q) self.assertStmtsType(instruction_set.instructions, YGate) self.assertQasm(qasm_txt) def test_y_reg_inv(self): qasm_txt = 'y q[0];\ny q[1];\ny q[2];' instruction_set = self.circuit.y(self.q).inverse() self.assertStmtsType(instruction_set.instructions, YGate) self.assertQasm(qasm_txt) def test_z(self): self.circuit.z(self.q[1]) self.assertResult(ZGate, 'z q[1];', 'z q[1];') def test_rzz(self): c = self.circuit self.assertRaises(QISKitError, c.rzz, 0.1, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.rzz, 0.1, self.q[0], self.q[0]) c.rzz(pi/2, self.q[1], self.q[2]) self.assertResult(RZZGate, 'rzz(pi/2) q[1],q[2];', 'rzz(-pi/2) q[1],q[2];') def assertResult(self, t, qasm_txt, qasm_txt_): """ t: type qasm_txt: qasm representation qasm_txt_: qasm representation of inverse """ c = self.circuit self.assertRaises(QISKitError, c.z, self.c[0]) self.assertRaises(QISKitError, c.z, self.c) self.assertRaises(QISKitError, c.z, (self.q, 3)) self.assertRaises(QISKitError, c.z, (self.q, 'a')) self.assertRaises(QISKitError, c.z, 0) def test_z_reg(self): qasm_txt = 'z q[0];\nz q[1];\nz q[2];' instruction_set = self.circuit.z(self.q) self.assertStmtsType(instruction_set.instructions, ZGate) self.assertQasm(qasm_txt) def test_z_reg_inv(self): qasm_txt = 'z q[0];\nz q[1];\nz q[2];' instruction_set = self.circuit.z(self.q).inverse() self.assertStmtsType(instruction_set.instructions, ZGate) self.assertQasm(qasm_txt)
# negative_superposition_state_xbasis.py from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer # Define the Quantum and Classical Registers q = QuantumRegister(1) c = ClassicalRegister(1) # Build the circuit negative_superposition_state_xbasis = QuantumCircuit(q, c) negative_superposition_state_xbasis.x(q) negative_superposition_state_xbasis.h(q) negative_superposition_state_xbasis.barrier() negative_superposition_state_xbasis.h(q) negative_superposition_state_xbasis.measure(q, c) # Execute the circuit job = execute(negative_superposition_state_xbasis, backend = Aer.get_backend('qasm_simulator'), shots=1024) result = job.result() # Print the result print(result.get_counts(negative_superposition_state_xbasis))
def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393 """ circuit = QuantumCircuit(2, 3) self.circuit_drawer(circuit, filename='no_op_circut.png')
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=24 prog.cz(input_qubit[0], input_qubit[3]) # number=25 prog.h(input_qubit[3]) # number=26 prog.h(input_qubit[3]) # number=21 prog.cz(input_qubit[0], input_qubit[3]) # number=22 prog.h(input_qubit[3]) # number=23 prog.h(input_qubit[3]) # number=27 prog.cz(input_qubit[0], input_qubit[3]) # number=28 prog.h(input_qubit[3]) # number=29 prog.cx(input_qubit[0], input_qubit[3]) # number=30 prog.x(input_qubit[3]) # number=31 prog.h(input_qubit[3]) # number=33 prog.cz(input_qubit[0], input_qubit[3]) # number=34 prog.h(input_qubit[3]) # number=35 prog.cx(input_qubit[0], input_qubit[3]) # number=18 prog.rx(-0.364424747816416, input_qubit[3]) # number=36 prog.y(input_qubit[3]) # number=20 prog.h(input_qubit[3]) # number=37 prog.cz(input_qubit[0], input_qubit[3]) # number=38 prog.h(input_qubit[3]) # number=39 prog.cx(input_qubit[0], input_qubit[3]) # number=12 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n - 1, f) prog.append(oracle.to_gate(), [input_qubit[i] for i in range(n - 1)] + [input_qubit[n - 1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=19 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 # circuit end return prog
def test_empty_circuit(self): """Test empty circuit""" circuit = QuantumCircuit() self.circuit_drawer(circuit, filename='empty_circut.png')
def run_bench(benchmark, nqubits, gate, locs=(1, )): qc = QuantumCircuit(nqubits) getattr(qc, gate)(*locs) native_execute(benchmark, qc, default_options)
def trial_circuit_ryrz(n, m, theta, entangler_map, meas_string = None, measurement = True): """Trial function for classical optimization problems. n = number of qubits m = depth theta = control vector of size n*m*2 stacked as theta[n*i*2+2*j+p] where j counts the qubits and i the depth and p if y and z. entangler_map = {0: [2, 1], 1: [2], 3: [2], 4: [2]} control is the key and values are the target pauli_string = length of number of qubits string """ q = QuantumRegister("q", n) c = ClassicalRegister("c", n) trial_circuit = QuantumCircuit(q, c) trial_circuit.h(q) if meas_string is None: meas_string = [None for x in range(n)] for i in range(m): trial_circuit.barrier(q) for node in entangler_map: for j in entangler_map[node]: trial_circuit.cz(q[node], q[j]) for j in range(n): trial_circuit.ry(theta[n * i * 2 + 2*j], q[j]) trial_circuit.rz(theta[n * i * 2 + 2*j + 1], q[j]) trial_circuit.barrier(q) for j in range(n): if meas_string[j] == 'X': trial_circuit.h(q[j]) elif meas_string[j] == 'Y': trial_circuit.s(q[j]).inverse() trial_circuit.h(q[j]) if measurement: for j in range(n): trial_circuit.measure(q[j], c[j]) return trial_circuit
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[1]) # number=29 prog.cz(input_qubit[3],input_qubit[1]) # number=30 prog.h(input_qubit[1]) # number=31 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[4]) # number=21 Zf = build_oracle(n, f) repeat = floor(sqrt(2 ** n) * pi / 4) for i in range(repeat): prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)]) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=38 prog.cz(input_qubit[1],input_qubit[0]) # number=39 prog.h(input_qubit[0]) # number=40 prog.h(input_qubit[0]) # number=51 prog.cz(input_qubit[1],input_qubit[0]) # number=52 prog.h(input_qubit[0]) # number=53 prog.h(input_qubit[0]) # number=64 prog.cz(input_qubit[1],input_qubit[0]) # number=65 prog.h(input_qubit[0]) # number=66 prog.x(input_qubit[0]) # number=49 prog.h(input_qubit[0]) # number=57 prog.cz(input_qubit[1],input_qubit[0]) # number=58 prog.h(input_qubit[0]) # number=59 prog.h(input_qubit[0]) # number=54 prog.cz(input_qubit[1],input_qubit[0]) # number=55 prog.h(input_qubit[0]) # number=56 prog.h(input_qubit[4]) # number=41 prog.h(input_qubit[0]) # number=61 prog.cz(input_qubit[1],input_qubit[0]) # number=62 prog.h(input_qubit[0]) # number=63 prog.cx(input_qubit[0],input_qubit[1]) # number=68 prog.x(input_qubit[1]) # number=69 prog.cx(input_qubit[0],input_qubit[1]) # number=70 prog.h(input_qubit[2]) # number=25 prog.cz(input_qubit[0],input_qubit[2]) # number=26 prog.h(input_qubit[2]) # number=27 prog.x(input_qubit[2]) # number=23 prog.cx(input_qubit[0],input_qubit[2]) # number=24 prog.cx(input_qubit[0],input_qubit[3]) # number=32 prog.x(input_qubit[1]) # number=67 prog.x(input_qubit[3]) # number=33 prog.h(input_qubit[3]) # number=42 prog.cz(input_qubit[0],input_qubit[3]) # number=43 prog.h(input_qubit[3]) # number=44 if n>=2: prog.mcu1(pi,input_qubit[1:],input_qubit[0]) prog.x(input_qubit[0]) # number=13 prog.rx(0.6157521601035993,input_qubit[1]) # number=60 prog.x(input_qubit[1]) # number=14 prog.x(input_qubit[2]) # number=15 prog.x(input_qubit[3]) # number=16 prog.h(input_qubit[0]) # number=17 prog.h(input_qubit[1]) # number=18 prog.h(input_qubit[2]) # number=19 prog.h(input_qubit[3]) # number=20 # circuit end return prog
def add_circuits(self, nCircuits, doMeasure=True, basis=['u3', 'cx'], basis_weights=None): """Adds circuits to program. Generates a circuit with a random number of operations in `basis`. Also adds a random number of measurements in [1,nQubits] to end of circuit. Args: nCircuits (int): Number of circuits to add. doMeasure (bool): Whether to add measurements. basis (list of str): List of op names. basis_weights (list of float or None): List of weights corresponding to indices in `basis`. """ uop_basis = basis[:] if basis_weights: uop_basis_weights = basis_weights[:] else: uop_basis_weights = None # remove barrier from uop basis if it is specified if 'barrier' in uop_basis: ind = uop_basis.index('barrier') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # remove measure from uop basis if it is specified if 'measure' in uop_basis: ind = uop_basis.index('measure') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # self.basis_gates = uop_basis self.basis_gates = basis self.circuitNameList = [] # TODO: replace choices with random.choices() when python 3.6 is # required. self.nQubit_list = choices( range(self.minQubits, self.maxQubits+1), k=nCircuits) self.depth_list = choices( range(self.minDepth, self.maxDepth+1), k=nCircuits) for iCircuit in range(nCircuits): nQubits = self.nQubit_list[iCircuit] depthCnt = self.depth_list[iCircuit] regpop = numpy.arange(1, nQubits+1) registerWeights = regpop[::-1].astype(float) registerWeights /= registerWeights.sum() maxRegisters = numpy.random.choice(regpop, p=registerWeights) regWeight = numpy.ones(maxRegisters) / float(maxRegisters) regSizes = rand_register_sizes(nQubits, regWeight) nRegisters = len(regSizes) circuit = QuantumCircuit() for isize, size in enumerate(regSizes): cr_name = 'cr' + str(isize) qr_name = 'qr' + str(isize) cr = ClassicalRegister(cr_name, size) qr = QuantumRegister(qr_name, size) circuit.add(qr, cr) while depthCnt > 0: # TODO: replace choices with random.choices() when python 3.6 # is required. opName = choices(basis, weights=basis_weights)[0] if hasattr(circuit, opName): op = getattr(circuit, opName) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(opName)) nregs = self.opSignature[opName]['nregs'] nparams = self.opSignature[opName]['nparams'] if nregs == 0: # this is a barrier or measure nregs = random.randint(1, nQubits) if nQubits >= nregs: # warning: assumes op function signature specifies # op parameters before qubits op_args = [] if nparams: op_args = [random.random() for p in range(nparams)] if opName is 'measure': # if measure occurs here, assume it's to do a conditional # randomly select a register to measure ireg = random.randint(0, nRegisters-1) qr_name = 'qr' + str(ireg) cr_name = 'cr' + str(ireg) qreg = circuit.regs[qr_name] creg = circuit.regs[cr_name] for qind in range(qreg.size): op(qreg[qind], creg[qind]) ifval = random.randint(0, (1 << qreg.size) - 1) # TODO: replace choices with random.choices() when # python 3.6 is required. uopName = choices(uop_basis, weights=uop_basis_weights)[0] if hasattr(circuit, uopName): uop = getattr(circuit, uopName) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(uopName)) unregs = self.opSignature[uopName]['nregs'] unparams = self.opSignature[uopName]['nparams'] if unregs == 0: # this is a barrier or measure unregs = random.randint(1, nQubits) if qreg.size >= unregs: qindList = random.sample(range(qreg.size), unregs) uop_args = [] if unparams: uop_args = [random.random() for p in range(unparams)] uop_args.extend([qreg[qind] for qind in qindList]) uop(*uop_args).c_if(creg, ifval) depthCnt -= 1 elif opName is 'barrier': ireg = random.randint(0, nRegisters-1) qr_name = 'qr' + str(ireg) qreg = circuit.regs[qr_name] bar_args = [(qreg, mi) for mi in range(qreg.size)] op(*bar_args) else: # select random register ireg = random.randint(0, nRegisters-1) qr_name = 'qr' + str(ireg) try: qreg = circuit.regs[qr_name] except Exception as e: print(e) import pdb;pdb.set_trace() if qreg.size >= nregs: qindList = random.sample(range(qreg.size), nregs) op_args.extend([qreg[qind] for qind in qindList]) op(*op_args) depthCnt -= 1 nmeasure = random.randint(1, nQubits) mList = random.sample(range(nmeasure), nmeasure) if doMeasure: for qind in mList: rind = 0 # register index cumtot = 0 while qind >= cumtot + circuit.regs['qr' + str(rind)].size: cumtot += circuit.regs['qr' + str(rind)].size rind += 1 qrind = int(qind - cumtot) qreg = circuit.regs['qr'+str(rind)] creg = circuit.regs['cr'+str(rind)] try: circuit.measure(qreg[qrind], creg[qrind]) except Exception as e: print(e) print(qrind) import pdb;pdb.set_trace() self.circuit_list.append(circuit)
def controlledXMixer(self, beta: list, p: int, graph: nx.Graph, inverse: bool = False, measure=False): # allow for ancillary qubits so that controlled rotations can be performed. # Include the controlled X-not version by adding X gates to each side of the controlled qubit line. self.quantum_circuit = [] for i in range(p): cir = QuantumCircuit(len(graph.nodes)) # Get all the q-regs quantum_regs = cir.qregs[0] for n in graph.nodes: bfs = dict(nx.traversal.bfs_successors(graph, n, depth_limit=1)) for source in bfs: if len(bfs[source]) > 0: control_bits = list(quantum_regs[n] for n in bfs[source]) if inverse == True: cir.x(control_bits) cir.mcrx(beta[i], control_bits, quantum_regs[int(source)]) if inverse == True: cir.x(control_bits) if measure == True and i == p - 1: classical_regs = ClassicalRegister(len(graph.nodes)) cir.add_register(classical_regs) cir.measure(quantum_regs, classical_regs) self.quantum_circuit.append(cir)
def clifford_1_qubit_circuit(self, num): """Return the 1-qubit clifford circuit corresponding to `num` where `num` is between 0 and 23. """ # pylint: disable=unbalanced-tuple-unpacking # This is safe since `_unpack_num` returns list the size of the sig (i, j, p) = self._unpack_num(num, self.CLIFFORD_1_QUBIT_SIG) qr = QuantumRegister(1) qc = QuantumCircuit(qr) if i == 1: qc.h(0) if j == 1: qc._append(SXdgGate(), [qr[0]], []) if j == 2: qc._append(SGate(), [qr[0]], []) if p == 1: qc.x(0) if p == 2: qc.y(0) if p == 3: qc.z(0) return qc
def make_circuit(n: int, f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[4]) # number=21 Zf = build_oracle(n, f) repeat = floor(sqrt(2**n) * pi / 4) for i in range(repeat): prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)]) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=31 prog.cz(input_qubit[1], input_qubit[0]) # number=32 prog.h(input_qubit[0]) # number=33 prog.h(input_qubit[1]) # number=44 prog.cz(input_qubit[0], input_qubit[1]) # number=45 prog.h(input_qubit[1]) # number=46 prog.cx(input_qubit[0], input_qubit[1]) # number=48 prog.x(input_qubit[1]) # number=49 prog.cx(input_qubit[0], input_qubit[1]) # number=50 prog.cx(input_qubit[0], input_qubit[1]) # number=42 prog.x(input_qubit[0]) # number=26 prog.cx(input_qubit[1], input_qubit[0]) # number=27 prog.h(input_qubit[1]) # number=37 prog.cz(input_qubit[0], input_qubit[1]) # number=38 prog.h(input_qubit[1]) # number=39 prog.x(input_qubit[1]) # number=35 prog.cx(input_qubit[0], input_qubit[1]) # number=36 prog.x(input_qubit[2]) # number=11 prog.x(input_qubit[3]) # number=12 prog.cx(input_qubit[3], input_qubit[2]) # number=43 prog.cx(input_qubit[3], input_qubit[2]) # number=47 if n >= 2: prog.mcu1(pi, input_qubit[1:], input_qubit[0]) prog.x(input_qubit[0]) # number=13 prog.cx(input_qubit[0], input_qubit[1]) # number=22 prog.x(input_qubit[1]) # number=23 prog.cx(input_qubit[0], input_qubit[1]) # number=24 prog.x(input_qubit[2]) # number=15 prog.x(input_qubit[1]) # number=29 prog.y(input_qubit[4]) # number=28 prog.x(input_qubit[3]) # number=16 prog.h(input_qubit[0]) # number=17 prog.h(input_qubit[1]) # number=18 prog.h(input_qubit[2]) # number=19 prog.h(input_qubit[3]) # number=20 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog
{'local': False, 'simulator': False}) device_status = [get_backend(backend).status for backend in list_of_backends] best = min([x for x in device_status if x['available'] is True], key=lambda x: x['pending_jobs']) return best['name'] try: # Create a Quantum and Classical Register and giving a name. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') # Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend 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'
def clifford_2_qubit_circuit(self, num): """Return the 2-qubit clifford circuit corresponding to `num` where `num` is between 0 and 11519. """ vals = self._unpack_num_multi_sigs(num, self.CLIFFORD_2_QUBIT_SIGS) qr = QuantumRegister(2) qc = QuantumCircuit(qr) if vals[0] == 0 or vals[0] == 3: (form, i0, i1, j0, j1, p0, p1) = vals else: (form, i0, i1, j0, j1, k0, k1, p0, p1) = vals if i0 == 1: qc.h(0) if i1 == 1: qc.h(1) if j0 == 1: qc.sxdg(0) if j0 == 2: qc.s(0) if j1 == 1: qc.sxdg(1) if j1 == 2: qc.s(1) if form in (1, 2, 3): qc.cx(0, 1) if form in (2, 3): qc.cx(1, 0) if form == 3: qc.cx(0, 1) if form in (1, 2): if k0 == 1: qc._append(VGate(), [qr[0]], []) if k0 == 2: qc._append(WGate(), [qr[0]], []) if k1 == 1: qc._append(VGate(), [qr[1]], []) if k1 == 2: qc._append(VGate(), [qr[1]], []) qc._append(VGate(), [qr[1]], []) if p0 == 1: qc.x(0) if p0 == 2: qc.y(0) if p0 == 3: qc.z(0) if p1 == 1: qc.x(1) if p1 == 2: qc.y(1) if p1 == 3: qc.z(1) return qc