本文整理汇总了Python中qiskit.QuantumCircuit.measure方法的典型用法代码示例。如果您正苦于以下问题:Python QuantumCircuit.measure方法的具体用法?Python QuantumCircuit.measure怎么用?Python QuantumCircuit.measure使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qiskit.QuantumCircuit
的用法示例。
在下文中一共展示了QuantumCircuit.measure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: trial_circuit_computational
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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
示例2: qc_approx_sim
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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;
示例3: setUp
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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]
示例4: setUpClass
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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)
示例5: test_cancel
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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]
示例6: test_gate_x
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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})
示例7: test_run_async
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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]
示例8: setUp
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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)
示例9: test_run_async_simulator
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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))))
示例10: test_run_async_device
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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))))
示例11: test_initialize_middle_circuit
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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)
示例12: setUp
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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)
示例13: trial_circuit_ryrz
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
def trial_circuit_ryrz(n, m, theta, entangler_map, meas_string=None,
measurement=True):
"""Creates a QuantumCircuit object ocnsisting in layers of
parametrized single-qubit Y and Z rotations and CZ two-qubit gates
Args:
n (int) : number of qubits
m (int) : depth of the circuit
theta array[float] : angles that parametrize the Y and Z rotations
entangler_map : CZ connectivity, e.g. {0: [1], 1: [2]}
meas_string (str) : measure a given Pauli operator at the end of the
circuit
measurement (bool) : whether to measure the qubit (register "q")
on classical bits (register "c")
Returns:
A QuantumCircuit object
"""
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
示例14: test_entangle
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [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])
示例15: trial_circuit_ryrz
# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import measure [as 别名]
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