def test_change_circuit_qobj_after_compile_noname(self): q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qr = q_program.get_quantum_register() cr = q_program.get_classical_register() qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc3 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc2.h(qr[0]) qc2.cx(qr[0], qr[1]) qc2.cx(qr[0], qr[2]) qc3.h(qr) qc2.measure(qr, cr) qc3.measure(qr, cr) circuits = [qc2.name, qc3.name] shots = 1024 backend = 'local_qasm_simulator' config = {'seed': 10, 'shots': 1, 'xvals': [1, 2, 3, 4]} qobj1 = q_program.compile(circuits, backend=backend, shots=shots, seed=88, config=config) qobj1['circuits'][0]['config']['shots'] = 50 qobj1['circuits'][0]['config']['xvals'] = [1, 1, 1] config['shots'] = 1000 config['xvals'][0] = 'only for qobj2' qobj2 = q_program.compile(circuits, backend=backend, shots=shots, seed=88, config=config) self.assertTrue(qobj1['circuits'][0]['config']['shots'] == 50) self.assertTrue(qobj1['circuits'][1]['config']['shots'] == 1) self.assertTrue(qobj1['circuits'][0]['config']['xvals'] == [1, 1, 1]) self.assertTrue(qobj1['circuits'][1]['config']['xvals'] == [1, 2, 3, 4]) self.assertTrue(qobj1['config']['shots'] == 1024) self.assertTrue(qobj2['circuits'][0]['config']['shots'] == 1000) self.assertTrue(qobj2['circuits'][1]['config']['shots'] == 1000) self.assertTrue(qobj2['circuits'][0]['config']['xvals'] == [ 'only for qobj2', 2, 3, 4]) self.assertTrue(qobj2['circuits'][1]['config']['xvals'] == [ 'only for qobj2', 2, 3, 4])
def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 3, verbose=False) c = QP_program.create_classical_register("c", 3, verbose=False) qc = QP_program.create_circuit("circuitName", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.cx(q[0], q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. coupling_map = {0: [1], 1: [2]} initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)} circuits = ["circuitName"] qobj = QP_program.compile(circuits, backend=backend, shots=shots, coupling_map=coupling_map, initial_layout=initial_layout, seed=88) result = QP_program.run(qobj) to_check = QP_program.get_qasm("circuitName") self.assertEqual(len(to_check), 160) self.assertEqual(result.get_counts("circuitName"), {'000': 518, '111': 506})
def test_run_program(self): """Test run. If all correct should the data. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc2.cx(qr[0], qr[1]) qc2.cx(qr[0], qr[2]) qc3.h(qr) qc2.measure(qr, cr) qc3.measure(qr, cr) circuits = ['qc2', 'qc3'] shots = 1024 # the number of shots in the experiment. backend = 'local_qasm_simulator' qobj = QP_program.compile(circuits, backend=backend, shots=shots, seed=88) out = QP_program.run(qobj) results2 = out.get_counts('qc2') results3 = out.get_counts('qc3') self.assertEqual(results2, {'000': 518, '111': 506}) self.assertEqual(results3, {'001': 119, '111': 129, '110': 134, '100': 117, '000': 129, '101': 126, '010': 145, '011': 125})
def test_simple_compile(self): """ Compares with and without skip_translation """ name = 'test_simple' qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit(name, [qr], [cr]) qc.u1(3.14, qr[0]) qc.u2(3.14, 1.57, qr[0]) qc.measure(qr, cr) rtrue = qp.compile([name], backend='local_qasm_simulator', shots=1024, skip_translation=True) rfalse = qp.compile([name], backend='local_qasm_simulator', shots=1024, skip_translation=False) self.assertEqual(rtrue['config'], rfalse['config']) self.assertEqual(rtrue['circuits'], rfalse['circuits'])
def test_compile_program_noname(self): """Test compile with a no name. """ q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qc = q_program.get_circuit() qr = q_program.get_quantum_register() cr = q_program.get_classical_register() qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) out = q_program.compile() self.log.info(out) self.assertEqual(len(out), 3)
def test_get_execution_list_noname(self): """Test get_execution_list for circuits without name. """ q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qc = q_program.get_circuit() qr = q_program.get_quantum_register() cr = q_program.get_classical_register() qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qobj = q_program.compile() result = q_program.get_execution_list(qobj, print_func=self.log.info) self.assertEqual(len(result), 1)
def test_teleport(self): """test teleportation as in tutorials""" self.log.info('test_teleport') pi = np.pi shots = 1000 qp = QuantumProgram() qr = qp.create_quantum_register('qr', 3) cr0 = qp.create_classical_register('cr0', 1) cr1 = qp.create_classical_register('cr1', 1) cr2 = qp.create_classical_register('cr2', 1) circuit = qp.create_circuit('teleport', [qr], [cr0, cr1, cr2]) circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.ry(pi/4, qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr0[0]) circuit.measure(qr[1], cr1[0]) circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) backend = 'local_qasm_simulator' qobj = qp.compile('teleport', backend=backend, shots=shots, seed=self.seed) results = qp.run(qobj) data = results.get_counts('teleport') alice = {} bob = {} alice['00'] = data['0 0 0'] + data['1 0 0'] alice['01'] = data['0 1 0'] + data['1 1 0'] alice['10'] = data['0 0 1'] + data['1 0 1'] alice['11'] = data['0 1 1'] + data['1 1 1'] bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1'] bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1'] self.log.info('test_telport: circuit:') self.log.info( circuit.qasm() ) self.log.info('test_teleport: data {0}'.format(data)) self.log.info('test_teleport: alice {0}'.format(alice)) 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 test_compile_program(self): """Test compile_program. If all correct should return COMPLETED. """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'test' coupling_map = None out = QP_program.compile(['circuitName'], backend=backend, coupling_map=coupling_map, qobjid='cooljob') # print(out) self.assertEqual(len(out), 3)
def test_get_execution_list(self): """Test get_execution_list. If all correct should return {'local_qasm_simulator': ['circuitName']}. """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'local_qasm_simulator' coupling_map = None qobj = QP_program.compile(['circuitName'], backend=backend, coupling_map=coupling_map, qobjid="cooljob") result = QP_program.get_execution_list(qobj) # print(result) self.assertEqual(result, ['circuitName'])
def test_get_compiled_qasm(self): """Test get_compiled_qasm. If all correct should return lenght dictionary. """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'local_qasm_simulator' coupling_map = None qobj = QP_program.compile(['circuitName'], backend=backend, coupling_map=coupling_map) result = QP_program.get_compiled_qasm(qobj, 'circuitName',) # print(result) self.assertEqual(len(result), 184)
def test_run_program_map(self): """Test run_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, name="circuit-dev") circuits = ["circuit-dev"] qobj = QP_program.compile(circuits, backend=backend, shots=shots, max_credits=max_credits, seed=65, coupling_map=coupling_map, initial_layout=initial_layout) result = QP_program.run(qobj) self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
class MapperTest(QiskitTestCase): """Test the mapper.""" def setUp(self): self.seed = 42 self.qprogram = 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-terra/issues/81 """ self.qprogram.load_qasm_file( self._get_resource_path('qasm/overoptimization.qasm'), name='test') coupling_map = [[0, 2], [1, 2], [2, 3]] result1 = self.qprogram.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map) count1 = result1.get_counts("test") result2 = self.qprogram.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-terra/issues/111 """ self.qprogram.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.qprogram.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-terra/issues/159 """ self.qprogram = QuantumProgram() qr = self.qprogram.create_quantum_register('qr', 2) cr = self.qprogram.create_classical_register('cr', 2) qc = self.qprogram.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.qprogram.compile(["Bell"], backend=backend, initial_layout=initial_layout, coupling_map=coupling_map) self.assertEqual(self.qprogram.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.qprogram.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.qprogram.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, '11110': 0.002232419390471667, '11111': 0.017684822659235985 } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-terra/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-terra/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-terra/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-terra/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER) def test_already_mapped(self): """Test that if the circuit already matches the backend topology, it is not remapped. See: https://github.com/QISKit/qiskit-terra/issues/342 """ self.qprogram = QuantumProgram() qr = self.qprogram.create_quantum_register('qr', 16) cr = self.qprogram.create_classical_register('cr', 16) qc = self.qprogram.create_circuit('native_cx', [qr], [cr]) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) for j in range(16): qc.measure(qr[j], cr[j]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]] qobj = self.qprogram.compile(["native_cx"], backend=backend, coupling_map=coupling_map) cx_qubits = [ x.qubits for x in qobj.experiments[0].instructions if x.name == "cx" ] self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]) def test_yzy_zyz_cases(self): """Test mapper function yzy_to_zyz works in previously failed cases. See: https://github.com/QISKit/qiskit-terra/issues/607 """ backend = FakeQX4BackEnd() circ1 = load_qasm_string(YZY_ZYZ_1) qobj1 = qiskit.wrapper.compile(circ1, backend) self.assertIsInstance(qobj1, Qobj) circ2 = load_qasm_string(YZY_ZYZ_2) qobj2 = qiskit.wrapper.compile(circ2, backend) self.assertIsInstance(qobj2, Qobj) def test_move_measurements(self): """Measurements applied AFTER swap mapping. """ backend = FakeQX5BackEnd() cmap = backend.configuration['coupling_map'] circ = qiskit.load_qasm_file( self._get_resource_path('qasm/move_measurements.qasm'), name='move') dag_circuit = DAGCircuit.fromQuantumCircuit(circ) lay = { ('qa', 0): ('q', 0), ('qa', 1): ('q', 1), ('qb', 0): ('q', 15), ('qb', 1): ('q', 2), ('qb', 2): ('q', 14), ('qN', 0): ('q', 3), ('qN', 1): ('q', 13), ('qN', 2): ('q', 4), ('qc', 0): ('q', 12), ('qNt', 0): ('q', 5), ('qNt', 1): ('q', 11), ('qt', 0): ('q', 6) } out_dag = transpile(dag_circuit, initial_layout=lay, coupling_map=cmap, format='dag') moved_meas = remove_last_measurements(out_dag, perform_remove=False) meas_nodes = out_dag.get_named_nodes('measure') self.assertEqual(len(moved_meas), len(meas_nodes))
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, '11110': 0.002232419390471667, '11111': 0.017684822659235985 } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER) def test_already_mapped(self): """Test that if the circuit already matches the backend topology, it is not remapped. See: https://github.com/QISKit/qiskit-sdk-py/issues/342 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 16) cr = self.qp.create_classical_register('cr', 16) qc = self.qp.create_circuit('native_cx', [qr], [cr]) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) for j in range(16): qc.measure(qr[j], cr[j]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]] qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map) cx_qubits = [x["qubits"] for x in qobj["circuits"][0]["compiled_circuit"]["operations"] if x["name"] == "cx"] self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
# quantum register for the first circuit q_register1 = program.create_quantum_register('q_register1', 4) c_register1 = program.create_classical_register('c_register1', 4) # quantum register for the second circuit q_register2 = program.create_quantum_register('q_register2', 4) c_register2 = program.create_classical_register('c_register2', 4) # making the first circuits circuit1 = program.create_circuit('GHZ', [q_register1], [c_register1]) circuit2 = program.create_circuit('superpostion', [q_register2], [c_register2]) circuit1.h(q_register1[0]) circuit1.cx(q_register1[0], q_register1[1]) circuit1.cx(q_register1[1], q_register1[2]) circuit1.cx(q_register1[2], q_register1[3]) for i in range(4): circuit1.measure(q_register1[i], c_register1[i]) # making the second circuits circuit2.h(q_register2) for i in range(2): circuit2.measure(q_register2[i], c_register2[i]) # printing the circuits print(program.get_qasm('GHZ')) print(program.get_qasm('superpostion')) object = program.compile(['GHZ','superpostion'], backend='local_qasm_simulator') program.get_execution_list(object, verbose=True) print(program.get_compiled_configuration(object, 'GHZ')) print(program.get_compiled_qasm(object, 'GHZ'))
# Print the QASM code to actually execute # (This QASM code is generated by qiskit) print("\nQASM Code to be executed by the local_qasm_simulator:\n") print(qft3.qasm()) # Simulate the execution of the qft3 circuit simulate = Q_program.execute(["qft3"], backend="local_qasm_simulator", shots=1024) # Print the result of the simulation print("Simulation Result:") print(simulate.get_counts("qft3")) ## Plot a histogram of the results #plot_histogram(simulate.get_counts("qft3")) # Determine QASM code needed for 'real' ibmqx4 machine. # First, get the ibmqx4 coupling map: ibmqx4_backend = Q_program.get_backend_configuration('ibmqx4') ibmqx4_coupling = ibmqx4_backend['coupling_map'] # Second, compile the program with ibmqx4_coupling: qobj=Q_program.compile(["qft3"], backend="local_qasm_simulator", coupling_map=ibmqx4_coupling) # Last, get the new QASM source, and print it: QASM_source = Q_program.get_compiled_qasm(qobj,'qft3') print("\nQASM Code needed for real ibmqx4:\n") print(QASM_source) # How to run on a real ibmqx4 machine. if real_run: run = Q_program.execute(["qft3"], backend="ibmqx4", coupling_map=ibmqx4_coupling, shots=1024, max_credits=3, wait=10, timeout=240) plot_histogram(run.get_counts("qft3"))
circuit.measure(qr[0], cr[3]) # measure gate from the qbit 1 to classical bit 2 circuit.measure(qr[1], cr[2]) # measure gate from the qbit 2 to classical bit 1 circuit.measure(qr[2], cr[1]) # measure gate from the qbit 3 to classical bit 0 circuit.measure(qr[3], cr[0]) source = qp.get_qasm('Circuit') print(source) # ---------------------------------------------- # Output # ---------------------------------------------- device = 'local_qasm_simulator' circuits = ['Circuit'] qp.set_api(Qconfig.APItoken, Qconfig.config['url']) #set the APIToken and API url qobj = qp.compile(circuits, device) result = qp.run(qobj, wait=2, timeout=240) print(result) print(result.get_counts('Circuit'))
circuit.ccx(q_register[0], q_register[1], q_register[2]) # XOR gate from Qbit 0 to the Qbit 3 circuit.cx(q_register[0], q_register[3]) # XOR gate from Qbit 1 to the Qbit 3 circuit.cx(q_register[1], q_register[3]) # measure gate from the Qbit 0 to Classical bit 3 circuit.measure(q_register[0], c_register[3]) # measure gate from the Qbit 1 to Classical bit 2 circuit.measure(q_register[1], c_register[2]) # measure gate from the Qbit 2 to Classical bit 1 circuit.measure(q_register[2], c_register[1]) # measure gate from the Qbit 3 to Classical bit 0 circuit.measure(q_register[3], c_register[0]) source = program.get_qasm('circuit') print(source) backend = 'local_qasm_simulator' circuits = ['circuit'] object = program.compile(circuits, backend) result = program.run(object, wait=2, timeout=240) print(result) print(result.get_counts('circuit'))
# Grover's algorithm is O(sqrt(N)), which is quadratically faster than a classical # unordered search algorithm. For a deeper analysis into Grover's algorithm, please go to # https://people.cs.umass.edu/~strubell/doc/quantum_tutorial.pdf. This article, written by # Emma Strubell, is very informative if you are a beginner to quantum like me! # Now we measure the qubits from the quantum register to the classical register. qCircuit.measure(qRegister[0], cRegister[0]) qCircuit.measure(qRegister[1], cRegister[1]) # Now we have to compile and execute our program. The code below was taken # from the tutorial section of https://github.com/IBM/qiskit-sdk-py. device = 'ibmqx_qasm_simulator' # Backend to execute your program, in this case it is the online simulator circuits = ["qCircuit"] # Group of circuits to execute qProgram.compile(circuits, "local_qasm_simulator") # Compile your program # Run your program in the device and check the execution result every 2 seconds result = qProgram.run(wait=2, timeout=240) print(qProgram.get_counts("qCircuit")) # USE THE BLOCK OF CODE BELOW IF YOU WANT TO RUN ON AN ACTUAL QUANTUM COMPUTER # It's cool running on an actual quantum computer, but keep in mind that # decoherence and other environmental noise causes error. # device = 'ibmqx2' # Backend where you execute your program; in this case, on the Real Quantum Chip online # circuits = ["qCircuit"] # Group of circuits to execute # shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots. # max_credits = 3 # Maximum number of credits to spend on executions.
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]] result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed) self.assertEqual(result1.get_counts("test"), { '0001': 480, '0101': 544 }) 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, '11110': 0.002232419390471667, '11111': 0.017684822659235985 } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.025 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER) def test_already_mapped(self): """Test that if the circuit already matches the backend topology, it is not remapped. See: https://github.com/QISKit/qiskit-sdk-py/issues/342 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 16) cr = self.qp.create_classical_register('cr', 16) qc = self.qp.create_circuit('native_cx', [qr], [cr]) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) for j in range(16): qc.measure(qr[j], cr[j]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]] qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map) cx_qubits = [ x["qubits"] for x in qobj["circuits"][0]["compiled_circuit"]["operations"] if x["name"] == "cx" ] self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
############################################################### try: qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) except: offline = True print("""WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator""") qobjs = [] # Create online (so I/O bound) jobs if we have connetion or local (so CPU bound) # jobs otherwise if offline == False: print("Creating %d online jobs..." % NUM_JOBS) for _ in range(0, NUM_JOBS): qobjs.append(qp.compile(["rippleadd"], backend=online_backend, coupling_map=None, shots=1024)) print("Creating %d local jobs..." % NUM_JOBS) # Create CPU intensive jobs for _ in range(0, NUM_JOBS): qobjs.append(qp.compile(["rippleadd"], backend=local_backend, coupling_map=None, shots=1024)) end = False # This function will be called once all jobs have finished. def print_results_callback(results, error=None): if error != None: print("There was an error executing the circuits!!: Error = {}".format(error)) return for result in results:
############# QASM # QASM from a program QASM_source = qp.get_qasm('Circuit') #print(QASM_source) ################ Compile & run in simulator # Sample stdout #(qiskit) [centos@localhost qiskit]$ python basic-test.py #{'0101': 238, '0110': 225, '0100': 365, '0111': 164, '0010': 8, '0000': 7, '0001': 11, '0011': 6} backend = 'local_qasm_simulator' circuits = ['Circuit'] # Group of circuits to execute qobj = qp.compile(circuits, backend) # Compile your program result = qp.run(qobj, wait=2, timeout=240) ##print(result) print ("Content-type: application/json\n\n") # result.get_counts - dict object print (str(result.get_counts('Circuit')).replace("'", "\"")) ############### Run on real device ## Backend where you execute your program; in this case, on the Real Quantum Chip online #backend = 'ibmqx4' #circuits = ['Circuit'] # Group of circuits to execute #shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots. #max_credits = 3 # Maximum number of credits to spend on executions.
def create_experiment(Q_program: QuantumProgram, inputA: str, inputB: str, name: str, backend: str) -> Tuple[str, str]: # qubit mapping index_a1 = 2 index_a2 = 4 index_b1 = 0 index_b2 = 3 # input build q = Q_program.create_quantum_register("q", 5) ans = Q_program.create_classical_register("ans", 5) qc: QuantumCircuit = Q_program.create_circuit(name, [q], [ans]) a1 = q[index_a1] a2 = q[index_a2] b1 = q[index_b1] b2 = q[index_b2] expected = list("00000") expected_result = (int(a, 2) + int(b, 2)) % 4 expected[index_a1] = str(int(expected_result / 2) % 2) expected[index_a2] = str(int(expected_result / 1) % 2) expected[index_b1] = b[2] expected[index_b2] = b[3] expected = "".join(reversed(expected)) print("Job: %s + %s = %s. Expecting answer: %s" % (a, b, bin(expected_result), expected)) # circuit setup if a[2] == "1": print("a1 setting to 1") qc.x(a1) if a[3] == "1": print("a2 setting to 1") qc.x(a2) if b[2] == "1": print("b1 setting to 1") qc.x(b1) if b[3] == "1": print("b2 setting to 1") qc.x(b2) # circuit algorithm qc.h(a1) qc.crk(2, a1, a2, cnot_back=True) qc.h(a2) qc.crk(1, a2, b2) qc.crk(2, a1, b2) qc.crk(1, a1, b1, cnot_back=True) qc.h(a2) qc.crk(-2, a1, a2, cnot_back=True) qc.h(a1) qc.measure(q, ans) # job parameters processor = "ibmqx4" print("Compile & Run manually for '%s' using backend '%s':" % (processor, backend)) qobj_id = "@%s: %s(%s,%s) -> %s" % ( datetime.now().strftime('%Y-%m-%d %H:%M:%S'), name, a, b, expected) conf = Q_program.get_backend_configuration(processor, list_format=False) qobj = Q_program.compile(name_of_circuits=[name], backend=backend, shots=shots, config=conf, max_credits=3, qobj_id=qobj_id) qasm = Q_program.get_compiled_qasm(qobj, name) measurements = list(filter(lambda r: "measure" in r, qasm.split('\n'))) instructions = list(filter(lambda r: "measure" not in r, qasm.split('\n'))) qasm = "\n".join(["// draper(%s,%s)->%s" % (a, b, expected)] + instructions + measurements) return qasm, expected
qc = qp.create_circuit('Bell', [qr], [cr]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) source = qp.get_qasm('Bell') print(source) #result = qp.execute('Bell') circuits = ['Bell'] qobj = qp.compile(circuits, backend) result = qp.run(qobj, wait=2, timeout=240) #print(result.get_counts('Bell')) pprint(qp.available_backends()) #pprint(qp.get_backend_status('ibmqx2')) pprint(qp.get_backend_configuration('ibmqx5'))
def test_example_multiple_compile(self): """Test a toy example compiling multiple circuits. Pass if the results are correct. """ coupling_map = {0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2]} QPS_SPECS = { "circuits": [{ "name": "ghz", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5} ]}, { "name": "bell", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5 }]} ] } qp = QuantumProgram(specs=QPS_SPECS) ghz = qp.get_circuit("ghz") bell = qp.get_circuit("bell") q = qp.get_quantum_register("q") c = qp.get_classical_register("c") # Create a GHZ state ghz.h(q[0]) for i in range(4): ghz.cx(q[i], q[i+1]) # Insert a barrier before measurement ghz.barrier() # Measure all of the qubits in the standard basis for i in range(5): ghz.measure(q[i], c[i]) # Create a Bell state bell.h(q[0]) bell.cx(q[0], q[1]) bell.barrier() bell.measure(q[0], c[0]) bell.measure(q[1], c[1]) qp.set_api(API_TOKEN, URL) bellobj = qp.compile(["bell"], backend='local_qasm_simulator', shots=2048, seed=10) ghzobj = qp.compile(["ghz"], backend='local_qasm_simulator', shots=2048, coupling_map=coupling_map, seed=10) bellresult = qp.run(bellobj) ghzresult = qp.run(ghzobj) print(bellresult.get_counts("bell")) print(ghzresult.get_counts("ghz")) self.assertEqual(bellresult.get_counts("bell"), {'00000': 1034, '00011': 1014}) self.assertEqual(ghzresult.get_counts("ghz"), {'00000': 1047, '11111': 1001})
qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) except: offline = True print("""WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator""") qobjs = [] # Create online (so I/O bound) jobs if we have connetion or local (so CPU bound) # jobs otherwise if not offline: print("Creating %d online jobs..." % NUM_JOBS) for _ in range(0, NUM_JOBS): qobjs.append( qp.compile(["rippleadd"], backend=online_backend, coupling_map=None, shots=1024)) print("Creating %d local jobs..." % NUM_JOBS) # Create CPU intensive jobs for _ in range(0, NUM_JOBS): qobjs.append( qp.compile(["rippleadd"], backend=local_backend, coupling_map=None, shots=1024)) end = False def print_results_callback(results, error=None):
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], 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], 3: []} result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed) # TODO: the circuit produces different results under different versions # of Python, which defeats the purpose of the "seed" parameter. A proper # fix should be issued - this is a workaround for this particular test. if version_info.minor == 5: # Python 3.5 self.assertEqual(result1.get_counts("test"), { '0001': 507, '0101': 517 }) else: # Python 3.6 and higher self.assertEqual(result1.get_counts("test"), { '0001': 480, '0101': 544 }) 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 = 'ibmqx4' cmap = {1: [0], 2: [0, 1, 4], 3: [2, 4]} qobj = self.qp.compile(["Bell"], backend=backend, coupling_map=cmap) # TODO: Python 3.5 produces an equivalent but different QASM, with the # last lines swapped. This assertion compares the output with the two # expected programs, but proper revision should be done. self.assertIn(self.qp.get_compiled_qasm(qobj, "Bell"), (EXPECTED_QASM_1Q_GATES, EXPECTED_QASM_1Q_GATES_3_5)) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
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]) ############################################################### # Set up the API and execute the program. ############################################################### qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) # First version: not mapped result = qp.execute(["rippleadd"], backend=backend, coupling_map=None, shots=1024) print(result) print(result.get_counts("rippleadd")) # Second version: mapped to 2x8 array coupling graph obj = qp.compile(["rippleadd"], backend=backend, coupling_map=coupling_map, shots=1024) result = qp.run(obj) print(result) print(result.get_ran_qasm("rippleadd")) print(result.get_counts("rippleadd")) # Both versions should give the same distribution
## this algorithm can evaluate the function in one call, which is exponentially faster than a classical approach # classical approach: O(2^(n-1) + 1) # quantum approach: O(1) # we're going to measure the values quantumCircuit.measure(quantumRegister[0], classicalRegister[0]) quantumCircuit.measure(quantumRegister[1], classicalRegister[1]) quantumCircuit.measure(quantumRegister[2], classicalRegister[2]) circuits = ["quantumCircuit"] qp.compile(circuits, "local_qasm_simulator") result = qp.execute("quantumCircuit") print(result.get_counts("qCircuit")) # from qiskit import QuantumProgram # qp = QuantumProgram() # qr = qp.create_quantum_register('qr',2) # cr = qp.create_classical_register('cr',2) # qc = qp.create_circuit('Bell',[qr],[cr]) # qc.h(qr[0]) # qc.cx(qr[0], qr[1])