本文整理匯總了Python中qiskit.QuantumCircuit.cx方法的典型用法代碼示例。如果您正苦於以下問題:Python QuantumCircuit.cx方法的具體用法?Python QuantumCircuit.cx怎麽用?Python QuantumCircuit.cx使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類qiskit.QuantumCircuit
的用法示例。
在下文中一共展示了QuantumCircuit.cx方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_two_unitary_simulator
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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)
示例2: setUpClass
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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)
示例3: test_cancel
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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]
示例4: test_run_async
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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]
示例5: test_run_async_simulator
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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))))
示例6: test_run_async_device
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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))))
示例7: test_initialize_middle_circuit
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
def test_initialize_middle_circuit(self):
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.reset(qr[0])
qc.reset(qr[1])
qc.initialize(desired_vector, [qr[0], qr[1]])
qc.measure(qr, cr)
# statevector simulator does not support reset
shots = 2000
threshold = 0.04 * shots
job = wrapper.execute(qc, 'local_qasm_simulator', shots=shots)
result = job.result()
counts = result.get_counts()
target = {'00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4}
self.assertDictAlmostEqual(counts, target, threshold)
示例8: test_entangle
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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])
示例9: test_cancel
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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)
示例10: min
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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'
my_backend = get_backend(my_backend_name)
print("(Local QASM Simulator configuration) ")
示例11: TestStandard2Q
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
#.........這裏部分代碼省略.........
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()
示例12: TestStandard1Q
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
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])
#.........這裏部分代碼省略.........
示例13: CircuitBackend
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
class CircuitBackend(UnrollerBackend):
"""Backend for the unroller that produces a QuantumCircuit.
By default, basis gates are the QX gates.
"""
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 set_basis(self, basis):
"""Declare the set of user-defined gates to emit.
basis is a list of operation name strings.
"""
self.basis = basis
def version(self, version):
"""Ignore the version string.
v is a version number.
"""
pass
def new_qreg(self, name, size):
"""Create a new quantum register.
name = name of the register
sz = size of the register
"""
assert size >= 0, "invalid qreg size"
q_register = QuantumRegister(size, name)
self.circuit.add(q_register)
def new_creg(self, name, size):
"""Create a new classical register.
name = name of the register
sz = size of the register
"""
assert size >= 0, "invalid creg size"
c_register = ClassicalRegister(size, name)
self.circuit.add(c_register)
def define_gate(self, name, gatedata):
"""Define a new quantum gate.
We don't check that the definition and name agree.
name is a string.
gatedata is the AST node for the gate.
"""
self.gates[name] = gatedata
def _map_qubit(self, qubit):
"""Map qubit tuple (regname, index) to (QuantumRegister, index)."""
qregs = self.circuit.get_qregs()
if qubit[0] not in qregs:
raise BackendError("qreg %s does not exist" % qubit[0])
return (qregs[qubit[0]], qubit[1])
def _map_bit(self, bit):
"""Map bit tuple (regname, index) to (ClassicalRegister, index)."""
cregs = self.circuit.get_cregs()
if bit[0] not in cregs:
raise BackendError("creg %s does not exist" % bit[0])
return (cregs[bit[0]], bit[1])
def _map_creg(self, creg):
"""Map creg name to ClassicalRegister."""
cregs = self.circuit.get_cregs()
if creg not in cregs:
raise BackendError("creg %s does not exist" % creg)
return cregs[creg]
def u(self, arg, qubit, nested_scope=None):
"""Fundamental single qubit gate.
arg is 3-tuple of Node expression objects.
qubit is (regname,idx) tuple.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if self.listen:
if "U" not in self.basis:
self.basis.append("U")
#.........這裏部分代碼省略.........
示例14: unmajority
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
def unmajority(p, a, b, c):
"""Unmajority gate."""
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b)
# Build a temporary subcircuit that adds a to b,
# storing the result in b
adder_subcircuit = QuantumCircuit(cin, a, b, cout)
majority(adder_subcircuit, cin[0], b[0], a[0])
for j in range(n - 1):
majority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
adder_subcircuit.cx(a[n - 1], cout[0])
for j in reversed(range(n - 1)):
unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
unmajority(adder_subcircuit, cin[0], b[0], a[0])
# Set the inputs to the adder
qc.x(a[0]) # Set input a = 0...0001
qc.x(b) # Set input b = 1...1111
# Apply the adder
qc += adder_subcircuit
# Measure the output register in the computational basis
for j in range(n):
qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])
###############################################################
示例15: QuantumRegister
# 需要導入模塊: from qiskit import QuantumCircuit [as 別名]
# 或者: from qiskit.QuantumCircuit import cx [as 別名]
key=lambda x: x['pending_jobs'])
return best['name']
try:
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# Add a Measure gate to see the state.
qc.measure(q, c)
# See a list of available local simulators
print("Local backends: ", available_backends({'local': True}))
# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, "local_qasm_simulator")
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))
# see a list of available remote backends