本文整理汇总了Python中qiskit.QuantumProgram.get_circuit_names方法的典型用法代码示例。如果您正苦于以下问题:Python QuantumProgram.get_circuit_names方法的具体用法?Python QuantumProgram.get_circuit_names怎么用?Python QuantumProgram.get_circuit_names使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qiskit.QuantumProgram
的用法示例。
在下文中一共展示了QuantumProgram.get_circuit_names方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_register_and_circuit_names_nonames
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
def test_get_register_and_circuit_names_nonames(self):
"""Get the names of the circuits and registers after create them without a name
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(size=3)
cr1 = q_program.create_classical_register(size=3)
qr2 = q_program.create_quantum_register(size=3)
cr2 = q_program.create_classical_register(size=3)
q_program.create_circuit(qregisters=[qr1], cregisters=[cr1])
q_program.create_circuit(qregisters=[qr2], cregisters=[cr2])
q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2])
qrn = q_program.get_quantum_register_names()
crn = q_program.get_classical_register_names()
qcn = q_program.get_circuit_names()
self.assertEqual(len(qrn), 2)
self.assertEqual(len(crn), 2)
self.assertEqual(len(qcn), 3)
示例2: test_get_qasms_noname
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
def test_get_qasms_noname(self):
"""Test the get_qasms from a qprogram without names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(size=3)
cr = q_program.create_classical_register(size=3)
qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[1], qr[2])
qc1.measure(qr[0], cr[0])
qc1.measure(qr[1], cr[1])
qc1.measure(qr[2], cr[2])
qc2.h(qr)
qc2.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc2.measure(qr[2], cr[2])
results = dict(zip(q_program.get_circuit_names(), q_program.get_qasms()))
qr_name_len = len(qr.name)
cr_name_len = len(cr.name)
self.assertEqual(len(results[qc1.name]), qr_name_len * 9 + cr_name_len * 4 + 147)
self.assertEqual(len(results[qc2.name]), qr_name_len * 7 + cr_name_len * 4 + 137)
示例3: test_get_register_and_circuit_names
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
def test_get_register_and_circuit_names(self):
"""Get the names of the circuits and registers.
If all is correct we should get the arrays of the names
Previusly:
Libraries:
from qiskit import QuantumProgram
"""
QP_program = QuantumProgram()
qr1 = QP_program.create_quantum_register("qr1", 3, verbose=False)
cr1 = QP_program.create_classical_register("cr1", 3, verbose=False)
qr2 = QP_program.create_quantum_register("qr2", 3, verbose=False)
cr2 = QP_program.create_classical_register("cr2", 3, verbose=False)
QP_program.create_circuit("qc1", [qr1], [cr1])
QP_program.create_circuit("qc2", [qr2], [cr2])
QP_program.create_circuit("qc2", [qr1, qr2], [cr1, cr2])
qrn = QP_program.get_quantum_register_names()
crn = QP_program.get_classical_register_names()
qcn = QP_program.get_circuit_names()
self.assertEqual(qrn, {'qr1', 'qr2'})
self.assertEqual(crn, {'cr1', 'cr2'})
self.assertEqual(qcn, {'qc1', 'qc2'})
示例4: LocalQasmSimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
#.........这里部分代码省略.........
self.log.info('test_teleport: bob {0}'.format(bob))
alice_ratio = 1/np.tan(pi/8)**2
bob_ratio = bob['0']/float(bob['1'])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info('test_teleport: relative error = {0:.4f}'.format(error))
self.assertLess(error, 0.05)
def profile_qasm_simulator(self):
"""Profile randomly generated circuits.
Writes profile results to <this_module>.prof as well as recording
to the log file.
number of circuits = 100.
number of operations/circuit in [1, 40]
number of qubits in [1, 5]
"""
seed = 88
shots = 1024
nCircuits = 100
minDepth = 1
maxDepth = 40
minQubits = 1
maxQubits = 5
pr = cProfile.Profile()
randomCircuits = RandomQasmGenerator(seed,
minQubits=minQubits,
maxQubits=maxQubits,
minDepth=minDepth,
maxDepth=maxDepth)
randomCircuits.add_circuits(nCircuits)
self.qp = randomCircuits.getProgram()
pr.enable()
self.qp.execute(self.qp.get_circuit_names(),
backend='local_qasm_simulator',
shots=shots)
pr.disable()
sout = io.StringIO()
ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
self.log.info('------- start profiling QasmSimulator -----------')
ps.print_stats()
self.log.info(sout.getvalue())
self.log.info('------- stop profiling QasmSimulator -----------')
sout.close()
pr.dump_stats(self.moduleName + '.prof')
def profile_nqubit_speed_grow_depth(self):
"""simulation time vs the number of qubits
where the circuit depth is 10x the number of simulated
qubits. Also creates a pdf file with this module name showing a
plot of the results. Compilation is not included in speed.
"""
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
qubitRangeMax = 15
nQubitList = range(1,qubitRangeMax + 1)
nCircuits = 10
shots = 1024
seed = 88
maxTime = 30 # seconds; timing stops when simulation time exceeds this number
fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
backendList = ['local_qasm_simulator', 'local_unitary_simulator']
if shutil.which('qasm_simulator'):
示例5: LocalUnitarySimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
class LocalUnitarySimulatorTest(unittest.TestCase):
"""Test local unitary simulator."""
def setUp(self):
self.seed = 88
self.qasmFileName = os.path.join(qiskit.__path__[0],
'../test/python/qasm/example.qasm')
self.qp = QuantumProgram()
self.moduleName = os.path.splitext(__file__)[0]
self.modulePath = os.path.dirname(__file__)
logFileName = self.moduleName + '.log'
logging.basicConfig(filename=logFileName, level=logging.INFO)
def tearDown(self):
pass
def test_unitary_simulator(self):
"""test generation of circuit unitary"""
shots = 1024
self.qp.load_qasm_file(self.qasmFileName, name='example')
basis_gates = [] # unroll to base gates
unroller = unroll.Unroller(
qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
unroll.JsonBackend(basis_gates))
circuit = unroller.execute()
# if we want to manipulate the circuit, we have to convert it to a dict
circuit = json.loads(circuit.decode())
#strip measurements from circuit to avoid warnings
circuit['operations'] = [op for op in circuit['operations']
if op['name'] != 'measure']
# the simulator is expecting a JSON format, so we need to convert it back to JSON
job = {'compiled_circuit': json.dumps(circuit).encode()}
# numpy savetxt is currently prints complex numbers in a way
# loadtxt can't read. To save file do,
# fmtstr=['% .4g%+.4gj' for i in range(numCols)]
# np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
expected = np.loadtxt(os.path.join(self.modulePath,
'example_unitary_matrix.dat'),
dtype='complex', delimiter=',')
result = UnitarySimulator(job).run()
self.assertTrue(np.allclose(result['data']['unitary'], expected,
rtol=1e-3))
def profile_unitary_simulator(self):
"""Profile randomly generated circuits.
Writes profile results to <this_module>.prof as well as recording
to the log file.
number of circuits = 100.
number of operations/circuit in [1, 40]
number of qubits in [1, 5]
"""
nCircuits = 100
maxDepth = 40
maxQubits = 5
pr = cProfile.Profile()
randomCircuits = RandomQasmGenerator(seed=self.seed,
maxDepth=maxDepth,
maxQubits=maxQubits)
randomCircuits.add_circuits(nCircuits, doMeasure=False)
self.qp = randomCircuits.getProgram()
pr.enable()
self.qp.execute(self.qp.get_circuit_names(),
backend='local_unitary_simulator')
pr.disable()
sout = io.StringIO()
ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
logging.info('------- start profiling UnitarySimulator -----------')
ps.print_stats()
logging.info(sout.getvalue())
logging.info('------- stop profiling UnitarySimulator -----------')
sout.close()
pr.dump_stats(self.moduleName + '.prof')
示例6: TestLocalQasmSimulatorPy
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
#.........这里部分代码省略.........
alice_ratio = 1/np.tan(pi/8)**2
bob_ratio = bob['0']/float(bob['1'])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info('test_teleport: relative error = %s', error)
self.assertLess(error, 0.05)
@unittest.skipIf(not do_profiling, "skipping simulator profiling.")
def profile_qasm_simulator(self):
"""Profile randomly generated circuits.
Writes profile results to <this_module>.prof as well as recording
to the log file.
number of circuits = 100.
number of operations/circuit in [1, 40]
number of qubits in [1, 5]
"""
seed = 88
shots = 1024
n_circuits = 100
min_depth = 1
max_depth = 40
min_qubits = 1
max_qubits = 5
pr = cProfile.Profile()
random_circuits = RandomQasmGenerator(seed,
min_qubits=min_qubits,
max_qubits=max_qubits,
min_depth=min_depth,
max_depth=max_depth)
random_circuits.add_circuits(n_circuits)
self.qp = random_circuits.get_program()
pr.enable()
self.qp.execute(self.qp.get_circuit_names(),
backend='local_qasm_simulator_py',
shots=shots)
pr.disable()
sout = io.StringIO()
ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
self.log.info('------- start profiling QasmSimulatorPy -----------')
ps.print_stats()
self.log.info(sout.getvalue())
self.log.info('------- stop profiling QasmSimulatorPy -----------')
sout.close()
pr.dump_stats(self.moduleName + '.prof')
@unittest.skipIf(not do_profiling, "skipping simulator profiling.")
def profile_nqubit_speed_grow_depth(self):
"""simulation time vs the number of qubits
where the circuit depth is 10x the number of simulated
qubits. Also creates a pdf file with this module name showing a
plot of the results. Compilation is not included in speed.
"""
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
qubit_range_max = 15
n_qubit_list = range(1, qubit_range_max + 1)
n_circuits = 10
shots = 1024
seed = 88
max_time = 30 # seconds; timing stops when simulation time exceeds this number
fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \
'shots={shots}'
示例7: LocalUnitarySimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import get_circuit_names [as 别名]
#.........这里部分代码省略.........
# strip measurements from circuit to avoid warnings
circuit['operations'] = [op for op in circuit['operations']
if op['name'] != 'measure']
# the simulator is expecting a JSON format, so we need to convert it
# back to JSON
qobj = {
'id': 'unitary',
'config': {
'max_credits': None,
'shots': 1,
'backend_name': 'local_unitary_simulator_py'
},
'circuits': [
{
'name': 'test',
'compiled_circuit': circuit,
'compiled_circuit_qasm': self.qp.get_qasm('example'),
'config': {
'coupling_map': None,
'basis_gates': None,
'layout': None,
'seed': None
}
}
]
}
# numpy.savetxt currently prints complex numbers in a way
# loadtxt can't read. To save file do,
# fmtstr=['% .4g%+.4gj' for i in range(numCols)]
# np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
# delimiter=',')
expected = np.loadtxt(self._get_resource_path('example_unitary_matrix.dat'),
dtype='complex', delimiter=',')
q_job = QuantumJob(qobj,
backend=UnitarySimulatorPy(),
preformatted=True)
result = UnitarySimulatorPy().run(q_job).result()
self.assertTrue(np.allclose(result.get_unitary('test'),
expected,
rtol=1e-3))
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 profile_unitary_simulator(self):
"""Profile randomly generated circuits.
Writes profile results to <this_module>.prof as well as recording
to the log file.
number of circuits = 100.
number of operations/circuit in [1, 40]
number of qubits in [1, 5]
"""
n_circuits = 100
max_depth = 40
max_qubits = 5
pr = cProfile.Profile()
random_circuits = RandomQasmGenerator(seed=self.seed,
max_depth=max_depth,
max_qubits=max_qubits)
random_circuits.add_circuits(n_circuits, do_measure=False)
self.qp = random_circuits.get_program()
pr.enable()
self.qp.execute(self.qp.get_circuit_names(),
backend=UnitarySimulatorPy())
pr.disable()
sout = io.StringIO()
ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
self.log.info('------- start profiling UnitarySimulatorPy -----------')
ps.print_stats()
self.log.info(sout.getvalue())
self.log.info('------- stop profiling UnitarySimulatorPy -----------')
sout.close()
pr.dump_stats(self.moduleName + '.prof')