def test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" circ = QuantumCircuit.from_qasm_file(self._get_resource_path('example.qasm', Path.QASMS)) layout = Layout.generate_trivial_layout(*circ.qregs) orig_pass = BarrierBeforeFinalMeasurements() with patch.object(BarrierBeforeFinalMeasurements, 'run', wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout) self.assertTrue(mock_pass.called)
def test_simjob_raises_error_when_sending_bad_qobj(self): """Test SimulatorJob is denied resource request access when given an invalid Qobj instance. """ job_id = str(uuid.uuid4()) backend = FakeRueschlikon() self.bad_qobj.header = QobjHeader(backend_name=backend.name()) with self.assertRaises(SchemaValidationError): job = basicaerjob.BasicAerJob(backend, job_id, _nop, self.bad_qobj) job.submit()
def test_final_measurement_barrier_for_devices(self, mock_pass): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" circ = QuantumCircuit.from_qasm_file( self._get_resource_path('example.qasm', Path.QASMS)) dag_circuit = circuit_to_dag(circ) transpile_dag( dag_circuit, coupling_map=FakeRueschlikon().configuration().coupling_map) self.assertTrue(mock_pass.called)
def test_optimization_level(self): """Test several backends with all optimization levels""" for backend in [FakeTenerife(), FakeMelbourne(), FakeRueschlikon(), FakeTokyo(), FakePoughkeepsie()]: for optimization_level in range(4): result = transpile( [self._circuit], backend=backend, optimization_level=optimization_level ) self.assertIsInstance(result, QuantumCircuit)
def test_empty_dag(self): """ Empty DAG.""" circuit = QuantumCircuit() passmanager = PassManager() passmanager.append(ResourceEstimation()) _ = transpile(circuit, FakeRueschlikon(), pass_manager=passmanager) self.assertEqual(passmanager.property_set['size'], 0) self.assertEqual(passmanager.property_set['depth'], 0) self.assertEqual(passmanager.property_set['width'], 0) self.assertDictEqual(passmanager.property_set['count_ops'], {})
def run_with_api(self, api, job_class=IBMQJobPreQobj): """Creates a new ``IBMQJobPreQobj`` instance running with the provided API object. """ backend = FakeRueschlikon() self._current_api = api self._current_qjob = job_class(backend, None, api, False, qobj=new_fake_qobj()) self._current_qjob.submit() return self._current_qjob
def test_delay_converts_to_dt(self): """Test that a delay instruction is converted to units of dt given a backend.""" qc = QuantumCircuit(2) qc.delay(1000, [0], unit='us') backend = FakeRueschlikon() backend.configuration().dt = 0.5e-6 out = transpile([qc, qc], backend) self.assertEqual(out[0].data[0][0].unit, 'dt') self.assertEqual(out[1].data[0][0].unit, 'dt') out = transpile(qc, dt=1e-9) self.assertEqual(out.data[0][0].unit, 'dt')
def test_parallel_compile(self): """Trigger parallel routines in compile.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10)
class TestTranspileLevels(QiskitTestCase): """Test transpiler on fake backend""" @combine(circuit=[emptycircuit, circuit_2532], level=[0, 1, 2, 3], backend=[FakeTenerife(), FakeMelbourne(), FakeRueschlikon(), FakeTokyo(), FakePoughkeepsie(), None], dsc='Transpiler {circuit.__name__} on {backend} backend at level {level}', name='{circuit.__name__}_{backend}_level{level}') def test(self, circuit, level, backend): """All the levels with all the backends""" result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit)
def test_do_not_run_cxdirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run CXDirection.""" circ = QuantumCircuit.from_qasm_file(self._get_resource_path('example.qasm', Path.QASMS)) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) cxdir_pass = CXDirection(CouplingMap(coupling_map)) with unittest.mock.patch.object(CXDirection, 'run', wraps=cxdir_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called)
def test_layout_1711(self, level): """Test that a user-given initial layout is respected, in the qobj. See: https://github.com/Qiskit/qiskit-terra/issues/1711 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3) ancilla = QuantumRegister(13, 'ancilla') qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) initial_layout = {0: qr[1], 2: qr[0], 15: qr[2]} final_layout = { 0: qr[1], 1: ancilla[0], 2: qr[0], 3: ancilla[1], 4: ancilla[2], 5: ancilla[3], 6: ancilla[4], 7: ancilla[5], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: ancilla[10], 13: ancilla[11], 14: ancilla[12], 15: qr[2] } backend = FakeRueschlikon() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) qobj = assemble(qc_b) self.assertEqual(qc_b._layout._p2v, final_layout) compiled_ops = qobj.experiments[0].instructions for operation in compiled_ops: if operation.name == 'cx': self.assertIn(operation.qubits, backend.configuration().coupling_map) self.assertIn(operation.qubits, [[15, 0], [15, 2]])
def test_wait_for_final_state_timeout(self): """Test timeout waiting for job to reach a final state.""" job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (BasicAerJob, executor): job = BasicAerJob(backend, job_id, lambda: None, FakeQobj()) job.submit() mocked_future = executor.submit.return_value mocked_future.running.return_value = True mocked_future.cancelled.return_value = False mocked_future.done.return_value = False self.assertRaises(JobTimeoutError, job.wait_for_final_state, timeout=0.5)
def test_optimize_h_gates(self): """ Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]-- """ qr = QuantumRegister(1, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.h(qr[0]) expected = QuantumCircuit(qr) expected.u2(0, np.pi, qr[0]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = transpile(circuit, FakeRueschlikon(), pass_manager=passmanager) self.assertEqual(expected, result)
def test_cancel(self): # Again, cancelling jobs is beyond our responsibility. In this test # we only check if we delegate on the proper method of the underlaying # future object. job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (BasicAerJob, executor): job = BasicAerJob(backend, job_id, lambda: None, FakeQobj()) job.submit() job.cancel() self.assertCalledOnce(executor.submit) mocked_future = executor.submit.return_value self.assertCalledOnce(mocked_future.cancel)
def test_cancel(self): # Again, cancelling jobs is beyond our responsibility. In this test # we only check if we delegate on the proper method of the underlaying # future object. job_id = str(uuid.uuid4()) backend = FakeRueschlikon() # pylint: disable=invalid-name,redefined-outer-name with mocked_executor() as (SimulatorsJob, executor): job = SimulatorsJob(backend, job_id, lambda: None, new_fake_qobj()) job.submit() job.cancel() self.assertCalledOnce(executor.submit) mocked_future = executor.submit.return_value self.assertCalledOnce(mocked_future.cancel)
def test_compile_circuits_diff_registers(self): """Compile list of circuits with different qreg names. """ backend = FakeRueschlikon() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) circuits = transpile(circuits, backend) self.assertIsInstance(circuits[0], QuantumCircuit)
def test_move_measurements(self): """Measurements applied AFTER swap mapping. """ backend = FakeRueschlikon() cmap = backend.configuration().coupling_map circ = QuantumCircuit.from_qasm_file( self._get_resource_path('move_measurements.qasm', Path.QASMS)) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap) out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes('measure') for meas_node in meas_nodes: is_last_measure = all([after_measure.type == 'out' for after_measure in out_dag.quantum_successors(meas_node)]) self.assertTrue(is_last_measure)
def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs. """ backend = FakeRueschlikon() qr = QuantumRegister(3, name='qr') qr2 = QuantumRegister(1, name='qr2') qr3 = QuantumRegister(4, name='qr3') cr = ClassicalRegister(3, name='cr') qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit)
def test_callback(self): """Test the callback parameter.""" qr = QuantumRegister(1, 'qr') circuit = QuantumCircuit(qr, name='MyCircuit') circuit.h(qr[0]) circuit.h(qr[0]) circuit.h(qr[0]) expected_start = QuantumCircuit(qr) expected_start.u2(0, np.pi, qr[0]) expected_start.u2(0, np.pi, qr[0]) expected_start.u2(0, np.pi, qr[0]) expected_start_dag = circuit_to_dag(expected_start) expected_end = QuantumCircuit(qr) expected_end.u2(0, np.pi, qr[0]) expected_end_dag = circuit_to_dag(expected_end) calls = [] def callback(**kwargs): out_dict = kwargs out_dict['dag'] = copy.deepcopy(kwargs['dag']) calls.append(out_dict) passmanager = PassManager() passmanager.append(Unroller(['u2'])) passmanager.append(Optimize1qGates()) transpile(circuit, FakeRueschlikon(), pass_manager=passmanager, callback=callback) self.assertEqual(len(calls), 2) self.assertEqual(len(calls[0]), 5) self.assertEqual(calls[0]['count'], 0) self.assertEqual(calls[0]['pass_'].name(), 'Unroller') self.assertEqual(expected_start_dag, calls[0]['dag']) self.assertIsInstance(calls[0]['time'], float) self.assertEqual(calls[0]['property_set'], PropertySet()) self.assertEqual('MyCircuit', calls[0]['dag'].name) self.assertEqual(len(calls[1]), 5) self.assertEqual(calls[1]['count'], 1) self.assertEqual(calls[1]['pass_'].name(), 'Optimize1qGates') self.assertEqual(expected_end_dag, calls[1]['dag']) self.assertIsInstance(calls[0]['time'], float) self.assertEqual(calls[0]['property_set'], PropertySet()) self.assertEqual('MyCircuit', calls[1]['dag'].name)
def test_do_not_run_gatedirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run GateDirection.""" qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'qasm') circ = QuantumCircuit.from_qasm_file( os.path.join(qasm_dir, 'example.qasm')) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) orig_pass = GateDirection(CouplingMap(coupling_map)) with patch.object(GateDirection, 'run', wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called)
def test_move_measurements(self): """Measurements applied AFTER swap mapping. """ backend = FakeRueschlikon() cmap = backend.configuration().coupling_map circ = QuantumCircuit.from_qasm_file( self._get_resource_path('move_measurements.qasm', Path.QASMS)) dag_circuit = circuit_to_dag(circ) lay = Layout({('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(dag_circuit, initial_layout=lay, coupling_map=cmap) meas_nodes = out_dag.named_nodes('measure') for meas_node in meas_nodes: is_last_measure = all([after_measure.type == 'out' for after_measure in out_dag.quantum_successors(meas_node)]) self.assertTrue(is_last_measure)
def test_compile_with_initial_layout(self): """Test compile with an initial layout. Regression test for #1711 """ qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) initial_layout = {0: (qr, 1), 2: (qr, 0), 15: (qr, 2)} backend = FakeRueschlikon() qobj = compile(qc, backend, seed=42, initial_layout=initial_layout) compiled_ops = qobj.experiments[0].instructions for operation in compiled_ops: if operation.name == 'cx': self.assertIn(operation.qubits, backend.configuration().coupling_map) self.assertIn(operation.qubits, [[15, 0], [15, 2]])
def test_move_measurements(self): """Measurements applied AFTER swap mapping. """ backend = FakeRueschlikon() cmap = backend.configuration().coupling_map qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'qasm') circ = QuantumCircuit.from_qasm_file( os.path.join(qasm_dir, 'move_measurements.qasm')) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap) out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes('measure') for meas_node in meas_nodes: is_last_measure = all(after_measure.type == 'out' for after_measure in out_dag.quantum_successors(meas_node)) self.assertTrue(is_last_measure)
def test_9q_circuit_Rueschlikon_sd(self): """9 qubits in Rueschlikon, considering the direction 1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ 0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map) qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap16, pass_.property_set)
def test_5q_circuit_16q_coupling_no_solution(self): """ 5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, 'q') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertIsNone(layout)
def test_5q_circuit_Rueschlikon_no_solution(self): """5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertIsNone(layout) self.assertEqual(pass_.property_set["VF2Layout_stop_reason"], "nonexistent solution")
def test_wait_for_final_state(self): """Test waiting for job to reach a final state.""" def _job_call_back(c_job_id, c_job_status, c_job): """Job status query callback function.""" self.assertEqual(c_job_id, job_id) self.assertEqual(c_job_status, JobStatus.RUNNING) self.assertEqual(c_job, job) mocked_future.running.return_value = False mocked_future.done.return_value = True job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (BasicAerJob, executor): job = BasicAerJob(backend, job_id, lambda: None, FakeQobj()) job.submit() mocked_future = executor.submit.return_value mocked_future.running.return_value = True mocked_future.cancelled.return_value = False mocked_future.done.return_value = False job.wait_for_final_state(callback=_job_call_back)
def run_test(): """Run tests.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) qlist = [qc for k in range(15)] for opt_level in [0, 1, 2, 3]: tqc = transpile(qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242) result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: assert math.isclose(count["0000000000000000"], 500, rel_tol=0.1) assert math.isclose(count["0111111111111111"], 500, rel_tol=0.1)
def test_multiple_execution(self): # Notice that it is Python responsibility to test the executors # can run several tasks at the same time. It is our responsibility to # use the executor correctly. That is what this test checks. taskcount = 10 target_tasks = [lambda: None for _ in range(taskcount)] job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (SimulatorJob, executor): for index in range(taskcount): job = SimulatorJob(backend, job_id, target_tasks[index], FakeQobj()) job.submit() self.assertEqual(executor.submit.call_count, taskcount) for index in range(taskcount): _, callargs, _ = executor.submit.mock_calls[index] submitted_task = callargs[0] target_task = target_tasks[index] self.assertEqual(submitted_task, target_task)
def test_mapping_already_satisfied(self): """Test compiler doesn't change circuit already matching backend coupling """ backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[1]) qc.x(qr[2]) qc.x(qr[3]) qc.x(qr[4]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[3]) qc.cx(qr[3], qr[4]) qc.cx(qr[3], qr[14]) qc.measure(qr, cr) qobj = compile(qc, backend) compiled_ops = qobj.experiments[0].instructions original_cx_qubits = [[1, 2], [2, 3], [3, 4], [3, 14]] for operation in compiled_ops: if operation.name == 'cx': self.assertIn(operation.qubits, backend.configuration().coupling_map) self.assertIn(operation.qubits, original_cx_qubits)