def test_failed_reduced_map(self): """Generate a bad disconnected reduced map""" fake = FakeRueschlikon() cmap = fake.configuration().coupling_map coupling_map = CouplingMap(cmap) with self.assertRaises(CouplingError): coupling_map.reduce([12, 11, 10, 3])
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 = 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 = 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_already_mapped_1(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() coupling_map = backend.configuration().coupling_map basis_gates = backend.configuration().basis_gates qr = QuantumRegister(16, 'qr') cr = ClassicalRegister(16, 'cr') qc = QuantumCircuit(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]) qc.measure(qr, cr) new_qc = transpile(qc, coupling_map=coupling_map, basis_gates=basis_gates) cx_qubits = [qargs for (gate, qargs, _) in new_qc.data if gate.name == "cx"] cx_qubits_physical = [[ctrl[1], tgt[1]] for [ctrl, tgt] in cx_qubits] self.assertEqual(sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
def test_initial_layout_1(self): """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) 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() for optimization_level in range(4): qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=optimization_level) qobj = assemble(qc_b) 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_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_successful_reduced_map(self): """Generate a reduced map""" fake = FakeRueschlikon() cmap = fake.configuration().coupling_map coupling_map = CouplingMap(cmap) out = coupling_map.reduce([12, 11, 10, 9]).get_edges() ans = [(1, 2), (3, 2), (0, 1)] self.assertEqual(set(out), set(ans))
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_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_9q_circuit_16q_coupling(self): """ 9 qubits in Rueschlikon, without considering the direction q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8 | | | | | | | | q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9 """ cmap16 = 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_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set['layout'] self.assertEqual(layout[qr0[0]], 2) self.assertEqual(layout[qr0[1]], 1) self.assertEqual(layout[qr0[2]], 0) self.assertEqual(layout[qr0[3]], 4) self.assertEqual(layout[qr1[0]], 5) self.assertEqual(layout[qr1[1]], 6) self.assertEqual(layout[qr1[2]], 7) self.assertEqual(layout[qr1[3]], 3) self.assertEqual(layout[qr1[4]], 15) self.assertEqual(pass_.property_set['CSPLayout_stop_reason'], 'solution found')
def test_9q_circuit_16q_coupling_sd(self): """9 qubits in Rueschlikon, considering the direction q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = 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_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 10) self.assertEqual(layout[qr1[4]], 8) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_9q_circuit_Rueschlikon(self): """9 qubits in Rueschlikon, without considering the direction 1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ 0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9 1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1 | | | | | | | | q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2 """ 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=False, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap16, pass_.property_set)
def run_with_api(self, api): """Creates a new ``IBMQJob`` running with the provided API object.""" backend = FakeRueschlikon() self._current_api = api self._current_qjob = IBMQJob(backend, None, api, qobj=new_fake_qobj()) self._current_qjob.submit() return self._current_qjob
def test_already_mapped(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() qr = QuantumRegister(16, 'qr') cr = ClassicalRegister(16, 'cr') qc = QuantumCircuit(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]) qobj = compile(qc, backend=backend) 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_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_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_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)) layout = Layout.generate_trivial_layout(*circ.qregs) transpile(circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout) self.assertTrue(mock_pass.called)
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_optimization_level(self): """Test several backends with all optimization levels""" for backend in [FakeTenerife(), FakeMelbourne(), FakeRueschlikon(), FakeTokyo()]: for optimization_level in range(4): result = transpile( [self._circuit], backend=backend, optimization_level=optimization_level ) self.assertIsInstance(result, QuantumCircuit)
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_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 test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" 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) 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 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 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_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_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)
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_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_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)