本文整理汇总了Python中qiskit.QuantumProgram.load_qasm_file方法的典型用法代码示例。如果您正苦于以下问题:Python QuantumProgram.load_qasm_file方法的具体用法?Python QuantumProgram.load_qasm_file怎么用?Python QuantumProgram.load_qasm_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qiskit.QuantumProgram
的用法示例。
在下文中一共展示了QuantumProgram.load_qasm_file方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_json_output
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
def test_json_output(self):
qp = QuantumProgram()
qp.load_qasm_file(self.QASM_FILE_PATH, name="example")
basis_gates = [] # unroll to base gates, change to test
unroller = unroll.Unroller(qasm.Qasm(data=qp.get_qasm("example")).parse(),
unroll.JsonBackend(basis_gates))
circuit = unroller.execute()
self.log.info('test_json_ouptut: %s', circuit)
示例2: StatevectorSimulatorSympyTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class StatevectorSimulatorSympyTest(QiskitTestCase):
"""Test local statevector simulator."""
def setUp(self):
self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
self.qp = QuantumProgram()
self.qp.load_qasm_file(self.qasm_filename, 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()
circuit_config = {'coupling_map': None,
'basis_gates': 'u1,u2,u3,cx,id',
'layout': None}
resources = {'max_credits': 3}
self.qobj = {'id': 'test_sim_single_shot',
'config': {
'max_credits': resources['max_credits'],
'shots': 1024,
'backend_name': 'local_statevector_simulator_sympy',
},
'circuits': [
{
'name': 'test',
'compiled_circuit': circuit,
'compiled_circuit_qasm': None,
'config': circuit_config
}
]}
self.q_job = QuantumJob(self.qobj,
backend=StatevectorSimulatorSympy(),
circuit_config=circuit_config,
resources=resources,
preformatted=True)
def test_statevector_simulator_sympy(self):
"""Test data counts output for single circuit run against reference."""
result = StatevectorSimulatorSympy().run(self.q_job).result()
actual = result.get_data('test')['statevector']
self.assertEqual(result.get_status(), 'COMPLETED')
self.assertEqual(actual[0], sqrt(2)/2)
self.assertEqual(actual[1], 0)
self.assertEqual(actual[2], 0)
self.assertEqual(actual[3], sqrt(2)/2)
示例3: test_execute_program_map
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
def test_execute_program_map(self):
"""Test execute_program_map.
If all correct should return 10010.
"""
QP_program = QuantumProgram()
QP_program.set_api(API_TOKEN, URL)
backend = 'local_qasm_simulator' # the backend to run on
shots = 100 # the number of shots in the experiment.
max_credits = 3
coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
("q", 2): ("q", 2), ("q", 3): ("q", 3),
("q", 4): ("q", 4)}
QP_program.load_qasm_file(QASM_FILE_PATH_2, "circuit-dev")
circuits = ["circuit-dev"]
result = QP_program.execute(circuits, backend=backend, shots=shots,
max_credits=max_credits,
coupling_map=coupling_map,
initial_layout=initial_layout, seed=5455)
self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
示例4: test_load_qasm_file
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
def test_load_qasm_file(self):
"""Test load_qasm_file and get_circuit.
If all is correct we should get the qasm file loaded in QASM_FILE_PATH
Previusly:
Libraries:
from qiskit import QuantumProgram
"""
QP_program = QuantumProgram()
name = QP_program.load_qasm_file(QASM_FILE_PATH, name="",
verbose=False)
result = QP_program.get_circuit(name)
to_check = result.qasm()
# print(to_check)
self.assertEqual(len(to_check), 554)
示例5: use_sympy_backends
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
def use_sympy_backends():
qprogram = QuantumProgram()
current_dir = os.path.dirname(os.path.realpath(__file__))
qasm_file = current_dir + "/../qasm/simple.qasm"
qasm_circuit = qprogram.load_qasm_file(qasm_file)
print("analyzing: " + qasm_file)
print(qprogram.get_qasm(qasm_circuit))
# sympy statevector simulator
backend = 'local_statevector_simulator_sympy'
result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
print("final quantum amplitude vector: ")
print(result.get_data(qasm_circuit)['statevector'])
# sympy unitary simulator
backend = 'local_unitary_simulator_sympy'
result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
print("\nunitary matrix of the circuit: ")
print(result.get_data(qasm_circuit)['unitary'])
示例6: LocalQasmSimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class LocalQasmSimulatorTest(unittest.TestCase):
"""Test local qasm simulator."""
@classmethod
def setUpClass(cls):
cls.moduleName = os.path.splitext(__file__)[0]
cls.pdf = PdfPages(cls.moduleName + '.pdf')
cls.log = logging.getLogger(__name__)
cls.log.setLevel(logging.INFO)
logFileName = cls.moduleName + '.log'
handler = logging.FileHandler(logFileName)
handler.setLevel(logging.INFO)
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(cls.__name__))
formatter = logging.Formatter(log_fmt)
handler.setFormatter(formatter)
cls.log.addHandler(handler)
@classmethod
def tearDownClass(cls):
cls.pdf.close()
def setUp(self):
self.seed = 88
self.qasmFileName = os.path.join(qiskit.__path__[0],
'../test/python/qasm/example.qasm')
self.qp = QuantumProgram()
def tearDown(self):
pass
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
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()
config = {'shots': shots, 'seed': self.seed}
job = {'compiled_circuit': circuit, 'config': config}
result = QasmSimulator(job).run()
self.assertEqual(result['status'], 'DONE')
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
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()
config = {'shots': shots, 'seed': self.seed}
job = {'compiled_circuit': circuit, 'config': config}
result = QasmSimulator(job).run()
expected = {'100 100': 137, '011 011': 131, '101 101': 117, '111 111': 127,
'000 000': 131, '010 010': 141, '110 110': 116, '001 001': 124}
self.assertEqual(result['data']['counts'], expected)
def test_if_statement(self):
self.log.info('test_if_statement_x')
shots = 100
max_qubits = 3
qp = QuantumProgram()
qr = qp.create_quantum_register('qr', max_qubits)
cr = qp.create_classical_register('cr', max_qubits)
circuit = qp.create_circuit('test_if', [qr], [cr])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.x(qr[2]).c_if(cr, 0x3)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
circuit2.x(qr[0])
circuit2.measure(qr[0], cr[0])
circuit2.measure(qr[1], cr[1])
circuit2.x(qr[2]).c_if(cr, 0x3)
circuit2.measure(qr[0], cr[0])
circuit2.measure(qr[1], cr[1])
circuit2.measure(qr[2], cr[2])
basis_gates = [] # unroll to base gates
unroller = unroll.Unroller(
qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
unroll.JsonBackend(basis_gates))
ucircuit = unroller.execute()
unroller = unroll.Unroller(
qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
unroll.JsonBackend(basis_gates))
ucircuit2 = unroller.execute()
config = {'shots': shots, 'seed': self.seed}
job = {'compiled_circuit': ucircuit, 'config': config}
result_if_true = QasmSimulator(job).run()
job = {'compiled_circuit': ucircuit2, 'config': config}
result_if_false = QasmSimulator(job).run()
#.........这里部分代码省略.........
示例7: LocalSimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class LocalSimulatorTest(unittest.TestCase):
"""
Test interface to local simulators.
"""
@classmethod
def setUpClass(cls):
cls.moduleName = os.path.splitext(__file__)[0]
cls.log = logging.getLogger(__name__)
cls.log.setLevel(logging.INFO)
logFileName = cls.moduleName + '.log'
handler = logging.FileHandler(logFileName)
handler.setLevel(logging.INFO)
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(cls.__name__))
formatter = logging.Formatter(log_fmt)
handler.setFormatter(formatter)
cls.log.addHandler(handler)
@classmethod
def tearDownClass(cls):
#cls.pdf.close()
pass
def setUp(self):
self.seed = 88
self.qasmFileName = os.path.join(qiskit.__path__[0],
'../test/python/qasm/example.qasm')
self.qp = QuantumProgram()
shots = 1
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()
self.job = {'compiled_circuit': circuit,
'config': {'shots': shots, 'seed': random.randint(0, 10)}
}
def tearDown(self):
pass
def test_local_configuration_present(self):
self.assertTrue(_localsimulator.local_configuration)
def test_local_configurations(self):
required_keys = ['name',
'url',
'simulator',
'description',
'coupling_map',
'basis_gates']
for conf in _localsimulator.local_configuration:
for key in required_keys:
self.assertIn(key, conf.keys())
def test_simulator_classes(self):
cdict = _localsimulator._simulator_classes
cdict = getattr(_localsimulator, '_simulator_classes')
self.log.info('found local simulators: {0}'.format(repr(cdict)))
self.assertTrue(cdict)
def test_local_backends(self):
backends = _localsimulator.local_backends()
self.log.info('found local backends: {0}'.format(repr(backends)))
self.assertTrue(backends)
def test_instantiation(self):
"""
Test instantiation of LocalSimulator
"""
backend_list = _localsimulator.local_backends()
for backend_name in backend_list:
backend = _localsimulator.LocalSimulator(backend_name, self.job)
示例8: LocalUnitarySimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [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')
示例9: TestLocalQasmSimulatorPy
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class TestLocalQasmSimulatorPy(QiskitTestCase):
"""Test local_qasm_simulator_py."""
@classmethod
def setUpClass(cls):
super().setUpClass()
if do_profiling:
cls.pdf = PdfPages(cls.moduleName + '.pdf')
@classmethod
def tearDownClass(cls):
if do_profiling:
cls.pdf.close()
def setUp(self):
self.seed = 88
self.qasm_filename = self._get_resource_path('qasm/example.qasm')
self.qp = QuantumProgram()
self.qp.load_qasm_file(self.qasm_filename, 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()
circuit_config = {'coupling_map': None,
'basis_gates': 'u1,u2,u3,cx,id',
'layout': None,
'seed': self.seed}
resources = {'max_credits': 3}
self.qobj = {'id': 'test_sim_single_shot',
'config': {
'max_credits': resources['max_credits'],
'shots': 1024,
'backend_name': 'local_qasm_simulator_py',
},
'circuits': [
{
'name': 'test',
'compiled_circuit': circuit,
'compiled_circuit_qasm': None,
'config': circuit_config
}
]}
self.q_job = QuantumJob(self.qobj,
backend=QasmSimulatorPy(),
circuit_config=circuit_config,
seed=self.seed,
resources=resources,
preformatted=True)
def tearDown(self):
pass
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
self.qobj['config']['shots'] = shots
result = QasmSimulatorPy().run(self.q_job).result()
self.assertEqual(result.get_status(), 'COMPLETED')
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
result = QasmSimulatorPy().run(self.q_job).result()
shots = 1024
threshold = 0.04 * shots
counts = result.get_counts('test')
target = {'100 100': shots / 8, '011 011': shots / 8,
'101 101': shots / 8, '111 111': shots / 8,
'000 000': shots / 8, '010 010': shots / 8,
'110 110': shots / 8, '001 001': shots / 8}
self.assertDictAlmostEqual(counts, target, threshold)
def test_if_statement(self):
self.log.info('test_if_statement_x')
shots = 100
max_qubits = 3
qp = QuantumProgram()
qr = qp.create_quantum_register('qr', max_qubits)
cr = qp.create_classical_register('cr', max_qubits)
circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
circuit_if_true.x(qr[0])
circuit_if_true.x(qr[1])
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.x(qr[2]).c_if(cr, 0x3)
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.measure(qr[2], cr[2])
circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
circuit_if_false.x(qr[0])
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.x(qr[2]).c_if(cr, 0x3)
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.measure(qr[2], cr[2])
basis_gates = [] # unroll to base gates
unroller = unroll.Unroller(
qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
unroll.JsonBackend(basis_gates))
#.........这里部分代码省略.........
示例10: UnitarySimulatorSympyTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class UnitarySimulatorSympyTest(QiskitTestCase):
"""Test local unitary simulator sympy."""
def setUp(self):
self.seed = 88
self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
self.qp = QuantumProgram()
def test_unitary_simulator(self):
"""test generation of circuit unitary"""
self.qp.load_qasm_file(self.qasm_filename, 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()
# 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_sympy_unitary_simulator'
},
'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
}
}
]
}
q_job = QuantumJob(qobj,
backend=UnitarySimulatorSympy(),
preformatted=True)
result = UnitarySimulatorSympy().run(q_job).result()
actual = result.get_data('test')['unitary']
self.assertEqual(actual[0][0], sqrt(2)/2)
self.assertEqual(actual[0][1], sqrt(2)/2)
self.assertEqual(actual[0][2], 0)
self.assertEqual(actual[0][3], 0)
self.assertEqual(actual[1][0], 0)
self.assertEqual(actual[1][1], 0)
self.assertEqual(actual[1][2], sqrt(2)/2)
self.assertEqual(actual[1][3], -sqrt(2)/2)
self.assertEqual(actual[2][0], 0)
self.assertEqual(actual[2][1], 0)
self.assertEqual(actual[2][2], sqrt(2)/2)
self.assertEqual(actual[2][3], sqrt(2)/2)
self.assertEqual(actual[3][0], sqrt(2)/2)
self.assertEqual(actual[3][1], -sqrt(2)/2)
self.assertEqual(actual[3][2], 0)
self.assertEqual(actual[3][3], 0)
示例11: LocalUnitarySimulatorTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class LocalUnitarySimulatorTest(QiskitTestCase):
"""Test local unitary simulator."""
def setUp(self):
self.seed = 88
self.qasm_filename = self._get_resource_path('qasm/example.qasm')
self.qp = QuantumProgram()
def tearDown(self):
pass
def test_unitary_simulator(self):
"""test generation of circuit unitary"""
self.qp.load_qasm_file(self.qasm_filename, 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()
# 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
#.........这里部分代码省略.........
示例12: MapperTest
# 需要导入模块: from qiskit import QuantumProgram [as 别名]
# 或者: from qiskit.QuantumProgram import load_qasm_file [as 别名]
class MapperTest(QiskitTestCase):
"""Test the mapper."""
def setUp(self):
self.seed = 42
self.qp = QuantumProgram()
def test_mapper_overoptimization(self):
"""
The mapper should not change the semantics of the input. An overoptimization introduced
the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81
"""
self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test')
coupling_map = [[0, 2], [1, 2], [2, 3]]
result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
coupling_map=coupling_map)
count1 = result1.get_counts("test")
result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None)
count2 = result2.get_counts("test")
self.assertEqual(count1.keys(), count2.keys(), )
def test_math_domain_error(self):
"""
The math library operates over floats and introduce floating point errors that should be
avoided.
See: https://github.com/QISKit/qiskit-sdk-py/issues/111
"""
self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test')
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 2000
result = self.qp.execute("test", backend="local_qasm_simulator",
coupling_map=coupling_map,
seed=self.seed, shots=shots)
counts = result.get_counts("test")
target = {'0001': shots / 2, '0101': shots / 2}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_optimize_1q_gates_issue159(self):
"""Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.
See: https://github.com/QISKit/qiskit-sdk-py/issues/159
"""
self.qp = QuantumProgram()
qr = self.qp.create_quantum_register('qr', 2)
cr = self.qp.create_classical_register('cr', 2)
qc = self.qp.create_circuit('Bell', [qr], [cr])
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.cx(qr[1], qr[0])
qc.cx(qr[1], qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]]
initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)}
qobj = self.qp.compile(["Bell"], backend=backend,
initial_layout=initial_layout, coupling_map=coupling_map)
self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5)
def test_random_parameter_circuit(self):
"""Run a circuit with randomly generated parameters."""
self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
shots = 1024
result1 = self.qp.execute(["rand"], backend="local_qasm_simulator",
coupling_map=coupling_map, shots=shots, seed=self.seed)
counts = result1.get_counts("rand")
expected_probs = {
'00000': 0.079239867254200971,
'00001': 0.032859032998526903,
'00010': 0.10752610993531816,
'00011': 0.018818532050952699,
'00100': 0.054830807251011054,
'00101': 0.0034141983951965164,
'00110': 0.041649309748902276,
'00111': 0.039967731207338125,
'01000': 0.10516937819949743,
'01001': 0.026635620063700002,
'01010': 0.0053475143548793866,
'01011': 0.01940513314416064,
'01100': 0.0044028405481225047,
'01101': 0.057524760052126644,
'01110': 0.010795354134597078,
'01111': 0.026491296821535528,
'10000': 0.094827455395274859,
'10001': 0.0008373965072688836,
'10010': 0.029082297894094441,
'10011': 0.012386622870598416,
'10100': 0.018739140061148799,
'10101': 0.01367656456536896,
'10110': 0.039184170706009248,
'10111': 0.062339335178438288,
'11000': 0.00293674365989009,
'11001': 0.012848433960739968,
'11010': 0.018472497159499782,
'11011': 0.0088903691234912003,
'11100': 0.031305389080034329,
'11101': 0.0004788556283690458,
#.........这里部分代码省略.........