def setUp(self): super().setUp() self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_ourense') self.properties = self.backend.properties() self.ref_gate = next(g for g in self.backend.configuration().basis_gates if g not in ['id', 'rz'])
def setUp(self): super().setUp() self.provider = FakeProvider() self.backend = self.provider.get_backend("fake_ourense") self.properties = self.backend.properties() self.ref_gate = next(g for g in self.backend.configuration().basis_gates if g not in ["id", "rz"])
class TestGateMap(QiskitVisualizationTestCase): """visual tests for plot_gate_map""" backends = list( filter( lambda x: not x.configuration().simulator and x.configuration(). num_qubits in range(5, 21), FakeProvider().backends(), )) @data(*backends) @unittest.skipIf(not HAS_MATPLOTLIB, "matplotlib not available.") def test_plot_gate_map(self, backend): """tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference( str(n) + "bit_quantum_computer.png") fig = plot_gate_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) @data(*backends) @unittest.skipIf(not HAS_MATPLOTLIB, "matplotlib not available.") def test_plot_circuit_layout(self, backend): """tests plot_circuit_layout for each device""" layout_length = int(backend._configuration.n_qubits / 2) qr = QuantumRegister(layout_length, "qr") circuit = QuantumCircuit(qr) circuit._layout = Layout({qr[i]: i * 2 for i in range(layout_length)}) circuit._layout.add_register(qr) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference( str(n) + "_plot_circuit_layout.png") fig = plot_circuit_layout(circuit, backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1) plt.close(fig) @unittest.skipIf(not HAS_MATPLOTLIB, "matplotlib not available.") def test_plot_gate_map_no_backend(self): """tests plotting of gate map without a device""" n_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png") fig = plot_coupling_map(num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig)
class TestGateMap(QiskitVisualizationTestCase): """ visual tests for plot_gate_map """ backends = list(filter(lambda x: not (x.configuration().simulator or x.configuration().n_qubits == 2), FakeProvider().backends())) @data(*backends) @unittest.skipIf(not HAS_MATPLOTLIB, 'matplotlib not available.') def test_plot_gate_map(self, backend): """ tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png") filename = "temp.png" fig = plot_gate_map(backend) fig.savefig(filename) self.assertImagesAreEqual(filename, img_ref, 0.2) os.remove(filename) @data(*backends) @unittest.skipIf(not HAS_MATPLOTLIB, 'matplotlib not available.') def test_plot_circuit_layout(self, backend): """ tests plot_circuit_layout for each device""" layout_length = int(backend._configuration.n_qubits / 2) qr = QuantumRegister(layout_length, 'qr') circuit = QuantumCircuit(qr) circuit._layout = Layout({qr[i]: i * 2 for i in range(layout_length)}) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png") filename = str(n) + "_plot_circuit_layout_result.png" fig = plot_circuit_layout(circuit, backend) fig.savefig(filename) self.assertImagesAreEqual(filename, img_ref, 0.1) os.remove(filename)
class TestBackendConfiguration(QiskitTestCase): """Test the methods on the BackendConfiguration class.""" @classmethod def setUpClass(cls): # TODO: these two class methods can be removed when the warnings # in backend config are removed. warnings.filterwarnings("ignore") @classmethod def tearDownClass(cls): warnings.resetwarnings() def setUp(self): self.provider = FakeProvider() self.config = self.provider.get_backend( 'fake_openpulse_2q').configuration() def test_simple_config(self): """Test the most basic getters.""" self.assertEqual(self.config.dt, 1.3333 * 1.e-9) self.assertEqual(self.config.dtm, 10.5 * 1.e-9) self.assertEqual(self.config.basis_gates, ['u1', 'u2', 'u3', 'cx', 'id']) def test_sample_rate(self): """Test that sample rate is 1/dt.""" self.assertEqual(self.config.sample_rate, 1. / self.config.dt) def test_hamiltonian(self): """Test the hamiltonian method.""" self.assertEqual( self.config.hamiltonian['description'], "A hamiltonian for a mocked 2Q device, with 1Q and 2Q terms.") # 3Q doesn't offer a hamiltonian -- test that we get a reasonable response backend_3q = self.provider.get_backend('fake_openpulse_3q') self.assertEqual(backend_3q.configuration().hamiltonian, None) def test_get_channels(self): """Test requesting channels from the system.""" self.assertEqual(self.config.drive(0), DriveChannel(0)) self.assertEqual(self.config.measure(1), MeasureChannel(1)) self.assertEqual(self.config.acquire(0), AcquireChannel(0)) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if the system doesn't have that many qubits self.assertEqual(self.config.acquire(10), AcquireChannel(10)) self.assertEqual(self.config.control(0), ControlChannel(0))
class TestBackendConfiguration(QiskitTestCase): """Test the methods on the BackendConfiguration class.""" def setUp(self): self.provider = FakeProvider() self.config = self.provider.get_backend( 'fake_openpulse_2q').configuration() def test_simple_config(self): """Test the most basic getters.""" self.assertEqual(self.config.dt, 1.3333 * 1.e-9) self.assertEqual(self.config.dtm, 10.5 * 1.e-9) self.assertEqual(self.config.basis_gates, ['u1', 'u2', 'u3', 'cx', 'id']) def test_sample_rate(self): """Test that sample rate is 1/dt.""" self.assertEqual(self.config.sample_rate, 1. / self.config.dt) def test_hamiltonian(self): """Test the hamiltonian method.""" self.assertEqual( self.config.hamiltonian['description'], "A hamiltonian for a mocked 2Q device, with 1Q and 2Q terms.") # 3Q doesn't offer a hamiltonian -- test that we get a reasonable response backend_3q = self.provider.get_backend('fake_openpulse_3q') self.assertEqual(backend_3q.configuration().hamiltonian, None) def test_get_channels(self): """Test requesting channels from the system.""" self.assertEqual(self.config.drive(0), DriveChannel(0)) self.assertEqual(self.config.measure(1), MeasureChannel(1)) self.assertEqual(self.config.acquire(0), AcquireChannel(0)) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if the system doesn't have that many qubits self.assertEqual(self.config.acquire(10), AcquireChannel(10)) self.assertEqual(self.config.control(0), ControlChannel(0)) def test_get_rep_times(self): """Test whether rep time property is the right size""" _rep_times_us = [100, 250, 500, 1000] _rep_times_s = [_rt * 1.e-6 for _rt in _rep_times_us] for i, time in enumerate(_rep_times_s): self.assertAlmostEqual(self.config.rep_times[i], time) for i, time in enumerate(_rep_times_us): self.assertEqual(round(self.config.rep_times[i] * 1e6), time)
def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_openpulse_2q') self.config = self.backend.configuration()
class TestCmdDef(QiskitTestCase): """Test CmdDef methods.""" def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_openpulse_2q') self.config = self.backend.configuration() def test_get_backend(self): """Test that backend is fetchable with cmd def present.""" def test_init(self): """Test `init`, `has`.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.config.drive(0))) cmd_def = CmdDef({('tmp', 0): sched}) self.assertTrue(cmd_def.has('tmp', 0)) def test_add(self): """Test `add`, `has`, `get`, `cmdss`.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.config.drive(0))) cmd_def = CmdDef() cmd_def.add('tmp', 1, sched) cmd_def.add('tmp', 0, sched) self.assertEqual(sched.instructions, cmd_def.get('tmp', (0, )).instructions) self.assertIn('tmp', cmd_def.cmds()) self.assertEqual(cmd_def.cmd_qubits('tmp'), [(0, ), (1, )]) def test_pop(self): """Test pop with default.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.config.drive(0))) cmd_def = CmdDef() cmd_def.add('tmp', 0, sched) cmd_def.pop('tmp', 0) self.assertFalse(cmd_def.has('tmp', 0)) with self.assertRaises(PulseError): cmd_def.pop('not_there', (0, )) def test_repr(self): """Test repr.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.config.drive(0))) cmd_def = CmdDef({('tmp', 0): sched}) repr(cmd_def) def test_parameterized_schedule(self): """Test building parameterized schedule.""" cmd_def = CmdDef() converter = QobjToInstructionConverter([]) qobj = PulseQobjInstruction(name='pv', ch='u1', t0=10, val='P2*cos(np.pi*P1)') converted_instruction = converter(qobj) cmd_def.add('pv_test', 0, converted_instruction) self.assertEqual(cmd_def.get_parameters('pv_test', 0), ('P1', 'P2')) sched = cmd_def.get('pv_test', 0, 0, P2=-1) self.assertEqual(sched.instructions[0][-1].command.value, -1) with self.assertRaises(PulseError): cmd_def.get('pv_test', 0, 0, P1=-1) with self.assertRaises(PulseError): cmd_def.get('pv_test', 0, P1=1, P2=2, P3=3) sched = cmd_def.pop('pv_test', 0, 0, P2=-1) self.assertEqual(sched.instructions[0][-1].command.value, -1) self.assertFalse(cmd_def.has('pv_test', 0)) def test_sequenced_parameterized_schedule(self): """Test parametrized schedule consist of multiple instruction. """ cmd_def = CmdDef() converter = QobjToInstructionConverter([]) qobjs = [ PulseQobjInstruction(name='fc', ch='d0', t0=10, phase='P1'), PulseQobjInstruction(name='fc', ch='d0', t0=20, phase='P2'), PulseQobjInstruction(name='fc', ch='d0', t0=30, phase='P3') ] converted_instruction = [converter(qobj) for qobj in qobjs] cmd_def.add( 'inst_seq', 0, ParameterizedSchedule(*converted_instruction, name='inst_seq')) with self.assertRaises(PulseError): cmd_def.get('inst_seq', 0, P1=1, P2=2, P3=3, P4=4, P5=5) with self.assertRaises(PulseError): cmd_def.get('inst_seq', 0, P1=1) with self.assertRaises(PulseError): cmd_def.get('inst_seq', 0, 1, 2, 3, P1=1) sched = cmd_def.get('inst_seq', 0, 1, 2, 3) self.assertEqual(sched.instructions[0][-1].command.phase, 1) self.assertEqual(sched.instructions[1][-1].command.phase, 2) self.assertEqual(sched.instructions[2][-1].command.phase, 3) sched = cmd_def.get('inst_seq', 0, P1=1, P2=2, P3=3) self.assertEqual(sched.instructions[0][-1].command.phase, 1) self.assertEqual(sched.instructions[1][-1].command.phase, 2) self.assertEqual(sched.instructions[2][-1].command.phase, 3) sched = cmd_def.get('inst_seq', 0, 1, 2, P3=3) self.assertEqual(sched.instructions[0][-1].command.phase, 1) self.assertEqual(sched.instructions[1][-1].command.phase, 2) self.assertEqual(sched.instructions[2][-1].command.phase, 3) def test_negative_phases(self): """Test bind parameters with negative values.""" cmd_def = CmdDef() converter = QobjToInstructionConverter([]) qobjs = [ PulseQobjInstruction(name='fc', ch='d0', t0=10, phase='P1'), PulseQobjInstruction(name='fc', ch='d0', t0=20, phase='-(P2)') ] converted_instruction = [converter(qobj) for qobj in qobjs] cmd_def.add( 'inst_seq', 0, ParameterizedSchedule(*converted_instruction, name='inst_seq')) sched = cmd_def.get('inst_seq', 0, -1, 2) self.assertEqual(sched.instructions[0][-1].command.phase, -1) self.assertEqual(sched.instructions[1][-1].command.phase, -2) def test_build_cmd_def(self): """Test building of parameterized cmd_def from defaults.""" defaults = self.backend.defaults() cmd_def = defaults.build_cmd_def() cx_pv = cmd_def.get('ParametrizedGate', (0, 1), P2=0) pv_found = False for _, instr in cx_pv.instructions: cmd = instr.command if isinstance(cmd, PersistentValue): self.assertEqual(cmd.value, 1) pv_found = True self.assertTrue(pv_found) self.assertEqual(cmd_def.get_parameters('u1', 0), ('P1', )) u1_minus_pi = cmd_def.get('u1', 0, P1=1) fc_cmd = u1_minus_pi.instructions[0][-1].command self.assertEqual(fc_cmd.phase, -np.pi)
def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_openpulse_2q') self.device = PulseChannelSpec.from_backend(self.backend)
import operator from test import combine from ddt import ddt, data from qiskit.circuit import QuantumCircuit from qiskit.compiler import assemble from qiskit.compiler import transpile from qiskit.exceptions import QiskitError from qiskit.execute_function import execute from qiskit.test.base import QiskitTestCase from qiskit.test.mock import FakeProvider, FakeLegacyProvider from qiskit.utils import optionals FAKE_PROVIDER = FakeProvider() FAKE_LEGACY_PROVIDER = FakeLegacyProvider() @ddt class TestFakeBackends(QiskitTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.circuit = QuantumCircuit(2) cls.circuit.h(0) cls.circuit.h(1) cls.circuit.h(0) cls.circuit.h(1) cls.circuit.x(0) cls.circuit.x(1)
class BackendpropertiesTestCase(QiskitTestCase): """Test usability methods of backend.properties().""" backend = FakeOurense() backend_name = 'fake_ourense' def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_ourense') self.properties = self.backend.properties() def test_gate_property(self): """Test for getting the gate properties.""" self.assertEqual(self.properties.gate_property('cx', (0, 1), 'gate_error'), self.properties._gates['cx'][(0, 1)]['gate_error']) self.assertEqual(self.properties.gate_property('cx'), self.properties._gates['cx']) with self.assertRaises(BackendPropertyError): self.properties.gate_property('u1', None, 'gate_error') def test_gate_error(self): """Test for getting the gate errors.""" self.assertEqual(self.properties.gate_error('u1', 1), self.properties._gates['u1'][(1,)]['gate_error'][0]) self.assertEqual(self.properties.gate_error('u1', [2, ]), self.properties._gates['u1'][(2,)]['gate_error'][0]) self.assertEqual(self.properties.gate_error('cx', [0, 1]), self.properties._gates['cx'][(0, 1)]['gate_error'][0]) with self.assertRaises(BackendPropertyError): self.properties.gate_error('cx', 0) def test_gate_length(self): """Test for getting the gate duration.""" self.assertEqual(self.properties.gate_length('u1', 1), self.properties._gates['u1'][(1,)]['gate_length'][0]) self.assertEqual(self.properties.gate_length('cx', [4, 3]), self.properties._gates['cx'][(4, 3)]['gate_length'][0]) def test_qubit_property(self): """Test for getting the qubit properties.""" self.assertEqual(self.properties.qubit_property(0, 'T1'), self.properties._qubits[0]['T1']) self.assertEqual(self.properties.qubit_property(0, 'frequency'), self.properties._qubits[0]['frequency']) self.assertEqual(self.properties.qubit_property(0), self.properties._qubits[0]) with self.assertRaises(BackendPropertyError): self.properties.qubit_property('T1') def test_t1(self): """Test for getting the t1 of given qubit.""" self.assertEqual(self.properties.t1(0), self.properties._qubits[0]['T1'][0]) def test_t2(self): """Test for getting the t2 of a given qubit""" self.assertEqual(self.properties.t2(0), self.properties._qubits[0]['T2'][0]) def test_frequency(self): """Test for getting the frequency of given qubit.""" self.assertEqual(self.properties.frequency(0), self.properties._qubits[0]['frequency'][0]) def test_readout_error(self): """Test for getting the readout error of given qubit.""" self.assertEqual(self.properties.readout_error(0), self.properties._qubits[0]['readout_error'][0]) def test_apply_prefix(self): """Testing unit conversions.""" self.assertEqual(self.properties._apply_prefix(71.9500421005539, 'µs'), 7.19500421005539e-05) self.assertEqual(self.properties._apply_prefix(71.9500421005539, 'ms'), 0.0719500421005539) with self.assertRaises(BackendPropertyError): self.properties._apply_prefix(71.9500421005539, 'ws') def test_operational(self): """Test operation status of a given qubit.""" self.assertTrue(self.properties.is_qubit_operational(0))
class TestBackendV2(QiskitAlgorithmsTestCase): """test BackendV2 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = FakeBackendSimple() self.seed = 50 def test_shor_factoring(self): """shor factoring test""" n_v = 15 factors = [3, 5] qasm_simulator = QuantumInstance( self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed ) shor = Shor(quantum_instance=qasm_simulator) result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) self.assertTrue(result.total_counts >= result.successful_counts) def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") qasm_simulator = QuantumInstance( self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed ) vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_yorktown") backend._configuration.max_experiments = 1 qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"])
def setUp(self): super().setUp() self.provider = FakeProvider() self.config = self.provider.get_backend( "fake_openpulse_2q").configuration()
class TestBackendConfiguration(QiskitTestCase): """Test the methods on the BackendConfiguration class.""" def setUp(self): super().setUp() self.provider = FakeProvider() self.config = self.provider.get_backend( "fake_openpulse_2q").configuration() def test_simple_config(self): """Test the most basic getters.""" self.assertEqual(self.config.dt, 1.3333 * 1.0e-9) self.assertEqual(self.config.dtm, 10.5 * 1.0e-9) self.assertEqual(self.config.basis_gates, ["u1", "u2", "u3", "cx", "id"]) def test_simple_config_qasm(self): """Test the most basic getters for qasm.""" qasm_conf = self.provider.get_backend( "fake_qasm_simulator").configuration() self.assertEqual(qasm_conf.dt, 1.3333 * 1.0e-9) self.assertEqual(qasm_conf.dtm, 10.5 * 1.0e-9) self.assertEqual(qasm_conf.qubit_lo_range, [[4.95e9, 5.05e9] for _ in range(5)]) self.assertEqual(qasm_conf.meas_lo_range, [[6.65e9, 6.75e9] for _ in range(5)]) def test_sample_rate(self): """Test that sample rate is 1/dt.""" self.assertEqual(self.config.sample_rate, 1.0 / self.config.dt) def test_hamiltonian(self): """Test the hamiltonian method.""" self.assertEqual( self.config.hamiltonian["description"], "A hamiltonian for a mocked 2Q device, with 1Q and 2Q terms.", ) ref_vars = { "v0": 5.0 * 1e9, "v1": 5.1 * 1e9, "j": 0.01 * 1e9, "r": 0.02 * 1e9, "alpha0": -0.33 * 1e9, "alpha1": -0.33 * 1e9, } self.assertEqual(self.config.hamiltonian["vars"], ref_vars) # Test that on serialization inverse conversion is done. self.assertEqual( self.config.to_dict()["hamiltonian"]["vars"], {k: var * 1e-9 for k, var in ref_vars.items()}, ) # 3Q doesn't offer a hamiltonian -- test that we get a reasonable response backend_3q = self.provider.get_backend("fake_openpulse_3q") self.assertEqual(backend_3q.configuration().hamiltonian, None) def test_get_channels(self): """Test requesting channels from the system.""" self.assertEqual(self.config.drive(0), DriveChannel(0)) self.assertEqual(self.config.measure(1), MeasureChannel(1)) self.assertEqual(self.config.acquire(0), AcquireChannel(0)) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if the system doesn't have that many qubits self.assertEqual(self.config.acquire(10), AcquireChannel(10)) self.assertEqual(self.config.control(qubits=[0, 1]), [ControlChannel(0)]) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._qubit_channel_map self.config.control(qubits=(10, 1)) def test_get_channel_qubits(self): """Test to get all qubits operated on a given channel.""" self.assertEqual( self.config.get_channel_qubits(channel=DriveChannel(0)), [0]) self.assertEqual( self.config.get_channel_qubits(channel=ControlChannel(0)), [0, 1]) backend_3q = self.provider.get_backend("fake_openpulse_3q") self.assertEqual( backend_3q.configuration().get_channel_qubits(ControlChannel(2)), [2, 1]) self.assertEqual( backend_3q.configuration().get_channel_qubits(ControlChannel(1)), [1, 0]) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._channel_qubit_map self.config.get_channel_qubits(MeasureChannel(10)) def test_get_qubit_channels(self): """Test to get all channels operated on a given qubit.""" self.assertTrue( self._test_lists_equal( actual=self.config.get_qubit_channels(qubit=(1, )), expected=[ DriveChannel(1), MeasureChannel(1), AcquireChannel(1) ], )) self.assertTrue( self._test_lists_equal( actual=self.config.get_qubit_channels(qubit=1), expected=[ ControlChannel(0), ControlChannel(1), AcquireChannel(1), DriveChannel(1), MeasureChannel(1), ], )) backend_3q = self.provider.get_backend("fake_openpulse_3q") self.assertTrue( self._test_lists_equal( actual=backend_3q.configuration().get_qubit_channels(1), expected=[ MeasureChannel(1), ControlChannel(0), ControlChannel(2), AcquireChannel(1), DriveChannel(1), ControlChannel(1), ], )) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._channel_qubit_map self.config.get_qubit_channels(10) def test_supported_instructions(self): """Test that supported instructions get entered into config dict properly.""" # verify the supported instructions is not in the config dict when the flag is not set self.assertNotIn("supported_instructions", self.config.to_dict()) # verify that supported instructions get added to config dict when set supp_instrs = ["u1", "u2", "play", "acquire"] setattr(self.config, "supported_instructions", supp_instrs) self.assertEqual(supp_instrs, self.config.to_dict()["supported_instructions"]) def test_get_rep_times(self): """Test whether rep time property is the right size""" _rep_times_us = [100, 250, 500, 1000] _rep_times_s = [_rt * 1.0e-6 for _rt in _rep_times_us] for i, time in enumerate(_rep_times_s): self.assertAlmostEqual(self.config.rep_times[i], time) for i, time in enumerate(_rep_times_us): self.assertEqual(round(self.config.rep_times[i] * 1e6), time) for rep_time in self.config.to_dict()["rep_times"]: self.assertGreater(rep_time, 0) def test_get_default_rep_delay_and_range(self): """Test whether rep delay property is the right size.""" _rep_delay_range_us = [100, 1000] _rep_delay_range_s = [_rd * 1.0e-6 for _rd in _rep_delay_range_us] _default_rep_delay_us = 500 _default_rep_delay_s = 500 * 1.0e-6 setattr(self.config, "rep_delay_range", _rep_delay_range_s) setattr(self.config, "default_rep_delay", _default_rep_delay_s) config_dict = self.config.to_dict() for i, rd in enumerate(config_dict["rep_delay_range"]): self.assertAlmostEqual(rd, _rep_delay_range_us[i], delta=1e-8) self.assertEqual(config_dict["default_rep_delay"], _default_rep_delay_us) def test_get_channel_prefix_index(self): """Test private method to get channel and index.""" self.assertEqual(self.config._get_channel_prefix_index("acquire0"), ("acquire", 0)) with self.assertRaises(BackendConfigurationError): self.config._get_channel_prefix_index("acquire") def _test_lists_equal(self, actual, expected): """Test if 2 lists are equal. It returns ``True`` is lists are equal.""" return collections.Counter(actual) == collections.Counter(expected) def test_deepcopy(self): """Ensure that a deepcopy succeeds and results in an identical object.""" copy_config = copy.deepcopy(self.config) self.assertEqual(copy_config, self.config) def test_u_channel_lo_scale(self): """Ensure that u_channel_lo scale is a complex number""" valencia_conf = self.provider.get_backend( "fake_valencia").configuration() self.assertTrue( isinstance(valencia_conf.u_channel_lo[0][0].scale, complex)) def test_processor_type(self): """Test the "processor_type" field in the backend configuration.""" reference_processor_type = { "family": "Canary", "revision": "1.0", "segment": "A", } self.assertEqual(self.config.processor_type, reference_processor_type) self.assertEqual(self.config.to_dict()["processor_type"], reference_processor_type)
class TestBackendV1(QiskitAlgorithmsTestCase): """test BackendV1 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = self._provider.get_backend("fake_qasm_simulator") self.seed = 50 def test_shor_factoring(self): """shor factoring test""" n_v = 15 factors = [3, 5] qasm_simulator = QuantumInstance(self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed) shor = Shor(quantum_instance=qasm_simulator) result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) self.assertTrue(result.total_counts >= result.successful_counts) def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" h2_op = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X)) optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") qasm_simulator = QuantumInstance(self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed) vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) qi = QuantumInstance(self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32) grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_yorktown") backend._configuration.max_experiments = 1 qi = QuantumInstance(self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32) grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_measurement_error_mitigation_with_vqe(self): """measurement error mitigation test with vqe""" try: from qiskit.ignis.mitigation.measurement import CompleteMeasFitter from qiskit.providers.aer import noise except ImportError as ex: self.skipTest( f"Package doesn't appear to be installed. Error: '{str(ex)}'") return algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) backend = self._qasm quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, ) h2_hamiltonian = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X)) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = self._provider.get_backend("fake_qasm_simulator") self.seed = 50
def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = FakeBackendSimple() self.seed = 50
def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_ourense') self.properties = self.backend.properties()
class TestBackendConfiguration(QiskitTestCase): """Test the methods on the BackendConfiguration class.""" def setUp(self): self.provider = FakeProvider() self.config = self.provider.get_backend( 'fake_openpulse_2q').configuration() def test_simple_config(self): """Test the most basic getters.""" self.assertEqual(self.config.dt, 1.3333 * 1.e-9) self.assertEqual(self.config.dtm, 10.5 * 1.e-9) self.assertEqual(self.config.basis_gates, ['u1', 'u2', 'u3', 'cx', 'id']) def test_sample_rate(self): """Test that sample rate is 1/dt.""" self.assertEqual(self.config.sample_rate, 1. / self.config.dt) def test_hamiltonian(self): """Test the hamiltonian method.""" self.assertEqual( self.config.hamiltonian['description'], "A hamiltonian for a mocked 2Q device, with 1Q and 2Q terms.") # 3Q doesn't offer a hamiltonian -- test that we get a reasonable response backend_3q = self.provider.get_backend('fake_openpulse_3q') self.assertEqual(backend_3q.configuration().hamiltonian, None) def test_get_channels(self): """Test requesting channels from the system.""" self.assertEqual(self.config.drive(0), DriveChannel(0)) self.assertEqual(self.config.measure(1), MeasureChannel(1)) self.assertEqual(self.config.acquire(0), AcquireChannel(0)) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if the system doesn't have that many qubits self.assertEqual(self.config.acquire(10), AcquireChannel(10)) self.assertEqual(self.config.control(qubits=[0, 1]), [ControlChannel(0)]) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._qubit_channel_map self.config.control(qubits=(10, 1)) def test_get_channel_qubits(self): """Test to get all qubits operated on a given channel.""" self.assertEqual( self.config.get_channel_qubits(channel=DriveChannel(0)), [0]) self.assertEqual( self.config.get_channel_qubits(channel=ControlChannel(0)), [0, 1]) backend_3q = self.provider.get_backend('fake_openpulse_3q') self.assertEqual( backend_3q.configuration().get_channel_qubits(ControlChannel(2)), [2, 1]) self.assertEqual( backend_3q.configuration().get_channel_qubits(ControlChannel(1)), [1, 0]) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._channel_qubit_map self.config.get_channel_qubits(MeasureChannel(10)) def test_get_qubit_channels(self): """Test to get all channels operated on a given qubit.""" self.assertTrue( self._test_lists_equal( actual=self.config.get_qubit_channels(qubit=(1, )), expected=[ DriveChannel(1), MeasureChannel(1), AcquireChannel(1) ])) self.assertTrue( self._test_lists_equal( actual=self.config.get_qubit_channels(qubit=1), expected=[ ControlChannel(0), ControlChannel(1), AcquireChannel(1), DriveChannel(1), MeasureChannel(1) ])) backend_3q = self.provider.get_backend('fake_openpulse_3q') self.assertTrue( self._test_lists_equal( actual=backend_3q.configuration().get_qubit_channels(1), expected=[ MeasureChannel(1), ControlChannel(0), ControlChannel(2), AcquireChannel(1), DriveChannel(1), ControlChannel(1) ])) with self.assertRaises(BackendConfigurationError): # Check that an error is raised if key not found in self._channel_qubit_map self.config.get_qubit_channels(10) def test_get_rep_times(self): """Test whether rep time property is the right size""" _rep_times_us = [100, 250, 500, 1000] _rep_times_s = [_rt * 1.e-6 for _rt in _rep_times_us] for i, time in enumerate(_rep_times_s): self.assertAlmostEqual(self.config.rep_times[i], time) for i, time in enumerate(_rep_times_us): self.assertEqual(round(self.config.rep_times[i] * 1e6), time) for rep_time in self.config.to_dict()['rep_times']: self.assertGreater(rep_time, 0) def test_get_default_rep_delay_and_range(self): """Test whether rep time property is the right size""" _rep_delay_range_us = [100, 1000] _rep_delay_range_s = [_rd * 1.e-6 for _rd in _rep_delay_range_us] _default_rep_delay_us = 500 _default_rep_delay_s = 500 * 1.e-6 setattr(self.config, 'rep_delay_range', _rep_delay_range_s) setattr(self.config, 'default_rep_delay', _default_rep_delay_s) config_dict = self.config.to_dict() for i, rd in enumerate(config_dict['rep_delay_range']): self.assertAlmostEqual(rd, _rep_delay_range_us[i], delta=1e-8) self.assertEqual(config_dict['default_rep_delay'], _default_rep_delay_us) def test_get_channel_prefix_index(self): """Test private method to get channel and index.""" self.assertEqual(self.config._get_channel_prefix_index('acquire0'), ('acquire', 0)) with self.assertRaises(BackendConfigurationError): self.config._get_channel_prefix_index("acquire") def _test_lists_equal(self, actual, expected): """Test if 2 lists are equal. It returns ``True`` is lists are equal.""" return collections.Counter(actual) == collections.Counter(expected) def test_deepcopy(self): """Ensure that a deepcopy succeeds and results in an identical object.""" copy_config = copy.deepcopy(self.config) print(copy_config.to_dict()) print("Original:") print(self.config.to_dict()) self.assertEqual(copy_config, self.config)
class BackendpropertiesTestCase(QiskitTestCase): """Test usability methods of backend.properties().""" backend = FakeOurense() backend_name = "fake_ourense" def setUp(self): super().setUp() self.provider = FakeProvider() self.backend = self.provider.get_backend("fake_ourense") self.properties = self.backend.properties() self.ref_gate = next(g for g in self.backend.configuration().basis_gates if g not in ["id", "rz"]) def test_gate_property(self): """Test for getting the gate properties.""" self.assertEqual( self.properties.gate_property("cx", (0, 1), "gate_error"), self.properties._gates["cx"][(0, 1)]["gate_error"], ) self.assertEqual(self.properties.gate_property("cx"), self.properties._gates["cx"]) with self.assertRaises(BackendPropertyError): self.properties.gate_property(self.ref_gate, None, "gate_error") def test_gate_error(self): """Test for getting the gate errors.""" self.assertEqual( self.properties.gate_error(self.ref_gate, 1), self.properties._gates[self.ref_gate][(1, )]["gate_error"][0], ) self.assertEqual( self.properties.gate_error( self.ref_gate, [ 2, ], ), self.properties._gates[self.ref_gate][(2, )]["gate_error"][0], ) self.assertEqual( self.properties.gate_error("cx", [0, 1]), self.properties._gates["cx"][(0, 1)]["gate_error"][0], ) with self.assertRaises(BackendPropertyError): self.properties.gate_error("cx", 0) def test_gate_length(self): """Test for getting the gate duration.""" self.assertEqual( self.properties.gate_length(self.ref_gate, 1), self.properties._gates[self.ref_gate][(1, )]["gate_length"][0], ) self.assertEqual( self.properties.gate_length("cx", [4, 3]), self.properties._gates["cx"][(4, 3)]["gate_length"][0], ) def test_qubit_property(self): """Test for getting the qubit properties.""" self.assertEqual(self.properties.qubit_property(0, "T1"), self.properties._qubits[0]["T1"]) self.assertEqual(self.properties.qubit_property(0, "frequency"), self.properties._qubits[0]["frequency"]) self.assertEqual(self.properties.qubit_property(0), self.properties._qubits[0]) with self.assertRaises(BackendPropertyError): self.properties.qubit_property("T1") def test_t1(self): """Test for getting the t1 of given qubit.""" self.assertEqual(self.properties.t1(0), self.properties._qubits[0]["T1"][0]) def test_t2(self): """Test for getting the t2 of a given qubit""" self.assertEqual(self.properties.t2(0), self.properties._qubits[0]["T2"][0]) def test_frequency(self): """Test for getting the frequency of given qubit.""" self.assertEqual(self.properties.frequency(0), self.properties._qubits[0]["frequency"][0]) def test_readout_error(self): """Test for getting the readout error of given qubit.""" self.assertEqual(self.properties.readout_error(0), self.properties._qubits[0]["readout_error"][0]) def test_readout_length(self): """Test for getting the readout length of given qubit.""" self.assertEqual(self.properties.readout_length(0), self.properties._qubits[0]["readout_length"][0]) def test_apply_prefix(self): """Testing unit conversions.""" self.assertEqual(self.properties._apply_prefix(71.9500421005539, "µs"), 7.19500421005539e-05) self.assertEqual(self.properties._apply_prefix(71.9500421005539, "ms"), 0.0719500421005539) with self.assertRaises(BackendPropertyError): self.properties._apply_prefix(71.9500421005539, "ws") def test_operational(self): """Test operation status of a given qubit.""" self.assertTrue(self.properties.is_qubit_operational(0)) def test_deepcopy(self): """Test that deepcopy creates an identical object.""" copy_prop = copy.deepcopy(self.properties) self.assertEqual(copy_prop, self.properties)
class TestCmdDef(QiskitTestCase): """Test CmdDef methods.""" def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_openpulse_2q') self.device = DeviceSpecification.create_from(self.backend) def test_get_backend(self): """Test that backend is fetchable with cmd def present.""" def test_init(self): """Test `init`, `has`.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.device.q[0].drive)) cmd_def = CmdDef({('tmp', 0): sched}) self.assertTrue(cmd_def.has('tmp', 0)) def test_add(self): """Test `add`, `has`, `get`, `cmdss`.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.device.q[0].drive)) cmd_def = CmdDef() cmd_def.add('tmp', 1, sched) cmd_def.add('tmp', 0, sched) self.assertEqual(sched.instructions, cmd_def.get('tmp', (0, )).instructions) self.assertIn('tmp', cmd_def.cmds()) self.assertEqual(cmd_def.cmd_qubits('tmp'), [(0, ), (1, )]) def test_pop(self): """Test pop with default.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.device.q[0].drive)) cmd_def = CmdDef() cmd_def.add('tmp', 0, sched) cmd_def.pop('tmp', 0) self.assertFalse(cmd_def.has('tmp', 0)) with self.assertRaises(PulseError): cmd_def.pop('not_there', (0, )) def test_repr(self): """Test repr.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.device.q[0].drive)) cmd_def = CmdDef({('tmp', 0): sched}) repr(cmd_def) def test_parameterized_schedule(self): """Test building parameterized schedule.""" cmd_def = CmdDef() converter = QobjToInstructionConverter([], buffer=0) qobj = PulseQobjInstruction(name='pv', ch='u1', t0=10, val='P2*cos(np.pi*P1)') converted_instruction = converter(qobj) cmd_def.add('pv_test', 0, converted_instruction) self.assertEqual(cmd_def.get_parameters('pv_test', 0), ('P1', 'P2')) sched = cmd_def.get('pv_test', 0, P1='0', P2=-1) self.assertEqual(sched.instructions[0][-1].command.value, -1) def test_build_cmd_def(self): """Test building of parameterized cmd_def from defaults.""" defaults = self.backend.defaults() cmd_def = defaults.build_cmd_def() cx_pv = cmd_def.get('cx', (0, 1), P2=0) pv_found = False for _, instr in cx_pv.instructions: cmd = instr.command if isinstance(cmd, PersistentValue): self.assertEqual(cmd.value, 1) pv_found = True self.assertTrue(pv_found) self.assertEqual(cmd_def.get_parameters('u1', 0), ('P1', )) u1_minus_pi = cmd_def.get('u1', 0, P1=1) fc_cmd = u1_minus_pi.instructions[0][-1].command self.assertEqual(fc_cmd.phase, np.pi)
def setUp(self): """ setup for backend """ self.backends = list(filter(lambda x: not (x.configuration().simulator or x.configuration().n_qubits == 2), FakeProvider().backends()))
def setUp(self): self.provider = FakeProvider() self.backend = self.provider.get_backend('fake_openpulse_2q') self.device = DeviceSpecification.create_from(self.backend)