text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
--- deprecations: - | The M, Q, W, V matrix setters and M, Q, W, V matrix standard deviation setters from :class:`~qiskit_nature.second_q.algorithms.excited_states_solvers.qeom.QEOMResult` were pending deprecated and remain computable from the H and S matrices.
qiskit-nature/releasenotes/notes/0.6/pending-deprecate-mqwv-matrix-setter-1cd9e2dfb68d1a85.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.6/pending-deprecate-mqwv-matrix-setter-1cd9e2dfb68d1a85.yaml", "repo_id": "qiskit-nature", "token_count": 99 }
141
--- fixes: - | The :class:`.ActiveSpaceTransformer` would sometimes set the wrong number of active particles because of a flawed integer rounding. This has now been fixed.
qiskit-nature/releasenotes/notes/0.7/fix-active-space-integer-rounding-753ae77146610d9d.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.7/fix-active-space-integer-rounding-753ae77146610d9d.yaml", "repo_id": "qiskit-nature", "token_count": 49 }
142
--- fixes: - | Fixed the support of :attr:`~qiskit_nature.settings.use_pauli_sum_op` in the :class:`.UCC` and :class:`.UVCC` classes as well as their extensions. This requires version 0.24 or higher of the ``qiskit-terra`` package.
qiskit-nature/releasenotes/notes/0.7/support-pauli-sum-op-setting-in-ucc-43e33016b268cf19.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.7/support-pauli-sum-op-setting-in-ucc-43e33016b268cf19.yaml", "repo_id": "qiskit-nature", "token_count": 92 }
143
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test HFInitialPoint.""" import unittest from unittest.mock import Mock from test import QiskitNatureTestCase import numpy as np from qiskit_nature.exceptions import QiskitNatureError from qiskit_nature.second_q.algorithms.initial_points import HFInitialPoint from qiskit_nature.second_q.circuit.library import UCC from qiskit_nature.second_q.problems import ElectronicStructureProblem from qiskit_nature.second_q.hamiltonians import ElectronicEnergy class TestHFInitialPoint(QiskitNatureTestCase): """Test HFInitialPoint.""" def setUp(self) -> None: super().setUp() self.hf_initial_point = HFInitialPoint() self.ansatz = Mock(spec=UCC) self.ansatz.reps = 1 self.excitation_list = [((0,), (1,))] self.ansatz.excitation_list = self.excitation_list def test_missing_ansatz(self): """Test set get ansatz.""" with self.assertRaises(QiskitNatureError): self.hf_initial_point.compute() def test_set_get_ansatz(self): """Test set get ansatz.""" self.hf_initial_point.ansatz = self.ansatz self.assertEqual(self.hf_initial_point.ansatz, self.ansatz) def test_set_get_problem(self): """Test set get problem.""" reference_energy = 123.0 electronic_energy = Mock(spec=ElectronicEnergy) problem = Mock(spec=ElectronicStructureProblem) problem.hamiltonian = electronic_energy problem.reference_energy = reference_energy self.hf_initial_point.problem = problem self.assertEqual(self.hf_initial_point.problem, problem) self.assertEqual(self.hf_initial_point._reference_energy, reference_energy) def test_set_missing_electronic_energy(self): """Test set missing ElectronicEnergy.""" problem = Mock(spec=ElectronicStructureProblem) problem.hamiltonian = None with self.assertWarns(UserWarning): self.hf_initial_point.problem = problem self.assertEqual(self.hf_initial_point.problem, None) def test_compute(self): """Test length of HF initial point array.""" problem = Mock(spec=ElectronicStructureProblem) problem.hamiltonian = Mock(spec=ElectronicEnergy) problem.reference_energy = None self.hf_initial_point.compute(ansatz=self.ansatz, problem=problem) initial_point = self.hf_initial_point.to_numpy_array() np.testing.assert_equal(initial_point, np.asarray([0.0])) def test_hf_initial_point_is_all_zero(self): """Test HF initial point is all zero.""" self.hf_initial_point.ansatz = self.ansatz initial_point = self.hf_initial_point.to_numpy_array() np.testing.assert_array_equal(initial_point, np.asarray([0.0])) def test_hf_energy(self): """Test HF energy.""" reference_energy = 123.0 electronic_energy = Mock(spec=ElectronicEnergy) problem = Mock(spec=ElectronicStructureProblem) problem.hamiltonian = electronic_energy problem.reference_energy = reference_energy self.hf_initial_point.problem = problem self.hf_initial_point.ansatz = self.ansatz energy = self.hf_initial_point.total_energy self.assertEqual(energy, 123.0) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/algorithms/initial_points/test_hf_initial_point.py/0
{ "file_path": "qiskit-nature/test/second_q/algorithms/initial_points/test_hf_initial_point.py", "repo_id": "qiskit-nature", "token_count": 1455 }
144
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the excitation generator.""" from test import QiskitNatureTestCase from ddt import data, ddt, unpack from qiskit_nature.second_q.circuit.library.ansatzes.utils.vibration_excitation_generator import ( generate_vibration_excitations, ) @ddt class TestVibrationExcitationGenerator(QiskitNatureTestCase): """Tests for the default vibration excitation generator method.""" @unpack @data( (1, [2], [((0,), (1,))]), (1, [3], [((0,), (1,)), ((0,), (2,))]), (2, [3], []), (1, [2, 2], [((0,), (1,)), ((2,), (3,))]), (2, [2, 2], [((0, 2), (1, 3))]), (1, [3, 3], [((0,), (1,)), ((0,), (2,)), ((3,), (4,)), ((3,), (5,))]), ( 2, [3, 3], [((0, 3), (1, 4)), ((0, 3), (1, 5)), ((0, 3), (2, 4)), ((0, 3), (2, 5))], ), (3, [3, 3], []), (2, [2, 2, 2], [((0, 2), (1, 3)), ((0, 4), (1, 5)), ((2, 4), (3, 5))]), (3, [2, 2, 2], [((0, 2, 4), (1, 3, 5))]), (4, [2, 2, 2], []), (2, [2, 3], [((0, 2), (1, 3)), ((0, 2), (1, 4))]), ( 2, [2, 3, 2], [ ((0, 2), (1, 3)), ((0, 2), (1, 4)), ((0, 5), (1, 6)), ((2, 5), (3, 6)), ((2, 5), (4, 6)), ], ), (3, [2, 3, 2], [((0, 2, 5), (1, 3, 6)), ((0, 2, 5), (1, 4, 6))]), ) def test_generate_excitations(self, num_excitations, num_modals, expect): """Test standard input arguments.""" excitations = generate_vibration_excitations(num_excitations, num_modals) self.assertEqual(excitations, expect)
qiskit-nature/test/second_q/circuit/library/ansatzes/utils/test_vibration_excitation_generator.py/0
{ "file_path": "qiskit-nature/test/second_q/circuit/library/ansatzes/utils/test_vibration_excitation_generator.py", "repo_id": "qiskit-nature", "token_count": 1069 }
145
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test FCIDump """ import builtins import unittest from abc import ABC, abstractmethod from test import QiskitNatureTestCase from test.second_q.utils import get_expected_two_body_ints import numpy as np from qiskit_nature.second_q.formats.fcidump import FCIDump from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem class BaseTestFCIDump(ABC): """FCIDump base test class.""" def __init__(self): self.log = None self.problem = None self.nuclear_repulsion_energy = None self.num_molecular_orbitals = None self.num_alpha = None self.num_beta = None self.mo_onee = None self.mo_onee_b = None self.mo_eri = None self.mo_eri_ba = None self.mo_eri_bb = None @abstractmethod def subTest(self, msg, **kwargs): # pylint: disable=invalid-name """subtest""" raise builtins.Exception("Abstract method") @abstractmethod def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """assert Almost Equal""" raise builtins.Exception("Abstract method") @abstractmethod def assertEqual(self, first, second, msg=None): """assert equal""" raise builtins.Exception("Abstract method") @abstractmethod def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """assert Sequence Equal""" raise builtins.Exception("Abstract method") def test_electronic_energy(self): """Test the ElectronicEnergy property.""" electronic_energy = self.problem.hamiltonian with self.subTest("inactive energy"): self.log.debug("inactive energy: %s", electronic_energy.nuclear_repulsion_energy) self.assertAlmostEqual( electronic_energy.nuclear_repulsion_energy, self.nuclear_repulsion_energy, places=3, ) with self.subTest("1-body alpha"): alpha_1body = electronic_energy.electronic_integrals.alpha["+-"] self.log.debug("MO one electron alpha integrals are %s", alpha_1body) self.assertEqual(alpha_1body.shape, self.mo_onee.shape) np.testing.assert_array_almost_equal( np.absolute(alpha_1body), np.absolute(self.mo_onee), decimal=4 ) if self.mo_onee_b is not None: with self.subTest("1-body beta"): beta_1body = electronic_energy.electronic_integrals.beta["+-"] self.log.debug("MO one electron beta integrals are %s", beta_1body) self.assertEqual(beta_1body.shape, self.mo_onee_b.shape) np.testing.assert_array_almost_equal( np.absolute(beta_1body), np.absolute(self.mo_onee_b), decimal=4 ) with self.subTest("2-body alpha-alpha"): alpha_2body = electronic_energy.electronic_integrals.alpha["++--"] self.log.debug("MO two electron alpha-alpha integrals are %s", alpha_2body) self.assertEqual(alpha_2body.shape, self.mo_eri.shape) np.testing.assert_array_almost_equal( np.absolute(alpha_2body), np.absolute(get_expected_two_body_ints(alpha_2body, self.mo_eri)), decimal=4, ) if self.mo_eri_ba is not None: with self.subTest("2-body beta-alpha"): beta_alpha_2body = electronic_energy.electronic_integrals.beta_alpha["++--"] self.log.debug("MO two electron beta-alpha integrals are %s", beta_alpha_2body) self.assertEqual(beta_alpha_2body.shape, self.mo_eri_ba.shape) np.testing.assert_array_almost_equal( np.absolute(beta_alpha_2body), np.absolute(get_expected_two_body_ints(beta_alpha_2body, self.mo_eri_ba)), decimal=4, ) if self.mo_eri_bb is not None: with self.subTest("2-body beta-beta"): beta_2body = electronic_energy.electronic_integrals.beta["++--"] self.log.debug("MO two electron beta-alpha integrals are %s", beta_2body) self.assertEqual(beta_2body.shape, self.mo_eri_bb.shape) np.testing.assert_array_almost_equal( np.absolute(beta_2body), np.absolute(get_expected_two_body_ints(beta_2body, self.mo_eri_bb)), decimal=4, ) def test_system_size(self): """Test the system size problem attributes.""" with self.subTest("orbital number"): self.log.debug("Number of orbitals is %s", self.problem.num_spatial_orbitals) self.assertEqual(self.problem.num_spatial_orbitals, self.num_molecular_orbitals) with self.subTest("alpha electron number"): self.log.debug("Number of alpha electrons is %s", self.problem.num_alpha) self.assertEqual(self.problem.num_alpha, self.num_alpha) with self.subTest("beta electron number"): self.log.debug("Number of beta electrons is %s", self.problem.num_beta) self.assertEqual(self.problem.num_beta, self.num_beta) class TestFCIDumpH2(QiskitNatureTestCase, BaseTestFCIDump): """RHF H2 FCIDump tests.""" def setUp(self): super().setUp() self.nuclear_repulsion_energy = 0.7199 self.num_molecular_orbitals = 2 self.num_alpha = 1 self.num_beta = 1 self.mo_onee = np.array([[1.2563, 0.0], [0.0, 0.4719]]) self.mo_onee_b = None self.mo_eri = np.array( [ [[[0.6757, 0.0], [0.0, 0.6646]], [[0.0, 0.1809], [0.1809, 0.0]]], [[[0.0, 0.1809], [0.1809, 0.0]], [[0.6646, 0.0], [0.0, 0.6986]]], ] ) self.mo_eri_ba = None self.mo_eri_bb = None fcidump = FCIDump.from_file( self.get_resource_path("test_fcidump_h2.fcidump", "second_q/formats/fcidump") ) self.problem = fcidump_to_problem(fcidump) class TestFCIDumpLiH(QiskitNatureTestCase, BaseTestFCIDump): """RHF LiH FCIDump tests.""" def setUp(self): super().setUp() self.nuclear_repulsion_energy = 0.9924 self.num_molecular_orbitals = 6 self.num_alpha = 2 self.num_beta = 2 loaded = np.load(self.get_resource_path("test_fcidump_lih.npz", "second_q/formats/fcidump")) self.mo_onee = loaded["mo_onee"] self.mo_onee_b = None self.mo_eri = loaded["mo_eri"] self.mo_eri_ba = None self.mo_eri_bb = None fcidump = FCIDump.from_file( self.get_resource_path("test_fcidump_lih.fcidump", "second_q/formats/fcidump") ) self.problem = fcidump_to_problem(fcidump) class TestFCIDumpOH(QiskitNatureTestCase, BaseTestFCIDump): """UHF OH FCIDump tests.""" def setUp(self): super().setUp() self.nuclear_repulsion_energy = 11.3412 self.num_molecular_orbitals = 6 self.num_alpha = 5 self.num_beta = 4 loaded = np.load(self.get_resource_path("test_fcidump_oh.npz", "second_q/formats/fcidump")) self.mo_onee = loaded["mo_onee"] self.mo_onee_b = loaded["mo_onee_b"] self.mo_eri = loaded["mo_eri"] self.mo_eri_ba = loaded["mo_eri_ba"] self.mo_eri_bb = loaded["mo_eri_bb"] fcidump = FCIDump.from_file( self.get_resource_path("test_fcidump_oh.fcidump", "second_q/formats/fcidump") ) self.problem = fcidump_to_problem(fcidump) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/formats/fcidump/test_fcidump.py/0
{ "file_path": "qiskit-nature/test/second_q/formats/fcidump/test_fcidump.py", "repo_id": "qiskit-nature", "token_count": 3815 }
146
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The expected water output QCSchema.""" from qiskit_nature.second_q.formats.qcschema import ( QCBasisSet, QCCenterData, QCElectronShell, QCModel, QCProperties, QCProvenance, QCSchema, QCTopology, QCWavefunction, ) EXPECTED = QCSchema( schema_name="qc_schema_output", schema_version=1, molecule=QCTopology( symbols=["O", "H", "H"], geometry=[ 0.0, 0.0, -0.1294769411935893, 0.0, -1.494187339479985, 1.0274465079245698, 0.0, 1.494187339479985, 1.0274465079245698, ], schema_name="qcschema_molecule", schema_version=2, ), driver="energy", model=QCModel( method="B3LYP", basis="cc-pVDZ", ), keywords={}, provenance=QCProvenance( creator="QM Program", version="1.1", routine="module.json.run_json", ), return_result=-76.4187620271478, success=True, properties=QCProperties( calcinfo_nbasis=24, calcinfo_nmo=24, calcinfo_nalpha=5, calcinfo_nbeta=5, calcinfo_natom=3, return_energy=-76.4187620271478, scf_one_electron_energy=-122.5182981454265, scf_two_electron_energy=44.844942513688004, nuclear_repulsion_energy=8.80146205625184, scf_dipole_moment=[0.0, 0.0, 1.925357619589245], # type: ignore[arg-type] scf_total_energy=-76.4187620271478, scf_xc_energy=-7.546868451661161, scf_iterations=6, ), wavefunction=QCWavefunction( basis=QCBasisSet( name="6-31G", description="6-31G on all Hydrogen and Oxygen atoms", center_data={ "bs_631g_h": QCCenterData( electron_shells=[ QCElectronShell( harmonic_type="spherical", angular_momentum=[0], exponents=["18.731137", "2.8253944", "0.6401217"], coefficients=[["0.0334946", "0.2347269", "0.8137573"]], ), QCElectronShell( harmonic_type="spherical", angular_momentum=[0], exponents=["0.1612778"], coefficients=[["1.0000000"]], ), ], ), "bs_631g_o": QCCenterData( electron_shells=[ QCElectronShell( harmonic_type="spherical", angular_momentum=[0], exponents=[ "5484.6717000", "825.2349500", "188.0469600", "52.9645000", "16.8975700", "5.7996353", ], coefficients=[ [ "0.0018311", "0.0139501", "0.0684451", "0.2327143", "0.4701930", "0.3585209", ] ], ), QCElectronShell( harmonic_type="spherical", angular_momentum=[0, 1], exponents=["15.5396160", "3.5999336", "1.0137618"], coefficients=[ ["-0.1107775", "-0.1480263", "1.1307670"], ["0.0708743", "0.3397528", "0.7271586"], ], ), QCElectronShell( harmonic_type="spherical", angular_momentum=[0, 1], exponents=["0.2700058"], coefficients=[["1.0000000"], ["1.0000000"]], ), ], ), }, atom_map=[ "bs_631g_o", "bs_631g_h", "bs_631g_h", ], ), ), )
qiskit-nature/test/second_q/formats/qcschema/water_output.py/0
{ "file_path": "qiskit-nature/test/second_q/formats/qcschema/water_output.py", "repo_id": "qiskit-nature", "token_count": 3200 }
147
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test HeisenbergModel.""" from test import QiskitNatureTestCase from rustworkx import PyGraph, is_isomorphic from qiskit_nature.second_q.hamiltonians.lattices import Lattice, LineLattice from qiskit_nature.second_q.hamiltonians import HeisenbergModel, IsingModel class TestHeisenbergModel(QiskitNatureTestCase): """TestHeisenbergModel""" def test_init(self): """Test init.""" line = LineLattice(num_nodes=2) heisenberg_model = HeisenbergModel(lattice=line) with self.subTest("Check the graph."): self.assertTrue( is_isomorphic( heisenberg_model.lattice.graph, line.graph, edge_matcher=lambda x, y: x == y ) ) with self.subTest("Check the second q op representation."): terms = [("X_0 X_1", 1.0), ("Y_0 Y_1", 1.0), ("Z_0 Z_1", 1.0)] hamiltonian = terms self.assertSetEqual(set(hamiltonian), set(heisenberg_model.second_q_op().items())) def test_triangular(self): """Test triangular lattice.""" triangle_graph = PyGraph(multigraph=False) triangle_graph.add_nodes_from(range(3)) triangle_weighted_edge_list = [ (0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (0, 0, 1.0), (1, 1, 1.0), (2, 2, 1.0), ] triangle_graph.add_edges_from(triangle_weighted_edge_list) triangle_lattice = Lattice(triangle_graph) ext_magnetic_field_y = (0.0, 1.0, 0.0) triangle_y_heisenberg_model = HeisenbergModel( triangle_lattice, ext_magnetic_field=ext_magnetic_field_y ) with self.subTest("Check the graph of triangular model."): self.assertTrue( is_isomorphic( triangle_y_heisenberg_model.lattice.graph, triangle_lattice.graph, edge_matcher=lambda x, y: x == y, ) ) with self.subTest("Check the second q ops in the triangular lattice with param in y axis."): terms = [ ("X_0 X_1", 1.0), ("Y_0 Y_1", 1.0), ("Z_0 Z_1", 1.0), ("X_0 X_2", 1.0), ("Y_0 Y_2", 1.0), ("Z_0 Z_2", 1.0), ("X_1 X_2", 1.0), ("Y_1 Y_2", 1.0), ("Z_1 Z_2", 1.0), ("Y_0", 1.0), ("Y_1", 1.0), ("Y_2", 1.0), ] hamiltonian = terms self.assertSetEqual( set(hamiltonian), set(triangle_y_heisenberg_model.second_q_op().items()) ) def test_ising(self): """Test Ising.""" line = LineLattice(num_nodes=2, onsite_parameter=1) ism = IsingModel(lattice=line) coupling_constants = (0.0, 0.0, 1.0) ext_magnetic_field = (1.0, 0.0, 0.0) hm_to_ism = HeisenbergModel( lattice=line, coupling_constants=coupling_constants, ext_magnetic_field=ext_magnetic_field, ) with self.subTest("Check if the HeisenbergModel reproduce IsingModel in a special case."): self.assertSetEqual( set(ism.second_q_op().items()), set(hm_to_ism.second_q_op().items()), ) def test_xy(self): """Test x and y directions.""" line = LineLattice(num_nodes=2) xy_coupling = (0.5, 0.5, 0.0) xy_ext_magnetic_field = (-0.75, 0.25, 0.0) xy_test_hm = HeisenbergModel( lattice=line, coupling_constants=xy_coupling, ext_magnetic_field=xy_ext_magnetic_field ) with self.subTest("Check if if x and y params are being applied."): terms = [ ("X_0 X_1", 0.5), ("Y_0 Y_1", 0.5), ("X_0", -0.75), ("Y_0", 0.25), ("X_1", -0.75), ("Y_1", 0.25), ] hamiltonian = terms self.assertSetEqual(set(hamiltonian), set(xy_test_hm.second_q_op().items())) def test_xyz_ext_field(self): """Test external field.""" line = LineLattice(num_nodes=2) xyz_ext_magnetic_field = (1.0, 1.0, 1.0) xyz_test_hm = HeisenbergModel(lattice=line, ext_magnetic_field=xyz_ext_magnetic_field) with self.subTest("Check if if x, y and z params are being applied."): terms = [ ("X_0 X_1", 1.0), ("Y_0 Y_1", 1.0), ("Z_0 Z_1", 1.0), ("X_0", 1.0), ("X_1", 1.0), ("Y_0", 1.0), ("Y_1", 1.0), ("Z_0", 1.0), ("Z_1", 1.0), ] hamiltonian = terms self.assertSetEqual(set(hamiltonian), set(xyz_test_hm.second_q_op().items()))
qiskit-nature/test/second_q/hamiltonians/test_heisenberg_model.py/0
{ "file_path": "qiskit-nature/test/second_q/hamiltonians/test_heisenberg_model.py", "repo_id": "qiskit-nature", "token_count": 2898 }
148
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for VibrationalOp""" import unittest from test import QiskitNatureTestCase from qiskit_nature.second_q.operators import VibrationalOp class TestVibrationalOp(QiskitNatureTestCase): """VibrationalOp tests.""" op1 = VibrationalOp({"+_0_0 -_0_0": 1}, num_modals=[1]) op2 = VibrationalOp({"-_0_0 +_0_0": 2}) op3 = VibrationalOp({"+_0_0 -_0_0": 1, "-_0_0 +_0_0": 2}) def test_automatic_num_modals(self): """Test operators with automatic num_modals""" with self.subTest("Empty data"): op = VibrationalOp({"": 1}) self.assertEqual(op.num_modals, []) with self.subTest("Single mode and modal"): op = VibrationalOp({"+_0_0": 1}) self.assertEqual(op.num_modals, [1]) with self.subTest("Single mode and modal"): op = VibrationalOp({"+_0_0 +_1_0": 1}) self.assertEqual(op.num_modals, [1, 1]) with self.subTest("Single mode and modal"): op = VibrationalOp({"+_0_0 +_1_1": 1}) self.assertEqual(op.num_modals, [1, 2]) with self.subTest("Single mode and modal"): op = VibrationalOp({"+_0_0 +_1_1": 1}, num_modals=[0, 0]) self.assertEqual(op.num_modals, [1, 2]) def test_neg(self): """Test __neg__""" vib_op = -self.op1 targ = VibrationalOp({"+_0_0 -_0_0": -1}, num_modals=[1]) self.assertEqual(vib_op, targ) def test_mul(self): """Test __mul__, and __rmul__""" with self.subTest("rightmul"): vib_op = self.op1 * 2 targ = VibrationalOp({"+_0_0 -_0_0": 2}, num_modals=[1]) self.assertEqual(vib_op, targ) with self.subTest("left mul"): vib_op = (2 + 1j) * self.op3 targ = VibrationalOp({"+_0_0 -_0_0": (2 + 1j), "-_0_0 +_0_0": (4 + 2j)}, num_modals=[1]) self.assertEqual(vib_op, targ) def test_div(self): """Test __truediv__""" vib_op = self.op1 / 2 targ = VibrationalOp({"+_0_0 -_0_0": 0.5}, num_modals=[1]) self.assertEqual(vib_op, targ) def test_add(self): """Test __add__""" vib_op = self.op1 + self.op2 targ = self.op3 self.assertEqual(vib_op, targ) with self.subTest("sum"): vib_op = sum( VibrationalOp({label: 1}, num_modals=[1, 1, 1]) for label in ["+_0_0", "-_1_0", "+_2_0 -_2_0"] ) targ = VibrationalOp({"+_0_0": 1, "-_1_0": 1, "+_2_0 -_2_0": 1}) self.assertEqual(vib_op, targ) def test_sub(self): """Test __sub__""" vib_op = self.op3 - self.op2 targ = VibrationalOp({"+_0_0 -_0_0": 1, "-_0_0 +_0_0": 0}, num_modals=[1]) self.assertEqual(vib_op, targ) def test_compose(self): """Test operator composition""" with self.subTest("single compose"): vib_op = VibrationalOp({"+_0_0 -_1_0": 1}, num_modals=[1, 1]) @ VibrationalOp( {"-_0_0": 1}, num_modals=[1, 1] ) targ = VibrationalOp({"+_0_0 -_1_0 -_0_0": 1}, num_modals=[1, 1]) self.assertEqual(vib_op, targ) with self.subTest("multi compose"): vib_op = VibrationalOp( {"+_0_0 +_1_0 -_1_0": 1, "-_0_0 +_0_0 -_1_0": 1}, num_modals=[1, 1] ) @ VibrationalOp({"": 1, "-_0_0 +_1_0": 1}, num_modals=[1, 1]) vib_op = vib_op.simplify() targ = VibrationalOp( { "+_0_0 +_1_0 -_1_0": 1, "-_0_0 +_0_0 -_1_0": 1, "+_0_0 +_1_0 -_0_0": 1, "-_0_0 -_1_0 +_1_0": 1, }, num_modals=[1, 1], ) self.assertEqual(vib_op, targ) with self.subTest("creation commutation relation"): op1 = VibrationalOp({"+_0_0": 1}, num_modals=[1]) comm = (op1 @ op1 - op1 @ op1).normal_order() self.assertTrue(comm.is_zero()) with self.subTest("annihilation commutation relation"): op1 = VibrationalOp({"-_0_0": 1}, num_modals=[1]) comm = (op1 @ op1 - op1 @ op1).normal_order() self.assertTrue(comm.is_zero()) with self.subTest("mixed commutation relation"): op1 = VibrationalOp({"-_0_0": 1}, num_modals=[1]) op2 = VibrationalOp({"+_0_0": 1}, num_modals=[1]) comm = (op1 @ op2 - op2 @ op1).normal_order() targ = VibrationalOp({"": 1}) self.assertEqual(comm, targ) def test_tensor(self): """Test tensor multiplication""" vib_op = self.op1.tensor(self.op2) targ = VibrationalOp({"+_0_0 -_0_0 -_1_0 +_1_0": 2}, num_modals=[1, 1]) self.assertEqual(vib_op, targ) def test_expand(self): """Test reversed tensor multiplication""" vib_op = self.op1.expand(self.op2) targ = VibrationalOp({"-_0_0 +_0_0 +_1_0 -_1_0": 2}, num_modals=[1, 1]) self.assertEqual(vib_op, targ) def test_pow(self): """Test __pow__""" with self.subTest("square trivial"): vib_op = ( VibrationalOp({"+_0_0 +_1_0 -_1_0": 3, "-_0_0 +_0_0 -_1_0": 1}, num_modals=[1, 1]) ** 2 ) vib_op = vib_op.simplify() targ = VibrationalOp.zero() self.assertEqual(vib_op, targ) with self.subTest("square nontrivial"): vib_op = ( VibrationalOp({"+_0_0 +_1_0 -_1_0": 3, "+_0_0 -_0_0 -_1_0": 1}, num_modals=[1, 1]) ** 2 ) vib_op = vib_op.simplify() targ = VibrationalOp({"+_0_0 -_1_0": 3}, num_modals=[1]) self.assertEqual(vib_op, targ) with self.subTest("3rd power"): vib_op = (3 * VibrationalOp.one()) ** 3 targ = 27 * VibrationalOp.one() self.assertEqual(vib_op, targ) with self.subTest("0th power"): vib_op = ( VibrationalOp({"+_0_0 +_1_0 -_1_0": 3, "-_0_0 +_0_0 -_1_0": 1}, num_modals=[1, 1]) ** 0 ) vib_op = vib_op.simplify() targ = VibrationalOp.one() self.assertEqual(vib_op, targ) def test_adjoint(self): """Test adjoint method""" vib_op = VibrationalOp( {"": 1j, "+_0_0 +_1_0 -_1_0": 3, "+_0_0 -_0_0 -_1_0": 1, "-_0_0 -_1_0": 2 + 4j}, num_modals=[1, 1, 1], ).adjoint() targ = VibrationalOp( {"": -1j, "+_1_0 -_1_0 -_0_0": 3, "+_1_0 +_0_0 -_0_0": 1, "+_1_0 +_0_0": 2 - 4j}, num_modals=[1, 1, 1], ) self.assertEqual(vib_op, targ) def test_simplify(self): """Test simplify""" with self.subTest("simplify integer"): vib_op = VibrationalOp({"+_0_0 -_0_0": 1, "+_0_0 -_0_0 +_0_0 -_0_0": 1}, num_modals=[1]) simplified_op = vib_op.simplify() targ = VibrationalOp({"+_0_0 -_0_0": 2}, num_modals=[1]) self.assertEqual(simplified_op, targ) with self.subTest("simplify complex"): vib_op = VibrationalOp( {"+_0_0 -_0_0": 1, "+_0_0 -_0_0 +_0_0 -_0_0": 1j}, num_modals=[1] ) simplified_op = vib_op.simplify() targ = VibrationalOp({"+_0_0 -_0_0": 1 + 1j}, num_modals=[1]) self.assertEqual(simplified_op, targ) with self.subTest("simplify doesn't reorder"): vib_op = VibrationalOp({"-_0_0 +_1_0": 1 + 0j}, num_modals=[1, 1]) simplified_op = vib_op.simplify() self.assertEqual(simplified_op, vib_op) vib_op = VibrationalOp({"-_1_0 +_0_0": 1 + 0j}, num_modals=[1, 1]) simplified_op = vib_op.simplify() self.assertEqual(simplified_op, vib_op) with self.subTest("simplify zero"): vib_op = self.op1 - self.op1 simplified_op = vib_op.simplify() targ = VibrationalOp.zero() self.assertEqual(simplified_op, targ) with self.subTest("simplify commutes with normal_order"): self.assertEqual(self.op2.simplify().normal_order(), self.op2.normal_order().simplify()) with self.subTest("simplify + index order"): orig = VibrationalOp({"+_1_0 -_0_0 +_0_0 -_0_0": 1, "-_0_0 +_1_0": 2}) vib_op = orig.simplify().index_order() targ = VibrationalOp({"-_0_0 +_1_0": 3}) self.assertEqual(vib_op, targ) def test_equiv(self): """test equiv""" prev_atol = VibrationalOp.atol prev_rtol = VibrationalOp.rtol op3 = self.op1 + (1 + 0.00005) * self.op2 self.assertFalse(op3.equiv(self.op3)) VibrationalOp.atol = 1e-4 VibrationalOp.rtol = 1e-4 self.assertTrue(op3.equiv(self.op3)) VibrationalOp.atol = prev_atol VibrationalOp.rtol = prev_rtol def test_induced_norm(self): """Test induced norm.""" op = 3 * VibrationalOp({"+_0_0": 1}, num_modals=[0]) + 4j * VibrationalOp( {"-_0_0": 1}, num_modals=[0] ) self.assertAlmostEqual(op.induced_norm(), 7.0) self.assertAlmostEqual(op.induced_norm(2), 5.0) def test_normal_order(self): """test normal_order method""" with self.subTest("Test for creation operator"): orig = VibrationalOp({"+_0_0": 1}) vib_op = orig.normal_order() self.assertEqual(vib_op, orig) with self.subTest("Test for annihilation operator"): orig = VibrationalOp({"-_0_0": 1}) vib_op = orig.normal_order() self.assertEqual(vib_op, orig) with self.subTest("Test for number operator"): orig = VibrationalOp({"+_0_0 -_0_0": 1}) vib_op = orig.normal_order() self.assertEqual(vib_op, orig) with self.subTest("Test for empty operator"): orig = VibrationalOp({"-_0_0 +_0_0": 1}) vib_op = orig.normal_order() targ = VibrationalOp({"": 1, "+_0_0 -_0_0": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test for multiple operators 1"): orig = VibrationalOp({"-_0_0 +_1_0": 1}) vib_op = orig.normal_order() targ = VibrationalOp({"+_1_0 -_0_0": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test for multiple operators 2"): orig = VibrationalOp({"-_0_0 +_0_0 +_1_0 -_2_0": 1}) vib_op = orig.normal_order() targ = VibrationalOp({"+_1_0 -_2_0": 1, "+_0_0 +_1_0 -_0_0 -_2_0": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test normal ordering simplifies"): orig = VibrationalOp({"-_0_0 +_1_0": 1, "+_1_0 -_0_0": 1, "+_0_0": 0.0}) vib_op = orig.normal_order() targ = VibrationalOp({"+_1_0 -_0_0": 2}) self.assertEqual(vib_op, targ) with self.subTest("Test with multiple modals 1"): orig = VibrationalOp({"-_0_0 +_0_1": 1}) vib_op = orig.normal_order() targ = VibrationalOp({"+_0_1 -_0_0": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test with multiple modals 2"): orig = VibrationalOp({"+_0_1 -_1_0": 1}) vib_op = orig.normal_order() self.assertEqual(vib_op, orig) with self.subTest("Test with multiple modals 3"): orig = VibrationalOp({"-_1_1 +_1_0 +_0_1 -_0_0": 1}) vib_op = orig.normal_order() targ = VibrationalOp({"+_0_1 +_1_0 -_0_0 -_1_1": 1}) self.assertEqual(vib_op, targ) def test_index_order(self): """test index_order method""" with self.subTest("Test for creation operator"): orig = VibrationalOp({"+_0_0": 1}) vib_op = orig.index_order() self.assertEqual(vib_op, orig) with self.subTest("Test for annihilation operator"): orig = VibrationalOp({"-_0_0": 1}) vib_op = orig.index_order() self.assertEqual(vib_op, orig) with self.subTest("Test for number operator"): orig = VibrationalOp({"+_0_0 -_0_0": 1}) vib_op = orig.index_order() self.assertEqual(vib_op, orig) with self.subTest("Test for empty operator"): orig = VibrationalOp({"-_0_0 +_0_0": 1}) vib_op = orig.index_order() self.assertEqual(vib_op, orig) with self.subTest("Test for multiple operators 1"): orig = VibrationalOp({"+_1_0 -_0_0": 1}) vib_op = orig.index_order() targ = VibrationalOp({"-_0_0 +_1_0": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test for multiple operators 2"): orig = VibrationalOp({"+_2_0 -_0_0 +_1_0 -_0_0": 1, "-_0_0 +_1_0": 2}) vib_op = orig.index_order() targ = VibrationalOp({"-_0_0 -_0_0 +_1_0 +_2_0": 1, "-_0_0 +_1_0": 2}) self.assertEqual(vib_op, targ) with self.subTest("Test index ordering simplifies"): orig = VibrationalOp({"-_0_0 +_1_0": 1, "+_1_0 -_0_0": 1, "+_0_0": 0.0}) vib_op = orig.index_order() targ = VibrationalOp({"-_0_0 +_1_0": 2}) self.assertEqual(vib_op, targ) with self.subTest("index order + simplify"): orig = VibrationalOp({"+_1_0 -_0_0 +_0_0 -_0_0": 1, "-_0_0 +_1_0": 2}) vib_op = orig.index_order().simplify() targ = VibrationalOp({"-_0_0 +_1_0": 3}) self.assertEqual(vib_op, targ) with self.subTest("Test with multiple modals 1"): orig = VibrationalOp({"+_0_1 -_0_0": 1}) vib_op = orig.index_order() targ = VibrationalOp({"-_0_0 +_0_1": 1}) self.assertEqual(vib_op, targ) with self.subTest("Test with multiple modals 2"): orig = VibrationalOp({"+_0_1 -_1_0": 1}) vib_op = orig.index_order() self.assertEqual(vib_op, orig) with self.subTest("Test with multiple modals 3"): orig = VibrationalOp({"-_1_1 +_1_0 +_0_1 -_0_0": 1}) vib_op = orig.index_order() targ = VibrationalOp({"-_0_0 +_0_1 +_1_0 -_1_1": 1}) self.assertEqual(vib_op, targ) def test_terms(self): """Test terms generator.""" op = VibrationalOp( { "+_0_0": 1, "-_0_1 +_1_1": 2, "+_1_0 -_1_1 +_2_0": 2, }, num_modals=[2, 2, 1], ) terms = [([("+", 0)], 1), ([("-", 1), ("+", 3)], 2), ([("+", 2), ("-", 3), ("+", 4)], 2)] with self.subTest("terms"): self.assertEqual(list(op.terms()), terms) with self.subTest("from_terms"): with self.assertRaises(NotImplementedError): VibrationalOp.from_terms(terms) def test_permute_indices(self): """Test index permutation method.""" with self.assertRaises(NotImplementedError): VibrationalOp({"+_0_0 -_1_0": 2}).permute_indices([1, 0]) def test_reg_len_with_skipped_key_validation(self): """Test the behavior of `register_length` after key validation was skipped.""" new_op = VibrationalOp({"+_0_0 -_1_1": 1}, validate=False) self.assertIsNone(new_op.num_modals) self.assertEqual(new_op.register_length, 3) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/operators/test_vibrational_op.py/0
{ "file_path": "qiskit-nature/test/second_q/operators/test_vibrational_op.py", "repo_id": "qiskit-nature", "token_count": 8636 }
149
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """PropertyTest class""" from test import QiskitNatureTestCase from itertools import zip_longest from qiskit_nature.second_q.properties import ( AngularMomentum, Magnetization, ParticleNumber, OccupiedModals, ) class PropertyTest(QiskitNatureTestCase): """Property instance tester""" def compare_angular_momentum( self, first: AngularMomentum, second: AngularMomentum, msg: str = None ) -> None: """Compares two AngularMomentum instances.""" if first.num_spatial_orbitals != second.num_spatial_orbitals: raise self.failureException(msg) def compare_magnetization( self, first: Magnetization, second: Magnetization, msg: str = None ) -> None: """Compares two Magnetization instances.""" if first.num_spatial_orbitals != second.num_spatial_orbitals: raise self.failureException(msg) def compare_particle_number( self, first: ParticleNumber, second: ParticleNumber, msg: str = None ) -> None: """Compares two ParticleNumber instances.""" if first.num_spatial_orbitals != second.num_spatial_orbitals: raise self.failureException(msg) def compare_occupied_modals( self, first: OccupiedModals, second: OccupiedModals, msg: str = None ) -> None: # pylint: disable=unused-argument """Compares two OccupiedModals instances.""" if any(f != s for f, s in zip_longest(first.num_modals, second.num_modals)): raise self.failureException(msg) def setUp(self) -> None: """Setup expected object.""" super().setUp() self.addTypeEqualityFunc(AngularMomentum, self.compare_angular_momentum) self.addTypeEqualityFunc(Magnetization, self.compare_magnetization) self.addTypeEqualityFunc(ParticleNumber, self.compare_particle_number) self.addTypeEqualityFunc(OccupiedModals, self.compare_occupied_modals)
qiskit-nature/test/second_q/properties/property_test.py/0
{ "file_path": "qiskit-nature/test/second_q/properties/property_test.py", "repo_id": "qiskit-nature", "token_count": 895 }
150
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the FreezeCoreTransformer.""" import unittest from test import QiskitNatureTestCase from test.second_q.utils import get_expected_two_body_ints from ddt import ddt, idata import numpy as np import qiskit_nature.optionals as _optionals from qiskit_nature import QiskitNatureError from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.qcschema import QCSchema from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem from qiskit_nature.second_q.operators.tensor_ordering import to_chemist_ordering from qiskit_nature.second_q.transformers import FreezeCoreTransformer @ddt class TestFreezeCoreTransformer(QiskitNatureTestCase): """FreezeCoreTransformer tests.""" from test.second_q.transformers.test_active_space_transformer import ( TestActiveSpaceTransformer, ) assertDriverResult = TestActiveSpaceTransformer.assertDriverResult assertElectronicEnergy = TestActiveSpaceTransformer.assertElectronicEnergy @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") @idata( [ {"freeze_core": True}, ] ) def test_full_active_space(self, kwargs): """Test that transformer has no effect when all orbitals are active.""" driver = PySCFDriver() driver_result = driver.run() driver_result.hamiltonian.constants["FreezeCoreTransformer"] = 0.0 driver_result.properties.electronic_dipole_moment.constants["FreezeCoreTransformer"] = ( 0.0, 0.0, 0.0, ) trafo = FreezeCoreTransformer(**kwargs) driver_result_reduced = trafo.transform(driver_result) self.assertDriverResult(driver_result_reduced, driver_result) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_freeze_core(self): """Test the `freeze_core` convenience argument.""" driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.6") driver_result = driver.run() trafo = FreezeCoreTransformer(freeze_core=True) driver_result_reduced = trafo.transform(driver_result) expected = qcschema_to_problem( QCSchema.from_json( self.get_resource_path("LiH_sto3g_reduced.json", "second_q/transformers/resources") ), include_dipole=False, ) # add energy shift, which currently cannot be stored in the QCSchema expected.hamiltonian.constants["FreezeCoreTransformer"] = -7.796219568771229 self.assertDriverResult(driver_result_reduced, expected) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_freeze_core_with_remove_orbitals(self): """Test the `freeze_core` convenience argument in combination with `remove_orbitals`.""" driver = PySCFDriver(atom="Be 0 0 0; H 0 0 1.3", basis="sto3g", spin=1) driver_result = driver.run() trafo = FreezeCoreTransformer(freeze_core=True, remove_orbitals=[4, 5]) driver_result_reduced = trafo.transform(driver_result) expected = qcschema_to_problem( QCSchema.from_json( self.get_resource_path("BeH_sto3g_reduced.json", "second_q/transformers/resources") ), include_dipole=False, ) # add energy shift, which currently cannot be stored in the QCSchema expected.hamiltonian.constants["FreezeCoreTransformer"] = -14.253802923103054 self.assertDriverResult(driver_result_reduced, expected) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_no_freeze_core(self): """Test the disabled `freeze_core` convenience argument. Regression test against https://github.com/Qiskit/qiskit-nature/issues/652 """ driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.6") driver_result = driver.run() trafo = FreezeCoreTransformer(freeze_core=False) driver_result_reduced = trafo.transform(driver_result) electronic_energy = driver_result_reduced.hamiltonian electronic_energy_exp = driver_result.hamiltonian with self.subTest("MO 1-electron integrals"): np.testing.assert_array_almost_equal( np.abs(electronic_energy.electronic_integrals.second_q_coeffs()["+-"]), np.abs(electronic_energy_exp.electronic_integrals.second_q_coeffs()["+-"]), ) with self.subTest("MO 2-electron integrals"): actual_ints = electronic_energy.electronic_integrals.second_q_coeffs()["++--"] expected_ints = get_expected_two_body_ints( actual_ints, to_chemist_ordering( electronic_energy_exp.electronic_integrals.second_q_coeffs()["++--"] ), ) np.testing.assert_array_almost_equal( np.abs(actual_ints), np.abs(expected_ints), ) with self.subTest("Inactive energy"): self.assertAlmostEqual(electronic_energy.constants["FreezeCoreTransformer"], 0.0) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_freeze_core_with_charge(self): """Test the transformer behavior with a charge present.""" driver = PySCFDriver(atom="Be 0 0 0", charge=1, spin=1) driver_result = driver.run() self.assertEqual(driver_result.num_alpha, 2) self.assertEqual(driver_result.num_beta, 1) trafo = FreezeCoreTransformer(freeze_core=True) driver_result_reduced = trafo.transform(driver_result) self.assertEqual(driver_result_reduced.num_alpha, 1) self.assertEqual(driver_result_reduced.num_beta, 0) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_standalone_usage(self): """Test usage on a standalone Hamiltonian.""" driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.6") problem = driver.run() trafo = FreezeCoreTransformer() with self.subTest("prepare_active_space not called yet"): with self.assertRaises(QiskitNatureError): reduced_hamiltonian = trafo.transform_hamiltonian(problem.hamiltonian) trafo.prepare_active_space(problem.molecule, problem.num_spatial_orbitals) reduced_hamiltonian = trafo.transform_hamiltonian(problem.hamiltonian) expected = qcschema_to_problem( QCSchema.from_json( self.get_resource_path("LiH_sto3g_reduced.json", "second_q/transformers/resources") ), include_dipole=False, ) # add energy shift, which currently cannot be stored in the QCSchema expected.hamiltonian.constants["FreezeCoreTransformer"] = -7.796219568771229 self.assertElectronicEnergy(reduced_hamiltonian, expected.hamiltonian) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/transformers/test_freeze_core_transformer.py/0
{ "file_path": "qiskit-nature/test/second_q/transformers/test_freeze_core_transformer.py", "repo_id": "qiskit-nature", "token_count": 3089 }
151
.. _qiskit_optimization-converters: .. automodule:: qiskit_optimization.converters :no-members: :no-inherited-members: :no-special-members:
qiskit-optimization/docs/apidocs/qiskit_optimization.converters.rst/0
{ "file_path": "qiskit-optimization/docs/apidocs/qiskit_optimization.converters.rst", "repo_id": "qiskit-optimization", "token_count": 61 }
152
<jupyter_start><jupyter_text>Quadratic Programs Introduction In this tutorial, we briefly introduce how to build optimization problems using Qiskit optimization module.Qiskit optimization introduces the `QuadraticProgram` class to make a model of an optimization problem.More precisely, it deals with quadratically constrained quadratic programs given as follows:$$\begin{align}\text{minimize}\quad& x^\top Q_0 x + c^\top x\\\text{subject to}\quad& A x \leq b\\& x^\top Q_i x + a_i^\top x \leq r_i, \quad 1,\dots,i,\dots,q\\& l_i \leq x_i \leq u_i, \quad 1,\dots,i,\dots,n,\end{align}$$where the $Q_i$ are $n \times n$ matrices, $A$ is a $m \times n$ matrix , $x$, and $c$ are $n$-dimensional vectors, $b$ is an $m$-dimensional vector, and where $x$ can be defined as binary, integer, or continuous variables.In addition to "$\leq$" constraints `QuadraticProgram` also supports "$\geq$" and "$=$". Loading a `QuadraticProgram` from an LP file As setup, you need to import the following module.<jupyter_code>from qiskit_optimization import QuadraticProgram from qiskit_optimization.translators import from_docplex_mp<jupyter_output><empty_output><jupyter_text>You start with an empty model. How to add variables and constraints to a model is explained in the section [Directly constructing a QuadraticProgram](Directly-constructing-a-QuadraticProgram). Qiskit optimization module supports the conversion from Docplex model. You can easily make a model of an optimization problem with Docplex.You can find the documentation of Docplex at https://ibmdecisionoptimization.github.io/docplex-doc/mp/index.htmlYou can load a Docplex model to `QuadraticProgram` by using `from_docplex_mp` function. Loading a `QuadraticProgram` from a docplex model<jupyter_code># Make a Docplex model from docplex.mp.model import Model mdl = Model("docplex model") x = mdl.binary_var("x") y = mdl.integer_var(lb=-1, ub=5, name="y") mdl.minimize(x + 2 * y) mdl.add_constraint(x - y == 3) mdl.add_constraint((x + y) * (x - y) <= 1) print(mdl.export_as_lp_string())<jupyter_output>\ This file has been generated by DOcplex \ ENCODING=ISO-8859-1 \Problem name: docplex model Minimize obj: x + 2 y Subject To c1: x - y = 3 qc1: [ x^2 - y^2 ] <= 1 Bounds 0 <= x <= 1 -1 <= y <= 5 Binaries x Generals y End<jupyter_text>`QuadraticProgram` has a method `prettyprint` to generate a comprehensive string representation.<jupyter_code># load from a Docplex model mod = from_docplex_mp(mdl) print(type(mod)) print() print(mod.prettyprint())<jupyter_output><class 'qiskit_optimization.problems.quadratic_program.QuadraticProgram'> Problem name: docplex model Minimize x + 2*y Subject to Linear constraints (1) x - y == 3 'c0' Quadratic constraints (1) x^2 - y^2 <= 1 'q0' Integer variables (1) -1 <= y <= 5 Binary variables (1) x<jupyter_text>Directly constructing a `QuadraticProgram` We then explain how to make model of an optimization problem directly using `QuadraticProgram`.Let's start from an empty model.<jupyter_code># make an empty problem mod = QuadraticProgram("my problem") print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 0 Subject to No constraints No variables<jupyter_text>The `QuadraticProgram` supports three types of variables:- Binary variable- Integer variable- Continuous variableWhen you add variables, you can specify names, types, lower bounds and upper bounds.<jupyter_code># Add variables mod.binary_var(name="x") mod.integer_var(name="y", lowerbound=-1, upperbound=5) mod.continuous_var(name="z", lowerbound=-1, upperbound=5) print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 0 Subject to No constraints Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>You can set the objective function by invoking `QuadraticProgram.minimize` or `QuadraticProgram.maximize`.You can add a constant term as well as linear and quadratic objective function by specifying linear and quadratic terms with either list, matrix or dictionary.Note that in the LP format the quadratic part has to be scaled by a factor $1/2$.Thus, when printing as LP format, the quadratic part is first multiplied by 2 and then divided by 2 again.For quadratic programs, there are 3 pieces that have to be specified: a constant (offset), a linear term ($c^{T}x$), and a quadratic term ($x^{T}Qx$).The cell below shows how to declare an objective function using a dictionary. For the linear term, keys in the dictionary correspond to variable names, and the corresponding values are the coefficients. For the quadratic term, keys in the dictionary correspond to the two variables being multiplied, and the values are again the coefficients.<jupyter_code># Add objective function using dictionaries mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1}) print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 2*x*y - z^2 + x + 3 Subject to No constraints Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>Another way to specify the quadratic program is using arrays. For the linear term, the array corresponds to the vector $c$ in the mathematical formulation. For the quadratic term, the array corresponds to the matrix $Q$. Note that the ordering of the variables ($x$ in the mathematical formulation) is the order in which the variables were originally declared in the `QuadraticProgram` object.<jupyter_code># Add objective function using lists/arrays mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]]) print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 2*x*y - z^2 + x + 3 Subject to No constraints Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>You can access the constant, the linear term, and the quadratic term by looking at `Quadratic.objective.{constant, linear, quadratic}`, respectively.As for linear and quadratic terms, you can get a dense matrix (`to_array`), a sparse matrix (`coefficients`), and a dictionary (`to_dict`).For dictionaries, you can specify whether to use variable indices or names as keys.Note that the quadratic terms are stored in a compressed way, e.g., `{('x', 'y'): 1, ('y', 'x'): 2}` is stored as `{('x', 'y'): 3}`.You can get the quadratic term as a symmetric matrix by calling `to_array(symmetric=True)` or `to_dict(symmetric=True)`.If you call `to_dict(name=True)`, you can get a dictionary whose keys are pairs of variable names.<jupyter_code>print("constant:\t\t\t", mod.objective.constant) print("linear dict:\t\t\t", mod.objective.linear.to_dict()) print("linear array:\t\t\t", mod.objective.linear.to_array()) print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n") print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict()) print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True)) print( "symmetric quadratic dict w/ name:\t", mod.objective.quadratic.to_dict(use_name=True, symmetric=True), ) print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n") print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n") print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)<jupyter_output>constant: 3 linear dict: {0: 1} linear array: [1 0 0] linear array as sparse matrix: (0, 0) 1 quadratic dict w/ index: {(0, 1): 2, (2, 2): -1} quadratic dict w/ name: {('x', 'y'): 2, ('z', 'z'): -1} symmetric quadratic dict w/ name: {('y', 'x'): 1, ('x', 'y'): 1, ('z', 'z'): -1} quadratic matrix: [[ 0 2 0] [ 0 0 0] [ 0 0 -1]] symmetric quadratic matrix: [[ 0 1 0] [ 1 0 0] [ 0 0 -1]] quadratic matrix as sparse matrix: (0, 1) 2 (2, 2) -1<jupyter_text>Adding/removing linear and quadratic constraints You can add linear constraints by setting name, linear expression, sense and right-hand-side value (rhs).You can use senses 'EQ', 'LE', and 'GE' as Docplex supports.<jupyter_code># Add linear constraints mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq") print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 2*x*y - z^2 + x + 3 Subject to Linear constraints (3) x + 2*y == 3 'lin_eq' x + 2*y <= 3 'lin_leq' x + 2*y >= 3 'lin_geq' Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>You can add quadratic constraints as well as objective function and linear constraints.<jupyter_code># Add quadratic constraints mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="==", rhs=1, name="quad_eq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="<=", rhs=1, name="quad_leq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense=">=", rhs=1, name="quad_geq", ) print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 2*x*y - z^2 + x + 3 Subject to Linear constraints (3) x + 2*y == 3 'lin_eq' x + 2*y <= 3 'lin_leq' x + 2*y >= 3 'lin_geq' Quadratic constraints (3) x^2 - y*z + x + y == 1 'quad_eq' x^2 - y*z + x + y <= 1 'quad_leq' x^2 - y*z + x + y >= 1 'quad_geq' Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>You can access linear and quadratic terms of linear and quadratic constraints as in the same way as the objective function.<jupyter_code>lin_geq = mod.get_linear_constraint("lin_geq") print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs) quad_geq = mod.get_quadratic_constraint("quad_geq") print( "quad_geq:", quad_geq.linear.to_dict(use_name=True), quad_geq.quadratic.to_dict(use_name=True), quad_geq.sense, lin_geq.rhs, )<jupyter_output>lin_geq: {'x': 1.0, 'y': 2.0} ConstraintSense.GE 3 quad_geq: {'x': 1.0, 'y': 1.0} {('x', 'x'): 1.0, ('y', 'z'): -1.0} ConstraintSense.GE 3<jupyter_text>You can also remove linear/quadratic constraints by `remove_linear_constraint` and `remove_quadratic_constraint`.<jupyter_code># Remove constraints mod.remove_linear_constraint("lin_eq") mod.remove_quadratic_constraint("quad_leq") print(mod.prettyprint())<jupyter_output>Problem name: my problem Minimize 2*x*y - z^2 + x + 3 Subject to Linear constraints (2) x + 2*y <= 3 'lin_leq' x + 2*y >= 3 'lin_geq' Quadratic constraints (2) x^2 - y*z + x + y == 1 'quad_eq' x^2 - y*z + x + y >= 1 'quad_geq' Integer variables (1) -1 <= y <= 5 Continuous variables (1) -1 <= z <= 5 Binary variables (1) x<jupyter_text>You can substitute some of variables with constants or other variables.More precisely, `QuadraticProgram` has a method `substitute_variables(constants=..., variables=...)` to deal with the following two cases.- $x \leftarrow c$: when `constants` have a dictionary `{x: c}`. - $x \leftarrow c y$: when `variables` have a dictionary `{x: (y, c)}`. Substituting Variables<jupyter_code>sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)}) print(sub.prettyprint())<jupyter_output>Problem name: my problem Minimize -z^2 + 3 Subject to Linear constraints (2) -2*z <= 3 'lin_leq' -2*z >= 3 'lin_geq' Quadratic constraints (2) z^2 - z == 1 'quad_eq' z^2 - z >= 1 'quad_geq' Continuous variables (1) -1 <= z <= 1<jupyter_text>If the resulting problem is infeasible due to lower bounds or upper bounds, the methods returns the status `Status.INFEASIBLE`.We try to replace variable `x` with -1, but -1 is out of range of `x` (0 <= `x` <= 1). So, it returns `Status.INFEASIBLE`.<jupyter_code>sub = mod.substitute_variables(constants={"x": -1}) print(sub.status)<jupyter_output>Infeasible substitution for variable: x<jupyter_text>You cannot substitute variables multiple times. The method raises an error in such a case.<jupyter_code>from qiskit_optimization import QiskitOptimizationError try: sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)}) except QiskitOptimizationError as e: print("Error: {}".format(e))<jupyter_output>Error: 'Cannot substitute by variable that gets substituted itself: y <- x 1'<jupyter_text>Note:When you display your problem as LP format using `export_as_lp_string`,`Binaries` denotes binary variables and `Generals` denotes integer variables.If variables are not included in either `Binaries` or `Generals`, such variables are continuous ones with default lower bound = 0 and upper bound = infinity.Note that you cannot use 'e' or 'E' as the first character of names due to the [specification of LP format](https://www.ibm.com/docs/en/icos/22.1.0?topic=representation-variable-names-in-lp-file-format).<jupyter_code>mod = QuadraticProgram() mod.binary_var(name="e") mod.binary_var(name="f") mod.continuous_var(name="g") mod.minimize(linear=[1, 2, 3]) print(mod.export_as_lp_string()) import tutorial_magics %qiskit_version_table %qiskit_copyright<jupyter_output><empty_output>
qiskit-optimization/docs/tutorials/01_quadratic_program.ipynb/0
{ "file_path": "qiskit-optimization/docs/tutorials/01_quadratic_program.ipynb", "repo_id": "qiskit-optimization", "token_count": 4915 }
153
\Problem name: my problem Minimize obj: x - y + 10 z + [ x ^2 - 2 y * z ] / 2 Subject To lin_eq: x + 2 y = 1 lin_leq: x + 2 y <= 1 lin_geq: x + 2 y >= 1 quad_eq: x + y + [ x ^2 - y * z + 2 z ^2 ] = 1 quad_leq: x + y + [ x ^2 - y * z + 2 z ^2 ] <= 1 quad_geq: x + y + [ x ^2 - y * z + 2 z ^2 ] >= 1 Bounds 0 <= x <= 1 -1 <= y <= 5 -1 <= z <= 5 Binaries x Generals y End
qiskit-optimization/docs/tutorials/aux_files/sample.lp/0
{ "file_path": "qiskit-optimization/docs/tutorials/aux_files/sample.lp", "repo_id": "qiskit-optimization", "token_count": 190 }
154
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An abstract class for optimization algorithms in Qiskit optimization module.""" from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from enum import Enum from logging import getLogger from typing import Any, Dict, List, Tuple, Type, Union, cast import numpy as np from qiskit.quantum_info import Statevector from qiskit.result import QuasiDistribution from ..converters.quadratic_program_to_qubo import QuadraticProgramConverter, QuadraticProgramToQubo from ..exceptions import QiskitOptimizationError from ..problems.quadratic_program import QuadraticProgram, Variable logger = getLogger(__name__) class OptimizationResultStatus(Enum): """Termination status of an optimization algorithm.""" SUCCESS = 0 """the optimization algorithm succeeded to find a feasible solution.""" FAILURE = 1 """the optimization algorithm ended in a failure.""" INFEASIBLE = 2 """the optimization algorithm obtained an infeasible solution.""" @dataclass class SolutionSample: """A sample of an optimization solution.""" x: np.ndarray """The values of the variables""" fval: float """The objective function value""" probability: float """The probability of this sample""" status: OptimizationResultStatus """The status of this sample""" class OptimizationResult: """A base class for optimization results. The optimization algorithms return an object of the type ``OptimizationResult`` with the information about the solution obtained. ``OptimizationResult`` allows users to get the value of a variable by specifying an index or a name as follows. Examples: >>> from qiskit_optimization import QuadraticProgram >>> from qiskit_optimization.algorithms import CplexOptimizer >>> problem = QuadraticProgram() >>> _ = problem.binary_var('x1') >>> _ = problem.binary_var('x2') >>> _ = problem.binary_var('x3') >>> problem.minimize(linear={'x1': 1, 'x2': -2, 'x3': 3}) >>> print([var.name for var in problem.variables]) ['x1', 'x2', 'x3'] >>> optimizer = CplexOptimizer() >>> result = optimizer.solve(problem) >>> print(result.variable_names) ['x1', 'x2', 'x3'] >>> print(result.x) [0. 1. 0.] >>> print(result[1]) 1.0 >>> print(result['x1']) 0.0 >>> print(result.fval) -2.0 >>> print(result.variables_dict) {'x1': 0.0, 'x2': 1.0, 'x3': 0.0} Note: The order of variables should be equal to that of the problem solved by optimization algorithms. Optimization algorithms and converters of ``QuadraticProgram`` should maintain the order when generating a new ``OptimizationResult`` object. """ def __init__( self, x: Union[List[float], np.ndarray] | None, fval: float | None, variables: List[Variable], status: OptimizationResultStatus, raw_results: Any | None = None, samples: List[SolutionSample] | None = None, ) -> None: """ Args: x: the variable values found in the optimization, or possibly None in case of FAILURE. fval: the objective function value. variables: the list of variables of the optimization problem. raw_results: the original results object from the optimization algorithm. status: the termination status of the optimization algorithm. samples: the solution samples. Raises: QiskitOptimizationError: if sizes of ``x`` and ``variables`` do not match. """ self._variables = variables self._variable_names = [var.name for var in self._variables] if x is None: # if no state is given, it is set to None self._x = None # pylint: disable=invalid-name self._variables_dict = None else: if len(x) != len(variables): raise QiskitOptimizationError( f"Inconsistent size of variable values (x) and variables. x: size {len(x)} {x}, " f"variables: size {len(variables)} {[v.name for v in variables]}" ) self._x = np.asarray(x) self._variables_dict = dict(zip(self._variable_names, self._x)) self._fval = fval self._raw_results = raw_results self._status = status if samples: sum_prob = np.sum([e.probability for e in samples]) if not np.isclose(sum_prob, 1.0): logger.debug("The sum of probability of samples is not close to 1: %f", sum_prob) self._samples = samples else: self._samples = [ SolutionSample(x=cast(np.ndarray, x), fval=fval, status=status, probability=1.0) ] def __repr__(self) -> str: return f"<{self.__class__.__name__}: {str(self)}>" def __str__(self) -> str: variables = ", ".join([f"{var}={x}" for var, x in self._variables_dict.items()]) return f"fval={self._fval}, {variables}, status={self._status.name}" def prettyprint(self) -> str: """Returns a pretty printed string of this optimization result. Returns: A pretty printed string representing the result. """ variables = ", ".join([f"{var}={x}" for var, x in self._variables_dict.items()]) return ( f"objective function value: {self._fval}\n" f"variable values: {variables}\n" f"status: {self._status.name}" ) def __getitem__(self, key: Union[int, str]) -> float: """Returns the value of the variable whose index or name is equal to ``key``. The key can be an integer or a string. If the key is an integer, this methods returns the value of the variable whose index is equal to ``key``. If the key is a string, this methods return the value of the variable whose name is equal to ``key``. Args: key: an integer or a string. Returns: The value of a variable whose index or name is equal to ``key``. Raises: IndexError: if ``key`` is an integer and is out of range of the variables. KeyError: if ``key`` is a string and none of the variables has ``key`` as name. TypeError: if ``key`` is neither an integer nor a string. """ if isinstance(key, int): return self._x[key] if isinstance(key, str): return self._variables_dict[key] raise TypeError(f"Integer or string key required, instead {type(key)}({key}) provided.") def get_correlations(self) -> np.ndarray: """ Get <Zi x Zj> correlation matrix from the samples. Returns: A correlation matrix. """ states = [v.x for v in self.samples] probs = [v.probability for v in self.samples] n = len(states[0]) correlations = np.zeros((n, n)) for k, prob in enumerate(probs): b = states[k] for i in range(n): for j in range(i): if b[i] == b[j]: correlations[i, j] += prob else: correlations[i, j] -= prob return correlations @property def x(self) -> np.ndarray | None: """Returns the variable values found in the optimization or None in case of FAILURE. Returns: The variable values found in the optimization. """ return self._x @property def fval(self) -> float | None: """Returns the objective function value. Returns: The function value corresponding to the objective function value found in the optimization. """ return self._fval @property def raw_results(self) -> Any: """Return the original results object from the optimization algorithm. Currently a dump for any leftovers. Returns: Additional result information of the optimization algorithm. """ return self._raw_results @property def status(self) -> OptimizationResultStatus: """Returns the termination status of the optimization algorithm. Returns: The termination status of the algorithm. """ return self._status @property def variables(self) -> List[Variable]: """Returns the list of variables of the optimization problem. Returns: The list of variables. """ return self._variables @property def variables_dict(self) -> Dict[str, float]: """Returns the variable values as a dictionary of the variable name and corresponding value. Returns: The variable values as a dictionary of the variable name and corresponding value. """ return self._variables_dict @property def variable_names(self) -> List[str]: """Returns the list of variable names of the optimization problem. Returns: The list of variable names of the optimization problem. """ return self._variable_names @property def samples(self) -> List[SolutionSample]: """Returns the list of solution samples Returns: The list of solution samples. """ return self._samples class OptimizationAlgorithm(ABC): """An abstract class for optimization algorithms in Qiskit optimization module.""" _MIN_PROBABILITY = 1e-6 @abstractmethod def get_compatibility_msg(self, problem: QuadraticProgram) -> str: """Checks whether a given problem can be solved with the optimizer implementing this method. Args: problem: The optimization problem to check compatibility. Returns: Returns the incompatibility message. If the message is empty no issues were found. """ def is_compatible(self, problem: QuadraticProgram) -> bool: """Checks whether a given problem can be solved with the optimizer implementing this method. Args: problem: The optimization problem to check compatibility. Returns: Returns True if the problem is compatible, False otherwise. """ return len(self.get_compatibility_msg(problem)) == 0 @abstractmethod def solve(self, problem: QuadraticProgram) -> "OptimizationResult": """Tries to solves the given problem using the optimizer. Runs the optimizer to try to solve the optimization problem. Args: problem: The problem to be solved. Returns: The result of the optimizer applied to the problem. Raises: QiskitOptimizationError: If the problem is incompatible with the optimizer. """ raise NotImplementedError def _verify_compatibility(self, problem: QuadraticProgram) -> None: """Verifies that the problem is suitable for this optimizer. If the problem is not compatible then an exception is raised. This method is for convenience for concrete optimizers and is not intended to be used by end user. Args: problem: Problem to verify. Returns: None Raises: QiskitOptimizationError: If the problem is incompatible with the optimizer. """ # check compatibility and raise exception if incompatible msg = self.get_compatibility_msg(problem) if msg: raise QiskitOptimizationError(f"Incompatible problem: {msg}") @staticmethod def _get_feasibility_status( problem: QuadraticProgram, x: Union[List[float], np.ndarray] ) -> OptimizationResultStatus: """Returns whether the input result is feasible or not for the given problem. Args: problem: Problem to verify. x: the input result list. Returns: The status of the result. """ is_feasible = problem.is_feasible(x) return ( OptimizationResultStatus.SUCCESS if is_feasible else OptimizationResultStatus.INFEASIBLE ) @staticmethod def _prepare_converters( converters: Union[QuadraticProgramConverter, List[QuadraticProgramConverter]] | None, penalty: float | None = None, ) -> List[QuadraticProgramConverter]: """Prepare a list of converters from the input. Args: converters: The converters to use for converting a problem into a different form. By default, when None is specified, an internally created instance of :class:`~qiskit_optimization.converters.QuadraticProgramToQubo` will be used. penalty: The penalty factor used in the default :class:`~qiskit_optimization.converters.QuadraticProgramToQubo` converter Returns: The list of converters. Raises: TypeError: When the converters include those that are not :class:`~qiskit_optimization.converters.QuadraticProgramConverter type. """ if converters is None: return [QuadraticProgramToQubo(penalty=penalty)] elif isinstance(converters, QuadraticProgramConverter): return [converters] elif isinstance(converters, list) and all( isinstance(converter, QuadraticProgramConverter) for converter in converters ): return converters else: raise TypeError("`converters` must all be of the QuadraticProgramConverter type") @staticmethod def _convert( problem: QuadraticProgram, converters: Union[QuadraticProgramConverter, List[QuadraticProgramConverter]], ) -> QuadraticProgram: """Convert the problem with the converters Args: problem: The problem to be solved converters: The converters to use for converting a problem into a different form. Returns: The problem converted by the converters. """ problem_ = problem if not isinstance(converters, list): converters = [converters] for converter in converters: problem_ = converter.convert(problem_) return problem_ @staticmethod def _check_converters( converters: Union[QuadraticProgramConverter, List[QuadraticProgramConverter]] | None, ) -> List[QuadraticProgramConverter]: if converters is None: converters = [] if not isinstance(converters, list): converters = [converters] if not all(isinstance(conv, QuadraticProgramConverter) for conv in converters): raise TypeError(f"Invalid object of converters: {converters}") return converters @classmethod def _interpret( cls, x: np.ndarray, problem: QuadraticProgram, converters: Union[QuadraticProgramConverter, List[QuadraticProgramConverter]] | None = None, result_class: Type[OptimizationResult] = OptimizationResult, **kwargs, ) -> OptimizationResult: """Convert back the result of the converted problem to the result of the original problem. Args: x: The result of the converted problem. converters: The converters to use for converting back the result of the problem to the result of the original problem. problem: The original problem for which `x` is interpreted. result_class: The class of the result object. kwargs: parameters of the constructor of result_class Returns: The result of the original problem. Raises: QiskitOptimizationError: if result_class is not a sub-class of OptimizationResult. TypeError: if converters are not QuadraticProgramConverter or a list of QuadraticProgramConverter. """ if not issubclass(result_class, OptimizationResult): raise QiskitOptimizationError( f"Invalid result class, not derived from OptimizationResult: {result_class}" ) converters = cls._check_converters(converters) for converter in converters[::-1]: x = converter.interpret(x) return result_class( x=x, fval=problem.objective.evaluate(x), variables=problem.variables, status=cls._get_feasibility_status(problem, x), **kwargs, ) @classmethod def _interpret_samples( cls, problem: QuadraticProgram, raw_samples: List[SolutionSample], converters: QuadraticProgramConverter | list[QuadraticProgramConverter] | None = None, ) -> Tuple[List[SolutionSample], SolutionSample]: """Interpret and sort all samples and return the raw sample corresponding to the best one""" converters = cls._check_converters(converters) prob: Dict[Tuple, float] = {} array = {} index = {} for i, sample in enumerate(raw_samples): x = sample.x for converter in converters[::-1]: x = converter.interpret(x) key = tuple(x) prob[key] = prob.get(key, 0.0) + sample.probability array[key] = x index[key] = i samples = [] for key, x in array.items(): probability = prob[key] fval = problem.objective.evaluate(x) status = cls._get_feasibility_status(problem, x) samples.append(SolutionSample(x, fval, probability, status)) sorted_samples = sorted( samples, key=lambda v: (v.status.value, problem.objective.sense.value * v.fval), ) best_raw = raw_samples[index[tuple(sorted_samples[0].x)]] return sorted_samples, best_raw @staticmethod def _eigenvector_to_solutions( eigenvector: Union[QuasiDistribution, Statevector, dict, np.ndarray], qubo: QuadraticProgram, min_probability: float = _MIN_PROBABILITY, ) -> List[SolutionSample]: """Convert the eigenvector to the bitstrings and corresponding eigenvalues. Args: eigenvector: The eigenvector from which the solution states are extracted. qubo: The QUBO to evaluate at the bitstring. min_probability: Only consider states where the amplitude exceeds this threshold. Returns: For each computational basis state contained in the eigenvector, return the basis state as bitstring along with the QUBO evaluated at that bitstring and the probability of sampling this bitstring from the eigenvector. Raises: TypeError: If the type of eigenvector is not supported. """ def generate_solution(bitstr, qubo, probability): x = np.fromiter(list(bitstr[::-1]), dtype=int) fval = qubo.objective.evaluate(x) return SolutionSample( x=x, fval=fval, probability=probability, status=OptimizationResultStatus.SUCCESS, ) solutions = [] if isinstance(eigenvector, QuasiDistribution): probabilities = eigenvector.binary_probabilities() # iterate over all samples for bitstr, sampling_probability in probabilities.items(): # add the bitstring, if the sampling probability exceeds the threshold if sampling_probability >= min_probability: solutions.append(generate_solution(bitstr, qubo, sampling_probability)) elif isinstance(eigenvector, Statevector): probabilities = eigenvector.probabilities() num_qubits = eigenvector.num_qubits # iterate over all states and their sampling probabilities for i, sampling_probability in enumerate(probabilities): # add the i-th state if the sampling probability exceeds the threshold if sampling_probability >= min_probability: bitstr = f"{i:b}".rjust(num_qubits, "0") solutions.append(generate_solution(bitstr, qubo, sampling_probability)) elif isinstance(eigenvector, dict): # When eigenvector is a dict, square the values since the values are normalized. # See https://github.com/Qiskit/qiskit-terra/pull/5496 for more details. probabilities = {bitstr: val**2 for (bitstr, val) in eigenvector.items()} # iterate over all samples for bitstr, sampling_probability in probabilities.items(): # add the bitstring, if the sampling probability exceeds the threshold if sampling_probability >= min_probability: solutions.append(generate_solution(bitstr, qubo, sampling_probability)) elif isinstance(eigenvector, np.ndarray): num_qubits = int(np.log2(eigenvector.size)) probabilities = np.abs(eigenvector * eigenvector.conj()) # iterate over all states and their sampling probabilities for i, sampling_probability in enumerate(probabilities): # add the i-th state if the sampling probability exceeds the threshold if sampling_probability >= min_probability: bitstr = f"{i:b}".rjust(num_qubits, "0") solutions.append(generate_solution(bitstr, qubo, sampling_probability)) else: raise TypeError( f"Eigenvector should be QuasiDistribution, Statevector, dict or numpy.ndarray. " f"But, it was {type(eigenvector)}." ) return solutions
qiskit-optimization/qiskit_optimization/algorithms/optimization_algorithm.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/algorithms/optimization_algorithm.py", "repo_id": "qiskit-optimization", "token_count": 9169 }
155
# This code is part of a Qiskit project. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An abstract class for graph optimization application classes.""" from abc import abstractmethod from typing import Dict, List, Optional, Union import networkx as nx import numpy as np import qiskit_optimization.optionals as _optionals from ..algorithms import OptimizationResult from .optimization_application import OptimizationApplication class GraphOptimizationApplication(OptimizationApplication): """ An abstract class for graph optimization applications. """ def __init__(self, graph: Union[nx.Graph, np.ndarray, List]) -> None: """ Args: graph: A graph representing a problem. It can be specified directly as a `NetworkX <https://networkx.org/>`_ graph, or as an array or list format suitable to build out a NetworkX graph. """ # The view of the graph is stored which means the graph can not be changed. self._graph = nx.Graph(graph).copy(as_view=True) @_optionals.HAS_MATPLOTLIB.require_in_call def draw( self, result: Optional[Union[OptimizationResult, np.ndarray]] = None, pos: Optional[Dict[int, np.ndarray]] = None, ) -> None: """Draw a graph with the result. When the result is None, draw an original graph without colors. Args: result: The calculated result for the problem pos: The positions of nodes """ if result is None: nx.draw(self._graph, pos=pos, with_labels=True) else: self._draw_result(result, pos) @abstractmethod def _draw_result( self, result: Union[OptimizationResult, np.ndarray], pos: Optional[Dict[int, np.ndarray]] = None, ) -> None: """Draw the result with colors Args: result : The calculated result for the problem pos: The positions of nodes """ pass @property def graph(self) -> nx.Graph: """Getter of the graph Returns: A graph for a problem """ return self._graph
qiskit-optimization/qiskit_optimization/applications/graph_optimization_application.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/applications/graph_optimization_application.py", "repo_id": "qiskit-optimization", "token_count": 973 }
156
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Converter to convert a problem with equality constraints to unconstrained with penalty terms.""" import logging from typing import Optional, cast, Union, Tuple, List import numpy as np from .quadratic_program_converter import QuadraticProgramConverter from ..exceptions import QiskitOptimizationError from ..problems.constraint import Constraint from ..problems.quadratic_objective import QuadraticObjective from ..problems.quadratic_program import QuadraticProgram from ..problems.variable import Variable logger = logging.getLogger(__name__) class LinearEqualityToPenalty(QuadraticProgramConverter): """Convert a problem with only equality constraints to unconstrained with penalty terms.""" def __init__(self, penalty: Optional[float] = None) -> None: """ Args: penalty: Penalty factor to scale equality constraints that are added to objective. If None is passed, a penalty factor will be automatically calculated on every conversion. """ self._src_num_vars: Optional[int] = None self._penalty: Optional[float] = penalty self._should_define_penalty: bool = penalty is None def convert(self, problem: QuadraticProgram) -> QuadraticProgram: """Convert a problem with equality constraints into an unconstrained problem. Args: problem: The problem to be solved, that does not contain inequality constraints. Returns: The converted problem, that is an unconstrained problem. Raises: QiskitOptimizationError: If an inequality constraint exists. """ # create empty QuadraticProgram model self._src_num_vars = problem.get_num_vars() dst = QuadraticProgram(name=problem.name) # If no penalty was given, set the penalty coefficient by _auto_define_penalty() if self._should_define_penalty: penalty = self._auto_define_penalty(problem) else: penalty = self._penalty # Set variables for x in problem.variables: if x.vartype == Variable.Type.CONTINUOUS: dst.continuous_var(x.lowerbound, x.upperbound, x.name) elif x.vartype == Variable.Type.BINARY: dst.binary_var(x.name) elif x.vartype == Variable.Type.INTEGER: dst.integer_var(x.lowerbound, x.upperbound, x.name) else: raise QiskitOptimizationError(f"Unsupported vartype: {x.vartype}") # get original objective terms offset = problem.objective.constant linear = problem.objective.linear.to_dict() quadratic = problem.objective.quadratic.to_dict() sense = problem.objective.sense.value # convert linear constraints into penalty terms for constraint in problem.linear_constraints: if constraint.sense != Constraint.Sense.EQ: raise QiskitOptimizationError( "An inequality constraint exists. " "The method supports only equality constraints." ) constant = constraint.rhs row = constraint.linear.to_dict() # constant parts of penalty*(Constant-func)**2: penalty*(Constant**2) offset += sense * penalty * constant**2 # linear parts of penalty*(Constant-func)**2: penalty*(-2*Constant*func) for j, coef in row.items(): # if j already exists in the linear terms dic, add a penalty term # into existing value else create new key and value in the linear_term dict linear[j] = linear.get(j, 0.0) + sense * penalty * -2 * coef * constant # quadratic parts of penalty*(Constant-func)**2: penalty*(func**2) for j, coef_1 in row.items(): for k, coef_2 in row.items(): # if j and k already exist in the quadratic terms dict, # add a penalty term into existing value # else create new key and value in the quadratic term dict # according to implementation of quadratic terms in OptimizationModel, # don't need to multiply by 2, since loops run over (x, y) and (y, x). tup = cast(Union[Tuple[int, int], Tuple[str, str]], (j, k)) quadratic[tup] = quadratic.get(tup, 0.0) + sense * penalty * coef_1 * coef_2 if problem.objective.sense == QuadraticObjective.Sense.MINIMIZE: dst.minimize(offset, linear, quadratic) else: dst.maximize(offset, linear, quadratic) # Update the penalty to the one just used self._penalty = penalty return dst @staticmethod def _auto_define_penalty(problem: QuadraticProgram) -> float: """Automatically define the penalty coefficient. Returns: Return the minimum valid penalty factor calculated from the upper bound and the lower bound of the objective function. If a constraint has a float coefficient, return the default value for the penalty factor. """ default_penalty = 1e5 # Check coefficients of constraints. # If a constraint has a float coefficient, return the default value for the penalty factor. terms = [] for constraint in problem.linear_constraints: terms.append(constraint.rhs) terms.extend(constraint.linear.to_array().tolist()) if any(isinstance(term, float) and not term.is_integer() for term in terms): logger.warning( "Warning: Using %f for the penalty coefficient because " "a float coefficient exists in constraints. \n" "The value could be too small. " "If so, set the penalty coefficient manually.", default_penalty, ) return default_penalty lin_b = problem.objective.linear.bounds quad_b = problem.objective.quadratic.bounds return 1.0 + (lin_b.upperbound - lin_b.lowerbound) + (quad_b.upperbound - quad_b.lowerbound) def interpret(self, x: Union[np.ndarray, List[float]]) -> np.ndarray: """Convert the result of the converted problem back to that of the original problem Args: x: The result of the converted problem or the given result in case of FAILURE. Returns: The result of the original problem. Raises: QiskitOptimizationError: if the number of variables in the result differs from that of the original problem. """ if len(x) != self._src_num_vars: raise QiskitOptimizationError( "The number of variables in the passed result differs from " "that of the original problem." ) return np.asarray(x) @property def penalty(self) -> Optional[float]: """Returns the penalty factor used in conversion. Returns: The penalty factor used in conversion. """ return self._penalty @penalty.setter def penalty(self, penalty: Optional[float]) -> None: """Set a new penalty factor. Args: penalty: The new penalty factor. If None is passed, a penalty factor will be automatically calculated on every conversion. """ self._penalty = penalty self._should_define_penalty = penalty is None
qiskit-optimization/qiskit_optimization/converters/linear_equality_to_penalty.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/converters/linear_equality_to_penalty.py", "repo_id": "qiskit-optimization", "token_count": 3307 }
157
# This code is part of a Qiskit project. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Substitute variables of QuadraticProgram.""" import logging from collections import defaultdict from dataclasses import dataclass from math import isclose from typing import Dict, Optional, Tuple, Union, cast from ..exceptions import QiskitOptimizationError from ..infinity import INFINITY from .constraint import ConstraintSense from .linear_expression import LinearExpression from .quadratic_expression import QuadraticExpression from .quadratic_program import QuadraticProgram logger = logging.getLogger(__name__) @dataclass class SubstitutionExpression: """Represents a substitution of a variable with a linear expression. If ``variable`` is ``None``, it substitutes a variable with the constant value. Otherwise, it substitutes a variable with (``constant + coefficient * new_variable``). """ const: float = 0.0 """Constant value""" coeff: float = 0.0 """Coefficient of the new variable""" variable: Optional[str] = None """Variable name or `None`""" def substitute_variables( quadratic_program: QuadraticProgram, constants: Optional[Dict[Union[str, int], float]] = None, variables: Optional[Dict[Union[str, int], Tuple[Union[str, int], float]]] = None, ) -> QuadraticProgram: """Substitutes variables with constants or other variables. Args: quadratic_program: a quadratic program whose variables are substituted. constants: replace variable by constant e.g., ``{'x': 2}`` means ``x`` is substituted with 2 variables: replace variables by weighted other variable need to copy everything using name reference to make sure that indices are matched correctly. The lower and upper bounds are updated accordingly. e.g., ``{'x': ('y', 2)}`` means ``x`` is substituted with ``y`` * 2 Returns: An optimization problem by substituting variables with constants or other variables. If the substitution is valid, ``QuadraticProgram.status`` is still ``QuadraticProgram.Status.VALID``. Otherwise, it gets ``QuadraticProgram.Status.INFEASIBLE``. Raises: QiskitOptimizationError: if the substitution is invalid as follows. - Same variable is substituted multiple times. - Coefficient of variable substitution is zero. """ # guarantee that there is no overlap between variables to be replaced and combine input subs = {} if constants: for i, v in constants.items(): # substitute i <- v i_2 = quadratic_program.get_variable(i).name if i_2 in subs: raise QiskitOptimizationError( f"Cannot substitute the same variable twice: {i} <- {v}" ) subs[i_2] = SubstitutionExpression(const=v) if variables: for i, (j, v) in variables.items(): if v == 0: raise QiskitOptimizationError(f"coefficient must be non-zero: {i} {j} {v}") # substitute i <- j * v i_2 = quadratic_program.get_variable(i).name j_2 = quadratic_program.get_variable(j).name if i_2 == j_2: raise QiskitOptimizationError( f"Cannot substitute the same variable: {i} <- {j} {v}" ) if i_2 in subs: raise QiskitOptimizationError( f"Cannot substitute the same variable twice: {i} <- {j} {v}" ) if j_2 in subs: raise QiskitOptimizationError( "Cannot substitute by variable that gets substituted itself: " f"{i} <- {j} {v}" ) subs[i_2] = SubstitutionExpression(variable=j_2, coeff=v) return _SubstituteVariables().substitute_variables(quadratic_program, subs) class _SubstituteVariables: """A class to substitute variables of an optimization problem with constants for other variables""" def __init__(self) -> None: self._src: Optional[QuadraticProgram] = None self._dst: Optional[QuadraticProgram] = None self._subs: Dict[str, SubstitutionExpression] = {} def substitute_variables( self, quadratic_program: QuadraticProgram, subs: Dict[str, SubstitutionExpression] ) -> QuadraticProgram: """Substitutes variables with constants or other variables. Args: quadratic_program: a quadratic program whose variables are substituted. subs: substitution expressions as a dictionary. e.g., {'x': SubstitutionExpression(const=1, coeff=2, variable='y'} means `x` is substituted with `1 + 2 * y`. Returns: An optimization problem by substituting variables with constants or other variables. If the substitution is valid, `QuadraticProgram.status` is still `QuadraticProgram.Status.VALID`. Otherwise, it gets `QuadraticProgram.Status.INFEASIBLE`. """ self._src = quadratic_program self._dst = QuadraticProgram(quadratic_program.name) self._subs = subs results = [ self._variables(), self._objective(), self._linear_constraints(), self._quadratic_constraints(), ] if not all(results): self._dst._status = QuadraticProgram.Status.INFEASIBLE return self._dst @staticmethod def _feasible(sense: ConstraintSense, rhs: float) -> bool: """Checks feasibility of the following condition 0 `sense` rhs """ if sense == ConstraintSense.EQ: if rhs == 0: return True elif sense == ConstraintSense.LE: if rhs >= 0: return True elif sense == ConstraintSense.GE: if rhs <= 0: return True return False def _variables(self) -> bool: # copy variables that are not replaced feasible = True for var in self._src.variables: name = var.name vartype = var.vartype lowerbound = var.lowerbound upperbound = var.upperbound if name not in self._subs: self._dst._add_variable(lowerbound, upperbound, vartype, name) for i, expr in self._subs.items(): lb_i = self._src.get_variable(i).lowerbound ub_i = self._src.get_variable(i).upperbound # substitute x_i <- x_j * coeff + const # lb_i <= x_i <= ub_i --> # (lb_i - const) / coeff <= x_j <= (ub_i - const) / coeff if coeff > 0 # (ub_i - const) / coeff <= x_j <= (lb_i - const) / coeff if coeff < 0 # lb_i <= const <= ub_i if coeff == 0 if isclose(expr.coeff, 0.0, abs_tol=1e-10): if not lb_i <= expr.const <= ub_i: logger.warning("Infeasible substitution for variable: %s", i) feasible = False else: if abs(lb_i) < INFINITY: new_lb_i = (lb_i - expr.const) / expr.coeff else: new_lb_i = lb_i if expr.coeff > 0 else -lb_i if abs(ub_i) < INFINITY: new_ub_i = (ub_i - expr.const) / expr.coeff else: new_ub_i = ub_i if expr.coeff > 0 else -ub_i var_j = self._dst.get_variable(expr.variable) lb_j = var_j.lowerbound ub_j = var_j.upperbound if expr.coeff > 0: var_j.lowerbound = max(lb_j, new_lb_i) var_j.upperbound = min(ub_j, new_ub_i) else: var_j.lowerbound = max(lb_j, new_ub_i) var_j.upperbound = min(ub_j, new_lb_i) for var in self._dst.variables: if var.lowerbound > var.upperbound: logger.warning( "Infeasible lower and upper bounds: %s %f %f", var, var.lowerbound, var.upperbound, ) feasible = False return feasible def _linear_expression(self, lin_expr: LinearExpression) -> Tuple[float, LinearExpression]: const = 0.0 lin_dict: Dict[str, float] = defaultdict(float) for i, w_i in lin_expr.to_dict(use_name=True).items(): i = cast(str, i) expr_i = self._subs.get(i, SubstitutionExpression(coeff=1, variable=i)) const += w_i * expr_i.const if expr_i.variable: lin_dict[expr_i.variable] += w_i * expr_i.coeff new_lin = LinearExpression( quadratic_program=self._dst, coefficients=lin_dict if lin_dict else {} ) return const, new_lin def _quadratic_expression( self, quad_expr: QuadraticExpression ) -> Tuple[float, Optional[LinearExpression], Optional[QuadraticExpression]]: const = 0.0 lin_dict: Dict[str, float] = defaultdict(float) quad_dict: Dict[Tuple[str, str], float] = defaultdict(float) for (i, j), w_ij in quad_expr.to_dict(use_name=True).items(): i = cast(str, i) j = cast(str, j) expr_i = self._subs.get(i, SubstitutionExpression(coeff=1, variable=i)) expr_j = self._subs.get(j, SubstitutionExpression(coeff=1, variable=j)) const += w_ij * expr_i.const * expr_j.const if expr_i.variable: lin_dict[expr_i.variable] += w_ij * expr_i.coeff * expr_j.const if expr_j.variable: lin_dict[expr_j.variable] += w_ij * expr_j.coeff * expr_i.const if expr_i.variable and expr_j.variable: quad_dict[expr_i.variable, expr_j.variable] += w_ij * expr_i.coeff * expr_j.coeff new_lin = LinearExpression( quadratic_program=self._dst, coefficients=lin_dict if lin_dict else {} ) new_quad = QuadraticExpression( quadratic_program=self._dst, coefficients=quad_dict if quad_dict else {} ) return const, new_lin, new_quad def _objective(self) -> bool: obj = self._src.objective const1, lin1 = self._linear_expression(obj.linear) const2, lin2, quadratic = self._quadratic_expression(obj.quadratic) constant = obj.constant + const1 + const2 linear = lin1.coefficients + lin2.coefficients if obj.sense == obj.sense.MINIMIZE: self._dst.minimize(constant=constant, linear=linear, quadratic=quadratic.coefficients) else: self._dst.maximize(constant=constant, linear=linear, quadratic=quadratic.coefficients) return True def _linear_constraints(self) -> bool: feasible = True for lin_cst in self._src.linear_constraints: constant, linear = self._linear_expression(lin_cst.linear) rhs = lin_cst.rhs - constant if linear.coefficients.nnz > 0: self._dst.linear_constraint( name=lin_cst.name, linear=linear.coefficients, sense=lin_cst.sense, rhs=rhs, ) else: if not self._feasible(lin_cst.sense, rhs): logger.warning("constraint %s is infeasible due to substitution", lin_cst.name) feasible = False return feasible def _quadratic_constraints(self) -> bool: feasible = True for quad_cst in self._src.quadratic_constraints: const1, lin1 = self._linear_expression(quad_cst.linear) const2, lin2, quadratic = self._quadratic_expression(quad_cst.quadratic) rhs = quad_cst.rhs - const1 - const2 linear = lin1.coefficients + lin2.coefficients if quadratic.coefficients.nnz > 0: self._dst.quadratic_constraint( name=quad_cst.name, linear=linear, quadratic=quadratic.coefficients, sense=quad_cst.sense, rhs=rhs, ) elif linear.nnz > 0: name = quad_cst.name lin_names = set(lin.name for lin in self._dst.linear_constraints) while name in lin_names: name = "_" + name self._dst.linear_constraint(name=name, linear=linear, sense=quad_cst.sense, rhs=rhs) else: if not self._feasible(quad_cst.sense, rhs): logger.warning("constraint %s is infeasible due to substitution", quad_cst.name) feasible = False return feasible
qiskit-optimization/qiskit_optimization/problems/substitute_variables.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/problems/substitute_variables.py", "repo_id": "qiskit-optimization", "token_count": 6227 }
158
--- fixes: - | Fix bit ordering in :class:`qiskit_optimization.algorithms.MinimumEigenOptimizer` with qasm_simulator. - | Fix probabilities of solution samples with qasm_simulator in :class:`qiskit_optimization.algorithms.MinimumEigenOptimizer`. See https://github.com/Qiskit/qiskit-optimization/pull/97 for details.
qiskit-optimization/releasenotes/notes/0.2/fix-bit-ordering-e807ec9f4b206ec3.yaml/0
{ "file_path": "qiskit-optimization/releasenotes/notes/0.2/fix-bit-ordering-e807ec9f4b206ec3.yaml", "repo_id": "qiskit-optimization", "token_count": 124 }
159
--- upgrade: - | If users set an empty variable name ``""`` with :meth:`~qiskit_optimization.QuadraticProgram.binary_var`, :meth:`~qiskit_optimization.QuadraticProgram.integer_var`, and :meth:`~qiskit_optimization.QuadraticProgram.continuous_var`, they set the default variable name (e.g., ``x0``) while they used to set the empty name as variable name. .. code-block:: python from qiskit_optimization.problems import QuadraticProgram qp = QuadraticProgram() x = qp.binary_var(name="") y = qp.integer_var(name="") z = qp.continuous_var(name="") print(x.name) # x0 print(y.name) # x1 print(z.name) # x2 features: - | Adds a method :meth:`~qiskit_optimization.QuadraticProgram.prettyprint` to :class:`~qiskit_optimization.QuadraticProgram` to generate a pretty-printed string of the object. Here is an example of pretty printing. .. code-block:: python from qiskit_optimization import QuadraticProgram qp = QuadraticProgram('problem 1') qp.integer_var(-1, 2, 'x') qp.integer_var(-1, 2, 'y') qp.continuous_var(-1, name='z') qp.binary_var('u') qp.binary_var('v') qp.binary_var_list(10) qp.integer_var_list(3) qp.continuous_var_list(3) qp.minimize(constant=3, linear={'x': 2, 'y': 3}, quadratic={('u', 'x'): -1}) qp.linear_constraint({'x': 1, 'y': -2}, '>=', 2, name='lin_GE') qp.linear_constraint({'x': 2, 'y': -1}, '==', 1, name='lin_EQ') qp.quadratic_constraint({'x': 1, 'u': 1}, {(3, 4): 1, (5, 6): -1}, '<=', 1, name='quad_LE') qp.quadratic_constraint({'x': 2, 'y': -1}, {('z', 'z'): -1}, '<=', 1) print(qp.prettyprint()) The output is as follows. :: Problem name: problem 1 Minimize -x*u + 2*x + 3*y + 3 Subject to Linear constraints (2) x - 2*y >= 2 'lin_GE' 2*x - y == 1 'lin_EQ' Quadratic constraints (2) u*v - x5*x6 + u + x <= 1 'quad_LE' -z^2 + 2*x - y <= 1 'q1' Integer variables (5) -1 <= x <= 2 -1 <= y <= 2 0 <= x15 0 <= x16 0 <= x17 Continuous variables (4) -1 <= z 0 <= x18 0 <= x19 0 <= x20 Binary variables (12) u v x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 other: - | Shows a warning message if non-printable strings are set to :class:`~qiskit_optimization.QuadraticProgram` as problem name, variable name, or constraint name.
qiskit-optimization/releasenotes/notes/0.4/add-prettyprint-8ec601f41c9cc7d2.yaml/0
{ "file_path": "qiskit-optimization/releasenotes/notes/0.4/add-prettyprint-8ec601f41c9cc7d2.yaml", "repo_id": "qiskit-optimization", "token_count": 1339 }
160
--- fixes: - | Fixed incorrect ``rho`` update when ``vary_rho`` is set to ``UPDATE_RHO_BY_RESIDUALS`` in :class:`~qiskit_optimization.algorithms.ADMMOptimizer`. - | Fixed incorrect population of ``y_saved`` in :class:`~qiskit_optimization.algorithms.ADMMState`.
qiskit-optimization/releasenotes/notes/0.6/fix-admm-02d70ff90df962eb.yaml/0
{ "file_path": "qiskit-optimization/releasenotes/notes/0.6/fix-admm-02d70ff90df962eb.yaml", "repo_id": "qiskit-optimization", "token_count": 111 }
161
# This code is part of a Qiskit project. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for QuantumRandomAccessOptimizer""" import unittest from test.optimization_test_case import QiskitOptimizationTestCase import numpy as np from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_algorithms import VQE, NumPyMinimumEigensolver, NumPyMinimumEigensolverResult, VQEResult from qiskit_algorithms.optimizers import COBYLA from qiskit_algorithms.utils import algorithm_globals from qiskit_optimization.algorithms import SolutionSample from qiskit_optimization.algorithms.optimization_algorithm import OptimizationResultStatus from qiskit_optimization.algorithms.qrao import ( QuantumRandomAccessEncoding, QuantumRandomAccessOptimizationResult, QuantumRandomAccessOptimizer, RoundingContext, RoundingResult, ) from qiskit_optimization.problems import QuadraticProgram class TestQuantumRandomAccessOptimizer(QiskitOptimizationTestCase): """QuantumRandomAccessOptimizer tests.""" def setUp(self): super().setUp() self.problem = QuadraticProgram() self.problem.binary_var("x") self.problem.binary_var("y") self.problem.binary_var("z") self.problem.minimize(linear={"x": 1, "y": 2, "z": 3}) self.encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) self.encoding.encode(self.problem) self.ansatz = RealAmplitudes(self.encoding.num_qubits) # for VQE algorithm_globals.random_seed = 50 def test_solve_relaxed_numpy(self): """Test QuantumRandomAccessOptimizer with NumPyMinimumEigensolver.""" np_solver = NumPyMinimumEigensolver() qrao = QuantumRandomAccessOptimizer(min_eigen_solver=np_solver) relaxed_results, rounding_context = qrao.solve_relaxed(encoding=self.encoding) self.assertIsInstance(relaxed_results, NumPyMinimumEigensolverResult) self.assertAlmostEqual(relaxed_results.eigenvalue, -3.24037, places=5) self.assertEqual(len(relaxed_results.aux_operators_evaluated), 3) self.assertAlmostEqual(relaxed_results.aux_operators_evaluated[0][0], 0.26726, places=5) self.assertAlmostEqual(relaxed_results.aux_operators_evaluated[1][0], 0.53452, places=5) self.assertAlmostEqual(relaxed_results.aux_operators_evaluated[2][0], 0.80178, places=5) self.assertIsInstance(rounding_context, RoundingContext) self.assertEqual(rounding_context.circuit.num_qubits, self.ansatz.num_qubits) self.assertEqual(rounding_context.encoding, self.encoding) self.assertAlmostEqual(rounding_context.expectation_values[0], 0.26726, places=5) self.assertAlmostEqual(rounding_context.expectation_values[1], 0.53452, places=5) self.assertAlmostEqual(rounding_context.expectation_values[2], 0.80178, places=5) def test_solve_relaxed_vqe(self): """Test QuantumRandomAccessOptimizer with VQE.""" vqe = VQE( ansatz=self.ansatz, optimizer=COBYLA(tol=1e-6), estimator=Estimator(), ) qrao = QuantumRandomAccessOptimizer(min_eigen_solver=vqe) relaxed_results, rounding_context = qrao.solve_relaxed(encoding=self.encoding) self.assertIsInstance(relaxed_results, VQEResult) self.assertAlmostEqual(relaxed_results.eigenvalue, -2.73861, delta=1e-4) self.assertEqual(len(relaxed_results.aux_operators_evaluated), 3) self.assertAlmostEqual( relaxed_results.aux_operators_evaluated[0][0].item(), 0.31632, delta=1e-4 ) self.assertAlmostEqual(relaxed_results.aux_operators_evaluated[1][0].item(), 0, delta=1e-4) self.assertAlmostEqual( relaxed_results.aux_operators_evaluated[2][0].item(), 0.94865, delta=1e-4 ) self.assertIsInstance(rounding_context, RoundingContext) self.assertEqual(rounding_context.circuit.num_qubits, self.ansatz.num_qubits) self.assertEqual(rounding_context.encoding, self.encoding) self.assertAlmostEqual(rounding_context.expectation_values[0], 0.31632, delta=1e-4) self.assertAlmostEqual(rounding_context.expectation_values[1], 0, delta=1e-4) self.assertAlmostEqual(rounding_context.expectation_values[2], 0.94865, delta=1e-4) def test_require_aux_operator_support(self): """Test whether the eigensolver supports auxiliary operator. If auxiliary operators are not supported, a TypeError should be raised. """ class ModifiedVQE(VQE): """Modified VQE method without auxiliary operator support. Since no existing eigensolver seems to lack auxiliary operator support, we have created one that claims to lack it. """ @classmethod def supports_aux_operators(cls) -> bool: return False vqe = ModifiedVQE( ansatz=self.ansatz, optimizer=COBYLA(), estimator=Estimator(), ) with self.assertRaises(TypeError): QuantumRandomAccessOptimizer(min_eigen_solver=vqe) def test_solve_numpy(self): """Test QuantumRandomAccessOptimizer with NumPyMinimumEigensolver.""" np_solver = NumPyMinimumEigensolver() qrao = QuantumRandomAccessOptimizer(min_eigen_solver=np_solver) results = qrao.solve(problem=self.problem) self.assertIsInstance(results, QuantumRandomAccessOptimizationResult) self.assertEqual(results.fval, 0) self.assertEqual(len(results.samples), 1) np.testing.assert_array_almost_equal(results.samples[0].x, [0, 0, 0]) self.assertAlmostEqual(results.samples[0].fval, 0) self.assertAlmostEqual(results.samples[0].probability, 1.0) self.assertEqual(results.samples[0].status, OptimizationResultStatus.SUCCESS) self.assertAlmostEqual(results.relaxed_fval, -0.24037, places=5) self.assertIsInstance(results.relaxed_result, NumPyMinimumEigensolverResult) self.assertAlmostEqual(results.relaxed_result.eigenvalue, -3.24037, places=5) self.assertEqual(len(results.relaxed_result.aux_operators_evaluated), 3) self.assertAlmostEqual( results.relaxed_result.aux_operators_evaluated[0][0], 0.26726, places=5 ) self.assertAlmostEqual( results.relaxed_result.aux_operators_evaluated[1][0], 0.53452, places=5 ) self.assertAlmostEqual( results.relaxed_result.aux_operators_evaluated[2][0], 0.80178, places=5 ) self.assertIsInstance(results.rounding_result, RoundingResult) self.assertAlmostEqual(results.rounding_result.expectation_values[0], 0.26726, places=5) self.assertAlmostEqual(results.rounding_result.expectation_values[1], 0.53452, places=5) self.assertAlmostEqual(results.rounding_result.expectation_values[2], 0.80178, places=5) self.assertIsInstance(results.rounding_result.samples[0], SolutionSample) def test_solve_quadratic(self): """Test QuantumRandomAccessOptimizer with a quadratic objective function.""" # quadratic objective problem2 = QuadraticProgram() problem2.binary_var("x") problem2.binary_var("y") problem2.binary_var("z") problem2.maximize(linear={"x": 1, "y": 2, "z": 3}, quadratic={("y", "z"): -4}) np_solver = NumPyMinimumEigensolver() qrao = QuantumRandomAccessOptimizer(min_eigen_solver=np_solver) results = qrao.solve(problem2) self.assertIsInstance(results, QuantumRandomAccessOptimizationResult) self.assertEqual(results.fval, 4) self.assertEqual(len(results.samples), 1) np.testing.assert_array_almost_equal(results.samples[0].x, [1, 0, 1]) self.assertAlmostEqual(results.samples[0].fval, 4) self.assertAlmostEqual(results.samples[0].probability, 1.0) self.assertEqual(results.samples[0].status, OptimizationResultStatus.SUCCESS) self.assertAlmostEqual(results.relaxed_fval, -5.98852, places=5) self.assertIsInstance(results.relaxed_result, NumPyMinimumEigensolverResult) self.assertAlmostEqual(results.relaxed_result.eigenvalue, -3.98852, places=5) self.assertEqual(len(results.relaxed_result.aux_operators_evaluated), 3) self.assertAlmostEqual( results.relaxed_result.aux_operators_evaluated[0][0], -0.27735, places=5 ) self.assertAlmostEqual( results.relaxed_result.aux_operators_evaluated[1][0], 0.96077, places=5 ) self.assertAlmostEqual(results.relaxed_result.aux_operators_evaluated[2][0], -1, places=5) self.assertIsInstance(results.rounding_result, RoundingResult) self.assertAlmostEqual(results.rounding_result.expectation_values[0], -0.27735, places=5) self.assertAlmostEqual(results.rounding_result.expectation_values[1], 0.96077, places=5) self.assertAlmostEqual(results.rounding_result.expectation_values[2], -1, places=5) self.assertIsInstance(results.rounding_result.samples[0], SolutionSample) def test_empty_encoding(self): """Test the encoding is empty.""" np_solver = NumPyMinimumEigensolver() encoding = QuantumRandomAccessEncoding(3) with self.assertRaises(ValueError): qrao = QuantumRandomAccessOptimizer(min_eigen_solver=np_solver) qrao.solve_relaxed(encoding=encoding) if __name__ == "__main__": unittest.main()
qiskit-optimization/test/algorithms/qrao/test_quantum_random_access_optimizer.py/0
{ "file_path": "qiskit-optimization/test/algorithms/qrao/test_quantum_random_access_optimizer.py", "repo_id": "qiskit-optimization", "token_count": 4149 }
162
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test SLSQP Optimizer """ import unittest from test import QiskitOptimizationTestCase import numpy as np from qiskit_optimization import INFINITY from qiskit_optimization.algorithms import SlsqpOptimizer from qiskit_optimization.problems import QuadraticProgram class TestSlsqpOptimizer(QiskitOptimizationTestCase): """SLSQP Optimizer Tests.""" def test_slsqp_optimizer(self): """Generic SLSQP Optimizer Test.""" problem = QuadraticProgram() problem.continuous_var(upperbound=4) problem.continuous_var(upperbound=4) problem.linear_constraint(linear=[1, 1], sense="=", rhs=2) problem.minimize(linear=[2, 2], quadratic=[[2, 0.25], [0.25, 0.5]]) # solve problem with SLSQP slsqp = SlsqpOptimizer(trials=3) result = slsqp.solve(problem) self.assertAlmostEqual(result.fval, 5.8750) def test_slsqp_optimizer_full_output(self): """Generic SLSQP Optimizer Test.""" problem = QuadraticProgram() problem.continuous_var(upperbound=4) problem.continuous_var(upperbound=4) problem.linear_constraint(linear=[1, 1], sense="=", rhs=2) problem.minimize(linear=[2, 2], quadratic=[[2, 0.25], [0.25, 0.5]]) # solve problem with SLSQP slsqp = SlsqpOptimizer(trials=3, full_output=True) result = slsqp.solve(problem) self.assertAlmostEqual(result.fval, 5.8750) self.assertAlmostEqual(result.fx, 5.8750) self.assertGreaterEqual(result.its, 1) self.assertEqual(result.imode, 0) self.assertIsNotNone(result.smode) self.assertEqual(len(result.samples), 1) self.assertAlmostEqual(result.fval, result.samples[0].fval) np.testing.assert_almost_equal(result.x, result.samples[0].x) self.assertEqual(result.status, result.samples[0].status) self.assertAlmostEqual(result.samples[0].probability, 1.0) def test_slsqp_unbounded(self): """Unbounded test for optimization""" problem = QuadraticProgram() problem.continuous_var(name="x") problem.continuous_var(name="y") problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) slsqp = SlsqpOptimizer() solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([2.0, 1.0], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(2.0, solution.fval, 3) def test_slsqp_unbounded_with_trials(self): """Unbounded test for optimization""" problem = QuadraticProgram() problem.continuous_var(name="x", lowerbound=-INFINITY, upperbound=INFINITY) problem.continuous_var(name="y", lowerbound=-INFINITY, upperbound=INFINITY) problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) slsqp = SlsqpOptimizer(trials=3) solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([2.0, 1.0], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(2.0, solution.fval, 3) def test_slsqp_bounded(self): """Same as above, but a bounded test""" problem = QuadraticProgram() problem.continuous_var(name="x", lowerbound=2.5) problem.continuous_var(name="y", upperbound=0.5) problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) slsqp = SlsqpOptimizer() solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([2.5, 0.5], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(0.75, solution.fval, 3) def test_slsqp_equality(self): """A test with equality constraint""" problem = QuadraticProgram() problem.continuous_var(name="x") problem.continuous_var(name="y") problem.linear_constraint(linear=[1, -1], sense="=", rhs=0) problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) slsqp = SlsqpOptimizer() solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([1.0, 1.0], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(1.0, solution.fval, 3) def test_slsqp_inequality(self): """A test with inequality constraint""" problem = QuadraticProgram() problem.continuous_var(name="x") problem.continuous_var(name="y") problem.linear_constraint(linear=[1, -1], sense=">=", rhs=1) problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) slsqp = SlsqpOptimizer() solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([2.0, 1.0], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(2.0, solution.fval, 3) def test_slsqp_optimizer_with_quadratic_constraint(self): """A test with equality constraint""" problem = QuadraticProgram() problem.continuous_var(upperbound=1) problem.continuous_var(upperbound=1) problem.minimize(linear=[1, 1]) linear = [-1, -1] quadratic = [[1, 0], [0, 1]] problem.quadratic_constraint(linear=linear, quadratic=quadratic, rhs=-1 / 2) slsqp = SlsqpOptimizer() solution = slsqp.solve(problem) self.assertIsNotNone(solution) self.assertIsNotNone(solution.x) np.testing.assert_almost_equal([0.5, 0.5], solution.x, 3) self.assertIsNotNone(solution.fval) np.testing.assert_almost_equal(1.0, solution.fval, 3) def test_multistart_properties(self): """ Tests properties of MultiStartOptimizer. Since it is an abstract class, the test is here. """ trials = 5 clip = 200.0 slsqp = SlsqpOptimizer(trials=trials, clip=clip) self.assertEqual(trials, slsqp.trials) self.assertAlmostEqual(clip, slsqp.clip) trials = 6 clip = 300.0 slsqp.trials = trials slsqp.clip = clip self.assertEqual(trials, slsqp.trials) self.assertAlmostEqual(clip, slsqp.clip) if __name__ == "__main__": unittest.main()
qiskit-optimization/test/algorithms/test_slsqp.py/0
{ "file_path": "qiskit-optimization/test/algorithms/test_slsqp.py", "repo_id": "qiskit-optimization", "token_count": 3135 }
163
# This code is part of a Qiskit project. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test VehicleRouting class""" import random from test.optimization_test_case import QiskitOptimizationTestCase import networkx as nx import numpy as np from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import OptimizationResult, OptimizationResultStatus from qiskit_optimization.applications.vehicle_routing import VehicleRouting from qiskit_optimization.problems import Constraint, QuadraticObjective, VarType class TestVehicleRouting(QiskitOptimizationTestCase): """Test VehicleRouting class""" def setUp(self): super().setUp() random.seed(600) low = 0 high = 100 pos = {i: (random.randint(low, high), random.randint(low, high)) for i in range(4)} self.graph = nx.random_geometric_graph(4, np.hypot(high - low, high - low) + 1, pos=pos) for w, v in self.graph.edges: delta = [ self.graph.nodes[w]["pos"][i] - self.graph.nodes[v]["pos"][i] for i in range(2) ] self.graph.edges[w, v]["weight"] = np.rint(np.hypot(delta[0], delta[1])) op = QuadraticProgram() for i in range(12): op.binary_var() self.result = OptimizationResult( x=[1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0], fval=184, variables=op.variables, status=OptimizationResultStatus.SUCCESS, ) self.result_d2 = OptimizationResult( x=[1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1], fval=208.0, variables=op.variables, status=OptimizationResultStatus.SUCCESS, ) self.result_nv3 = OptimizationResult( x=[1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0], fval=212.0, variables=op.variables, status=OptimizationResultStatus.SUCCESS, ) def test_to_quadratic_program(self): """Test to_quadratic_program""" vehicle_routing = VehicleRouting(self.graph) op = vehicle_routing.to_quadratic_program() # Test name self.assertEqual(op.name, "Vehicle routing") # Test variables self.assertEqual(op.get_num_vars(), 12) for var in op.variables: self.assertEqual(var.vartype, VarType.BINARY) # Test objective obj = op.objective self.assertEqual(obj.sense, QuadraticObjective.Sense.MINIMIZE) self.assertEqual(obj.constant, 0) self.assertDictEqual( obj.linear.to_dict(), { 0: 49.0, 1: 36.0, 2: 21.0, 3: 49.0, 4: 65.0, 5: 67.0, 6: 36.0, 7: 65.0, 8: 29.0, 9: 21.0, 10: 67.0, 11: 29.0, }, ) self.assertEqual(obj.quadratic.to_dict(), {}) # Test constraint lin = op.linear_constraints self.assertEqual(len(lin), 12) for i in range(3): self.assertEqual(lin[i].sense, Constraint.Sense.EQ) self.assertEqual(lin[i].rhs, 1) self.assertEqual( lin[i].linear.to_dict(), {3 * (i + 1): 1, 3 * (i + 1) + 1: 1, 3 * (i + 1) + 2: 1}, ) self.assertEqual(lin[3].sense, Constraint.Sense.EQ) self.assertEqual(lin[3].rhs, 1) self.assertEqual(lin[3].linear.to_dict(), {0: 1, 7: 1, 10: 1}) self.assertEqual(lin[4].sense, Constraint.Sense.EQ) self.assertEqual(lin[4].rhs, 1) self.assertEqual(lin[4].linear.to_dict(), {1: 1, 4: 1, 11: 1}) self.assertEqual(lin[5].sense, Constraint.Sense.EQ) self.assertEqual(lin[5].rhs, 1) self.assertEqual(lin[5].linear.to_dict(), {2: 1, 5: 1, 8: 1}) self.assertEqual(lin[6].sense, Constraint.Sense.EQ) self.assertEqual(lin[6].rhs, 2) self.assertEqual(lin[6].linear.to_dict(), {3: 1, 6: 1, 9: 1}) self.assertEqual(lin[7].sense, Constraint.Sense.EQ) self.assertEqual(lin[7].rhs, 2) self.assertEqual(lin[7].linear.to_dict(), {0: 1, 1: 1, 2: 1}) self.assertEqual(lin[8].sense, Constraint.Sense.LE) self.assertEqual(lin[8].rhs, 1) self.assertEqual(lin[8].linear.to_dict(), {4: 1, 7: 1}) self.assertEqual(lin[9].sense, Constraint.Sense.LE) self.assertEqual(lin[9].rhs, 1) self.assertEqual(lin[9].linear.to_dict(), {5: 1, 10: 1}) self.assertEqual(lin[10].sense, Constraint.Sense.LE) self.assertEqual(lin[10].rhs, 1) self.assertEqual(lin[10].linear.to_dict(), {8: 1.0, 11: 1.0}) self.assertEqual(lin[11].sense, Constraint.Sense.LE) self.assertEqual(lin[11].rhs, 2) self.assertEqual(lin[11].linear.to_dict(), {4: 1, 5: 1, 7: 1, 8: 1, 10: 1, 11: 1}) def test_interpret(self): """Test interpret""" vehicle_routing = VehicleRouting(self.graph) self.assertEqual( vehicle_routing.interpret(self.result), [[[0, 1], [1, 0]], [[0, 2], [2, 3], [3, 0]]], ) def test_edgelist(self): """Test _edgelist""" vehicle_routing = VehicleRouting(self.graph) self.assertEqual( vehicle_routing._edgelist(vehicle_routing.interpret(self.result)), [[0, 1], [1, 0], [0, 2], [2, 3], [3, 0]], ) def test_edge_color(self): """Test _edge_color""" vehicle_routing = VehicleRouting(self.graph) self.assertEqual( vehicle_routing._edge_color(vehicle_routing.interpret(self.result)), [0.0, 0.0, 0.5, 0.5, 0.5], ) def test_to_quadratic_program_d2(self): """Test to_quadratic_program for depot=2""" vehicle_routing = VehicleRouting(self.graph, depot=2) op = vehicle_routing.to_quadratic_program() # Test name self.assertEqual(op.name, "Vehicle routing") # Test variables self.assertEqual(op.get_num_vars(), 12) for var in op.variables: self.assertEqual(var.vartype, VarType.BINARY) # Test objective obj = op.objective self.assertEqual(obj.sense, QuadraticObjective.Sense.MINIMIZE) self.assertEqual(obj.constant, 0) self.assertDictEqual( obj.linear.to_dict(), { 0: 49.0, 1: 36.0, 2: 21.0, 3: 49.0, 4: 65.0, 5: 67.0, 6: 36.0, 7: 65.0, 8: 29.0, 9: 21.0, 10: 67.0, 11: 29.0, }, ) self.assertEqual(obj.quadratic.to_dict(), {}) # Test constraint lin = op.linear_constraints self.assertEqual(len(lin), 12) c012 = [-1, 0, 2] for i in range(3): j = c012[i] self.assertEqual(lin[i].sense, Constraint.Sense.EQ) self.assertEqual(lin[i].rhs, 1) self.assertEqual( lin[i].linear.to_dict(), {3 * (j + 1): 1, 3 * (j + 1) + 1: 1, 3 * (j + 1) + 2: 1}, ) self.assertEqual(lin[3].sense, Constraint.Sense.EQ) self.assertEqual(lin[3].rhs, 1) self.assertEqual(lin[3].linear.to_dict(), {3: 1, 6: 1, 9: 1}) self.assertEqual(lin[4].sense, Constraint.Sense.EQ) self.assertEqual(lin[4].rhs, 1) self.assertEqual(lin[4].linear.to_dict(), {0: 1, 7: 1, 10: 1}) self.assertEqual(lin[5].sense, Constraint.Sense.EQ) self.assertEqual(lin[5].rhs, 1) self.assertEqual(lin[5].linear.to_dict(), {2: 1, 5: 1, 8: 1}) self.assertEqual(lin[6].sense, Constraint.Sense.EQ) self.assertEqual(lin[6].rhs, 2) self.assertEqual(lin[6].linear.to_dict(), {1: 1, 4: 1, 11: 1}) self.assertEqual(lin[7].sense, Constraint.Sense.EQ) self.assertEqual(lin[7].rhs, 2) self.assertEqual(lin[7].linear.to_dict(), {6: 1, 7: 1, 8: 1}) self.assertEqual(lin[8].sense, Constraint.Sense.LE) self.assertEqual(lin[8].rhs, 1) self.assertEqual(lin[8].linear.to_dict(), {0: 1, 3: 1}) self.assertEqual(lin[9].sense, Constraint.Sense.LE) self.assertEqual(lin[9].rhs, 1) self.assertEqual(lin[9].linear.to_dict(), {2: 1, 9: 1}) self.assertEqual(lin[10].sense, Constraint.Sense.LE) self.assertEqual(lin[10].rhs, 1) self.assertEqual(lin[10].linear.to_dict(), {5: 1.0, 10: 1.0}) self.assertEqual(lin[11].sense, Constraint.Sense.LE) self.assertEqual(lin[11].rhs, 2) self.assertEqual(lin[11].linear.to_dict(), {0: 1, 2: 1, 3: 1, 5: 1, 9: 1, 10: 1}) def test_interpret_d2(self): """Test interpret for depot=2""" vehicle_routing = VehicleRouting(self.graph, depot=2) self.assertEqual( vehicle_routing.interpret(self.result_d2), [[[2, 0], [0, 1], [1, 2]], [[2, 3], [3, 2]]], ) def test_edgelist_d2(self): """Test _edgelist for depot=2""" vehicle_routing = VehicleRouting(self.graph, depot=2) self.assertEqual( vehicle_routing._edgelist(vehicle_routing.interpret(self.result_d2)), [[2, 0], [0, 1], [1, 2], [2, 3], [3, 2]], ) def test_edge_color_d2(self): """Test _edge_color for depot=2""" vehicle_routing = VehicleRouting(self.graph, depot=2) self.assertEqual( vehicle_routing._edge_color(vehicle_routing.interpret(self.result_d2)), [0.0, 0.0, 0.0, 0.5, 0.5], ) def test_to_quadratic_program_nv3(self): """Test to_quadratic_program for num_vehicles=3""" vehicle_routing = VehicleRouting(self.graph, num_vehicles=3) op = vehicle_routing.to_quadratic_program() # Test name self.assertEqual(op.name, "Vehicle routing") # Test variables self.assertEqual(op.get_num_vars(), 12) for var in op.variables: self.assertEqual(var.vartype, VarType.BINARY) # Test objective obj = op.objective self.assertEqual(obj.sense, QuadraticObjective.Sense.MINIMIZE) self.assertEqual(obj.constant, 0) self.assertDictEqual( obj.linear.to_dict(), { 0: 49.0, 1: 36.0, 2: 21.0, 3: 49.0, 4: 65.0, 5: 67.0, 6: 36.0, 7: 65.0, 8: 29.0, 9: 21.0, 10: 67.0, 11: 29.0, }, ) self.assertEqual(obj.quadratic.to_dict(), {}) # Test constraint lin = op.linear_constraints self.assertEqual(len(lin), 12) for i in range(3): self.assertEqual(lin[i].sense, Constraint.Sense.EQ) self.assertEqual(lin[i].rhs, 1) self.assertEqual( lin[i].linear.to_dict(), {3 * (i + 1): 1, 3 * (i + 1) + 1: 1, 3 * (i + 1) + 2: 1}, ) self.assertEqual(lin[3].sense, Constraint.Sense.EQ) self.assertEqual(lin[3].rhs, 1) self.assertEqual(lin[3].linear.to_dict(), {0: 1, 7: 1, 10: 1}) self.assertEqual(lin[4].sense, Constraint.Sense.EQ) self.assertEqual(lin[4].rhs, 1) self.assertEqual(lin[4].linear.to_dict(), {1: 1, 4: 1, 11: 1}) self.assertEqual(lin[5].sense, Constraint.Sense.EQ) self.assertEqual(lin[5].rhs, 1) self.assertEqual(lin[5].linear.to_dict(), {2: 1, 5: 1, 8: 1}) self.assertEqual(lin[6].sense, Constraint.Sense.EQ) self.assertEqual(lin[6].rhs, 3) self.assertEqual(lin[6].linear.to_dict(), {3: 1, 6: 1, 9: 1}) self.assertEqual(lin[7].sense, Constraint.Sense.EQ) self.assertEqual(lin[7].rhs, 3) self.assertEqual(lin[7].linear.to_dict(), {0: 1, 1: 1, 2: 1}) self.assertEqual(lin[8].sense, Constraint.Sense.LE) self.assertEqual(lin[8].rhs, 1) self.assertEqual(lin[8].linear.to_dict(), {4: 1, 7: 1}) self.assertEqual(lin[9].sense, Constraint.Sense.LE) self.assertEqual(lin[9].rhs, 1) self.assertEqual(lin[9].linear.to_dict(), {5: 1, 10: 1}) self.assertEqual(lin[10].sense, Constraint.Sense.LE) self.assertEqual(lin[10].rhs, 1) self.assertEqual(lin[10].linear.to_dict(), {8: 1.0, 11: 1.0}) self.assertEqual(lin[11].sense, Constraint.Sense.LE) self.assertEqual(lin[11].rhs, 2) self.assertEqual(lin[11].linear.to_dict(), {4: 1, 5: 1, 7: 1, 8: 1, 10: 1, 11: 1}) def test_interpret_nv3(self): """Test interpret for num_vehicles=3""" vehicle_routing = VehicleRouting(self.graph, num_vehicles=3) self.assertEqual( vehicle_routing.interpret(self.result_nv3), [[[0, 1], [1, 0]], [[0, 2], [2, 0]], [[0, 3], [3, 0]]], ) def test_edgelist_nv3(self): """Test _edgelist for num_vehicles=3""" vehicle_routing = VehicleRouting(self.graph, num_vehicles=3) self.assertEqual( vehicle_routing._edgelist(vehicle_routing.interpret(self.result_nv3)), [[0, 1], [1, 0], [0, 2], [2, 0], [0, 3], [3, 0]], ) def test_edge_color_nv3(self): """Test _edge_color for num_vehicles=3""" vehicle_routing = VehicleRouting(self.graph, num_vehicles=3) self.assertEqual( vehicle_routing._edge_color(vehicle_routing.interpret(self.result_nv3)), [0.0, 0.0, 1 / 3, 1 / 3, 2 / 3, 2 / 3], ) def test_create_random_instance(self): """Test create_random_instance""" vehicle_routing = VehicleRouting.create_random_instance(n=4, seed=600) graph = vehicle_routing.graph for node in graph.nodes: self.assertEqual(graph.nodes[node]["pos"], self.graph.nodes[node]["pos"]) for edge in graph.edges: self.assertEqual(graph.edges[edge]["weight"], self.graph.edges[edge]["weight"]) def test_num_vehicles(self): """Test num_vehicles""" vehicle_routing = VehicleRouting(self.graph, num_vehicles=2) vehicle_routing.num_vehicles = 5 self.assertEqual(vehicle_routing.num_vehicles, 5) def test_depot(self): """Test depot""" vehicle_routing = VehicleRouting(self.graph, depot=0) vehicle_routing.depot = 2 self.assertEqual(vehicle_routing.depot, 2)
qiskit-optimization/test/applications/test_vehicle_routing.py/0
{ "file_path": "qiskit-optimization/test/applications/test_vehicle_routing.py", "repo_id": "qiskit-optimization", "token_count": 7798 }
164
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test substitute_variables """ import unittest from test.optimization_test_case import QiskitOptimizationTestCase from qiskit_optimization import QuadraticProgram from qiskit_optimization.problems.substitute_variables import substitute_variables class TestSubstituteVariables(QiskitOptimizationTestCase): """Test substitute_variables""" def test_substitute_variables(self): """test substitute variables""" q_p = QuadraticProgram("test") q_p.binary_var(name="x") q_p.integer_var(name="y", lowerbound=-2, upperbound=4) q_p.continuous_var(name="z", lowerbound=-1.5, upperbound=3.2) q_p.minimize( constant=1, linear={"x": 1, "y": 2}, quadratic={("x", "y"): -1, ("z", "z"): 2}, ) q_p.linear_constraint({"x": 2, "z": -1}, "==", 1) q_p.quadratic_constraint({"x": 2, "z": -1}, {("y", "z"): 3}, "<=", -1) with self.subTest("x <- -1"): q_p2 = substitute_variables(q_p, constants={"x": -1}) self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE) q_p2 = substitute_variables(q_p, constants={"y": -3}) self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE) q_p2 = substitute_variables(q_p, constants={"x": 1, "z": 2}) self.assertEqual(q_p2.status, QuadraticProgram.Status.INFEASIBLE) q_p2.clear() self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID) with self.subTest("x <- 0"): q_p2 = substitute_variables(q_p, constants={"x": 0}) self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID) self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True), {"y": 2}) self.assertDictEqual(q_p2.objective.quadratic.to_dict(use_name=True), {("z", "z"): 2}) self.assertEqual(q_p2.objective.constant, 1) self.assertEqual(len(q_p2.linear_constraints), 1) self.assertEqual(len(q_p2.quadratic_constraints), 1) cst = q_p2.linear_constraints[0] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"z": -1}) self.assertEqual(cst.sense.name, "EQ") self.assertEqual(cst.rhs, 1) cst = q_p2.quadratic_constraints[0] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"z": -1}) self.assertDictEqual(cst.quadratic.to_dict(use_name=True), {("y", "z"): 3}) self.assertEqual(cst.sense.name, "LE") self.assertEqual(cst.rhs, -1) with self.subTest("z <- -1"): q_p2 = substitute_variables(q_p, constants={"z": -1}) self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID) self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True), {"x": 1, "y": 2}) self.assertDictEqual(q_p2.objective.quadratic.to_dict(use_name=True), {("x", "y"): -1}) self.assertEqual(q_p2.objective.constant, 3) self.assertEqual(len(q_p2.linear_constraints), 2) self.assertEqual(len(q_p2.quadratic_constraints), 0) cst = q_p2.linear_constraints[0] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"x": 2}) self.assertEqual(cst.sense.name, "EQ") self.assertEqual(cst.rhs, 0) cst = q_p2.linear_constraints[1] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"x": 2, "y": -3}) self.assertEqual(cst.sense.name, "LE") self.assertEqual(cst.rhs, -2) with self.subTest("y <- -0.5 * x"): q_p2 = substitute_variables(q_p, variables={"y": ("x", -0.5)}) self.assertEqual(q_p2.status, QuadraticProgram.Status.VALID) self.assertDictEqual(q_p2.objective.linear.to_dict(use_name=True), {}) self.assertDictEqual( q_p2.objective.quadratic.to_dict(use_name=True), {("x", "x"): 0.5, ("z", "z"): 2}, ) self.assertEqual(q_p2.objective.constant, 1) self.assertEqual(len(q_p2.linear_constraints), 1) self.assertEqual(len(q_p2.quadratic_constraints), 1) cst = q_p2.linear_constraints[0] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"x": 2, "z": -1}) self.assertEqual(cst.sense.name, "EQ") self.assertEqual(cst.rhs, 1) cst = q_p2.quadratic_constraints[0] self.assertDictEqual(cst.linear.to_dict(use_name=True), {"x": 2, "z": -1}) self.assertDictEqual(cst.quadratic.to_dict(use_name=True), {("x", "z"): -1.5}) self.assertEqual(cst.sense.name, "LE") self.assertEqual(cst.rhs, -1) if __name__ == "__main__": unittest.main()
qiskit-optimization/test/problems/test_substitute_variables.py/0
{ "file_path": "qiskit-optimization/test/problems/test_substitute_variables.py", "repo_id": "qiskit-optimization", "token_count": 2640 }
165
parameters: - name: "pythonVersion" type: string displayName: "Version of Python to test" - name: "testRust" type: boolean - name: "testImages" type: boolean - name: "installOptionals" type: boolean default: false - name: "installFromSdist" type: boolean default: false jobs: - job: "Linux_Tests_Python${{ replace(parameters.pythonVersion, '.', '') }}" displayName: "Test Linux Rust & Python ${{ parameters.pythonVersion }}" pool: {vmImage: 'ubuntu-latest'} variables: QISKIT_SUPPRESS_PACKAGING_WARNINGS: Y PIP_CACHE_DIR: $(Pipeline.Workspace)/.pip QISKIT_TEST_CAPTURE_STREAMS: 1 HAVE_VISUAL_TESTS_RUN: false steps: - task: UsePythonVersion@0 inputs: versionSpec: '${{ parameters.pythonVersion }}' name: 'usePython' displayName: 'Use Python ${{ parameters.pythonVersion }}' - task: Cache@2 inputs: key: 'stestr | "$(Agent.OS)" | "${{ parameters.pythonVersion }}" | "$(Build.BuildNumber)"' restoreKeys: | stestr | "$(Agent.OS)" | "${{ parameters.pythonVersion }}" stestr | "$(Agent.OS)" stestr path: .stestr displayName: "Cache stestr" - ${{ if eq(parameters.testRust, true) }}: # We need to avoid linking our crates into full Python extension libraries during Rust-only # testing because Rust/PyO3 can't handle finding a static CPython interpreter. - bash: cargo test --no-default-features env: # On Linux we link against `libpython` dynamically, but it isn't written into the rpath # of the test executable (I'm not 100% sure why ---Jake). It's easiest just to forcibly # include the correct place in the `dlopen` search path. LD_LIBRARY_PATH: '$(usePython.pythonLocation)/lib:$LD_LIBRARY_PATH' displayName: "Run Rust tests" - bash: | set -e python -m pip install --upgrade pip setuptools wheel virtualenv virtualenv test-job displayName: "Prepare venv" - ${{ if eq(parameters.installFromSdist, true) }}: - bash: | set -e # Use stable Rust, rather than MSRV, to spot-check that stable builds properly. rustup override set stable source test-job/bin/activate python -m pip install -U pip python -m pip install -U build python -m build --sdist . python -m pip install -U \ -c constraints.txt \ -r requirements.txt \ -r requirements-dev.txt \ dist/qiskit-*.tar.gz # Build and install both qiskit and qiskit-terra so that any optionals # depending on `qiskit` will resolve correctly. displayName: "Install Terra from sdist" - ${{ if eq(parameters.installFromSdist, false) }}: - bash: | set -e source test-job/bin/activate python -m pip install -U \ -c constraints.txt \ -r requirements.txt \ -r requirements-dev.txt \ -e . # Build and install both qiskit and qiskit-terra so that any optionals # depending on `qiskit` will resolve correctly. displayName: "Install Terra directly" - ${{ if eq(parameters.installOptionals, true) }}: - bash: | set -e source test-job/bin/activate python -m pip install -r requirements-optional.txt -c constraints.txt python -m pip check displayName: "Install optional packages" - bash: | set -e sudo apt-get update sudo apt-get install -y graphviz displayName: 'Install optional non-Python dependencies' - bash: | set -e source test-job/bin/activate python tools/report_numpy_state.py mkdir -p /tmp/terra-tests cp -r test /tmp/terra-tests/. cp .stestr.conf /tmp/terra-tests/. cp -r .stestr /tmp/terra-tests/. || : pushd /tmp/terra-tests export PYTHONHASHSEED=$(python -S -c "import random; print(random.randint(1, 4294967295))") echo "PYTHONHASHSEED=$PYTHONHASHSEED" stestr run popd env: QISKIT_PARALLEL: FALSE RUST_BACKTRACE: 1 displayName: 'Run Python tests' - bash: | set -e source test-job/bin/activate cp tools/subunit_to_junit.py /tmp/terra-tests/. python -m pip install -U junitxml pushd /tmp/terra-tests mkdir -p junit stestr last --subunit | ./subunit_to_junit.py -o junit/test-results.xml pushd .stestr ls | grep -P "^\d" | xargs -d "\n" rm -f popd popd cp -r /tmp/terra-tests/junit . cp -r /tmp/terra-tests/.stestr . displayName: 'Generate results' condition: succeededOrFailed() - task: PublishTestResults@2 condition: succeededOrFailed() inputs: testResultsFiles: '**/test-*.xml' testRunTitle: 'Test results for Linux Python ${{ parameters.pythonVersion }}' - task: CopyFiles@2 inputs: contents: '**/*.png' targetFolder: $(Build.ArtifactStagingDirectory) displayName: 'Copy images on test failure' condition: failed() - task: PublishBuildArtifacts@1 inputs: pathtoPublish: '$(Build.ArtifactStagingDirectory)' artifactName: 'drop_linux' displayName: 'Publish images on test failure' condition: failed() - ${{ if eq(parameters.testImages, true) }}: - bash: | set -e virtualenv image_tests image_tests/bin/python -m pip install -U \ -c constraints.txt \ -r requirements.txt \ -r requirements-dev.txt \ -r requirements-optional.txt \ -e . sudo apt-get update sudo apt-get install -y graphviz pandoc image_tests/bin/pip check displayName: 'Install dependencies' - bash: | echo "##vso[task.setvariable variable=HAVE_VISUAL_TESTS_RUN;]true" image_tests/bin/python -m unittest discover -v test/visual displayName: 'Run image test' env: # Needed to suppress a warning in jupyter-core 5.x by eagerly migrating to # a new internal interface that will be the default in jupyter-core 6.x. # This variable should become redundant on release of jupyter-core 6. JUPYTER_PLATFORM_DIRS: 1 - task: ArchiveFiles@2 displayName: Archive visual test failure diffs inputs: rootFolderOrFile: 'test/visual/mpl/visual_test_failures' includeRootFolder: false archiveType: tar archiveFile: '$(Build.ArtifactStagingDirectory)/visual_test_failures.tar.gz' verbose: true condition: and(failed(), eq(variables.HAVE_VISUAL_TESTS_RUN, 'true')) - task: ArchiveFiles@2 displayName: Archive circuit results inputs: rootFolderOrFile: 'test/visual/mpl/circuit/circuit_results' archiveType: tar archiveFile: '$(Build.ArtifactStagingDirectory)/circuit_results.tar.gz' verbose: true condition: and(failed(), eq(variables.HAVE_VISUAL_TESTS_RUN, 'true')) - task: ArchiveFiles@2 displayName: Archive graph results inputs: rootFolderOrFile: 'test/visual/mpl/graph/graph_results' archiveType: tar archiveFile: '$(Build.ArtifactStagingDirectory)/graph_results.tar.gz' verbose: true condition: and(failed(), eq(variables.HAVE_VISUAL_TESTS_RUN, 'true')) - task: PublishBuildArtifacts@1 displayName: 'Publish image test failure diffs' inputs: pathtoPublish: '$(Build.ArtifactStagingDirectory)' artifactName: 'image_test_failure_img_diffs' Parallel: true ParallelCount: 8 condition: and(failed(), eq(variables.HAVE_VISUAL_TESTS_RUN, 'true'))
qiskit/.azure/test-linux.yml/0
{ "file_path": "qiskit/.azure/test-linux.yml", "repo_id": "qiskit", "token_count": 3894 }
166
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. OS := $(shell uname -s) .PHONY: default ruff env lint lint-incr style black test test_randomized pytest pytest_randomized test_ci coverage coverage_erase clean default: ruff style lint-incr test ; # Dependencies need to be installed on the Anaconda virtual environment. env: if test $(findstring qiskitenv, $(shell conda info --envs | tr '[:upper:]' '[:lower:]')); then \ bash -c "source activate Qiskitenv;pip install -r requirements.txt"; \ else \ conda create -y -n Qiskitenv python=3; \ bash -c "source activate Qiskitenv;pip install -r requirements.txt"; \ fi; # Ignoring generated ones with .py extension. lint: pylint -rn qiskit test tools tools/verify_headers.py qiskit test tools examples pylint -rn --disable='invalid-name, missing-module-docstring, redefined-outer-name' examples/python/*.py tools/find_optional_imports.py tools/find_stray_release_notes.py # Only pylint on files that have changed from origin/main. Also parallelize (disables cyclic-import check) lint-incr: -git fetch -q https://github.com/Qiskit/qiskit-terra.git :lint_incr_latest tools/pylint_incr.py -j4 -rn -sn --paths :/qiskit/*.py :/test/*.py :/tools/*.py tools/pylint_incr.py -j4 -rn -sn --disable='invalid-name, missing-module-docstring, redefined-outer-name' --paths ':(glob,top)examples/python/*.py' tools/verify_headers.py qiskit test tools examples tools/find_optional_imports.py ruff: ruff qiskit test tools examples setup.py style: black --check qiskit test tools examples setup.py black: black qiskit test tools examples setup.py # Use the -s (starting directory) flag for "unittest discover" is necessary, # otherwise the QuantumCircuit header will be modified during the discovery. test: @echo ================================================ @echo Consider using tox as suggested in the CONTRIBUTING.MD guideline. For running the tests as the CI, use test_ci @echo ================================================ python3 -m unittest discover -s test/python -t . -v @echo ================================================ @echo Consider using tox as suggested in the CONTRIBUTING.MD guideline. For running the tests as the CI, use test_ci @echo ================================================ # Use pytest to run tests pytest: pytest test/python # Use pytest to run randomized tests pytest_randomized: pytest test/randomized test_ci: QISKIT_TEST_CAPTURE_STREAMS=1 stestr run test_randomized: python3 -m unittest discover -s test/randomized -t . -v coverage: coverage3 run --source qiskit -m unittest discover -s test/python -q coverage3 report coverage_erase: coverage erase clean: coverage_erase ;
qiskit/Makefile/0
{ "file_path": "qiskit/Makefile", "repo_id": "qiskit", "token_count": 985 }
167
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // This code is licensed under the Apache License, Version 2.0. You may // obtain a copy of this license in the LICENSE.txt file in the root directory // of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. // // Any modifications or derivative works of this code must retain this // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. use std::ops::BitAnd; use approx::abs_diff_eq; use num_complex::{Complex64, ComplexFloat}; use pyo3::prelude::*; use pyo3::wrap_pyfunction; use pyo3::Python; use hashbrown::HashSet; use itertools::Itertools; use ndarray::prelude::*; use numpy::{IntoPyArray, PyReadonlyArray1, PyReadonlyArray2}; use qiskit_circuit::gate_matrix::ONE_QUBIT_IDENTITY; use qiskit_circuit::util::C_ZERO; /// Find special unitary matrix that maps [c0,c1] to [r,0] or [0,r] if basis_state=0 or /// basis_state=1 respectively #[pyfunction] pub fn reverse_qubit_state( py: Python, state: [Complex64; 2], basis_state: usize, epsilon: f64, ) -> PyObject { reverse_qubit_state_inner(&state, basis_state, epsilon) .into_pyarray_bound(py) .into() } #[inline(always)] fn l2_norm(vec: &[Complex64]) -> f64 { vec.iter() .fold(0., |acc, elem| acc + elem.norm_sqr()) .sqrt() } fn reverse_qubit_state_inner( state: &[Complex64; 2], basis_state: usize, epsilon: f64, ) -> Array2<Complex64> { let r = l2_norm(state); let r_inv = 1. / r; if r < epsilon { Array2::eye(2) } else if basis_state == 0 { array![ [state[0].conj() * r_inv, state[1].conj() * r_inv], [-state[1] * r_inv, state[0] * r_inv], ] } else { array![ [-state[1] * r_inv, state[0] * r_inv], [state[0].conj() * r_inv, state[1].conj() * r_inv], ] } } /// This method finds the single-qubit gates for a UCGate to disentangle a qubit: /// we consider the n-qubit state v[:,0] starting with k zeros (in the computational basis). /// The qubit with label n-s-1 is disentangled into the basis state k_s(k,s). #[pyfunction] pub fn find_squs_for_disentangling( py: Python, v: PyReadonlyArray2<Complex64>, k: usize, s: usize, epsilon: f64, n: usize, ) -> Vec<PyObject> { let v = v.as_array(); let k_prime = 0; let i_start = if b(k, s + 1) == 0 { a(k, s + 1) } else { a(k, s + 1) + 1 }; let mut output: Vec<Array2<Complex64>> = (0..i_start).map(|_| Array2::eye(2)).collect(); let mut squs: Vec<Array2<Complex64>> = (i_start..2_usize.pow((n - s - 1) as u32)) .map(|i| { reverse_qubit_state_inner( &[ v[[2 * i * 2_usize.pow(s as u32) + b(k, s), k_prime]], v[[(2 * i + 1) * 2_usize.pow(s as u32) + b(k, s), k_prime]], ], k_s(k, s), epsilon, ) }) .collect(); output.append(&mut squs); output .into_iter() .map(|x| x.into_pyarray_bound(py).into()) .collect() } #[pyfunction] pub fn apply_ucg( py: Python, m: PyReadonlyArray2<Complex64>, k: usize, single_qubit_gates: Vec<PyReadonlyArray2<Complex64>>, ) -> PyObject { let mut m = m.as_array().to_owned(); let shape = m.shape(); let num_qubits = shape[0].ilog2(); let num_col = shape[1]; let spacing: usize = 2_usize.pow(num_qubits - k as u32 - 1); for j in 0..2_usize.pow(num_qubits - 1) { let i = (j / spacing) * spacing + j; let gate_index = i / (2_usize.pow(num_qubits - k as u32)); for col in 0..num_col { let gate = single_qubit_gates[gate_index].as_array(); let a = m[[i, col]]; let b = m[[i + spacing, col]]; m[[i, col]] = gate[[0, 0]] * a + gate[[0, 1]] * b; m[[i + spacing, col]] = gate[[1, 0]] * a + gate[[1, 1]] * b; } } m.into_pyarray_bound(py).into() } #[inline(always)] fn bin_to_int(bin: &[u8]) -> usize { bin.iter() .fold(0_usize, |acc, digit| (acc << 1) + *digit as usize) } #[pyfunction] pub fn apply_diagonal_gate( py: Python, m: PyReadonlyArray2<Complex64>, action_qubit_labels: Vec<usize>, diag: PyReadonlyArray1<Complex64>, ) -> PyResult<PyObject> { let diag = diag.as_slice()?; let mut m = m.as_array().to_owned(); let shape = m.shape(); let num_qubits = shape[0].ilog2(); let num_col = shape[1]; for state in std::iter::repeat([0_u8, 1_u8]) .take(num_qubits as usize) .multi_cartesian_product() { let diag_index = action_qubit_labels .iter() .fold(0_usize, |acc, i| (acc << 1) + state[*i] as usize); let i = bin_to_int(&state); for j in 0..num_col { m[[i, j]] = diag[diag_index] * m[[i, j]] } } Ok(m.into_pyarray_bound(py).into()) } #[pyfunction] pub fn apply_diagonal_gate_to_diag( mut m_diagonal: Vec<Complex64>, action_qubit_labels: Vec<usize>, diag: PyReadonlyArray1<Complex64>, num_qubits: usize, ) -> PyResult<Vec<Complex64>> { let diag = diag.as_slice()?; if m_diagonal.is_empty() { return Ok(m_diagonal); } for state in std::iter::repeat([0_u8, 1_u8]) .take(num_qubits) .multi_cartesian_product() .take(m_diagonal.len()) { let diag_index = action_qubit_labels .iter() .fold(0_usize, |acc, i| (acc << 1) + state[*i] as usize); let i = bin_to_int(&state); m_diagonal[i] *= diag[diag_index] } Ok(m_diagonal) } /// Helper method for _apply_multi_controlled_gate. This constructs the basis states the MG gate /// is acting on for a specific state state_free of the qubits we neither control nor act on fn construct_basis_states( state_free: &[u8], control_set: &HashSet<usize>, target_label: usize, ) -> [usize; 2] { let size = state_free.len() + control_set.len() + 1; let mut e1: usize = 0; let mut e2: usize = 0; let mut j = 0; for i in 0..size { e1 <<= 1; e2 <<= 1; if control_set.contains(&i) { e1 += 1; e2 += 1; } else if i == target_label { e2 += 1; } else { e1 += state_free[j] as usize; e2 += state_free[j] as usize; j += 1 } } [e1, e2] } #[pyfunction] pub fn apply_multi_controlled_gate( py: Python, m: PyReadonlyArray2<Complex64>, control_labels: Vec<usize>, target_label: usize, gate: PyReadonlyArray2<Complex64>, ) -> PyObject { let mut m = m.as_array().to_owned(); let gate = gate.as_array(); let shape = m.shape(); let num_qubits = shape[0].ilog2(); let num_col = shape[1]; let free_qubits = num_qubits as usize - control_labels.len() - 1; let control_set: HashSet<usize> = control_labels.into_iter().collect(); if free_qubits == 0 { let [e1, e2] = construct_basis_states(&[], &control_set, target_label); for i in 0..num_col { let temp: Vec<_> = gate .dot(&aview2(&[[m[[e1, i]]], [m[[e2, i]]]])) .into_iter() .take(2) .collect(); m[[e1, i]] = temp[0]; m[[e2, i]] = temp[1]; } return m.into_pyarray_bound(py).into(); } for state_free in std::iter::repeat([0_u8, 1_u8]) .take(free_qubits) .multi_cartesian_product() { let [e1, e2] = construct_basis_states(&state_free, &control_set, target_label); for i in 0..num_col { let temp: Vec<_> = gate .dot(&aview2(&[[m[[e1, i]]], [m[[e2, i]]]])) .into_iter() .take(2) .collect(); m[[e1, i]] = temp[0]; m[[e2, i]] = temp[1]; } } m.into_pyarray_bound(py).into() } #[pyfunction] pub fn ucg_is_identity_up_to_global_phase( single_qubit_gates: Vec<PyReadonlyArray2<Complex64>>, epsilon: f64, ) -> bool { let global_phase: Complex64 = if single_qubit_gates[0].as_array()[[0, 0]].abs() >= epsilon { single_qubit_gates[0].as_array()[[0, 0]].finv() } else { return false; }; for raw_gate in single_qubit_gates { let gate = raw_gate.as_array(); if !abs_diff_eq!( gate.mapv(|x| x * global_phase), aview2(&ONE_QUBIT_IDENTITY), epsilon = 1e-8 // Default tolerance from numpy for allclose() ) { return false; } } true } #[pyfunction] fn diag_is_identity_up_to_global_phase(diag: Vec<Complex64>, epsilon: f64) -> bool { let global_phase: Complex64 = if diag[0].abs() >= epsilon { diag[0].finv() } else { return false; }; for d in diag { if (global_phase * d - 1.0).abs() >= epsilon { return false; } } true } #[pyfunction] pub fn merge_ucgate_and_diag( py: Python, single_qubit_gates: Vec<PyReadonlyArray2<Complex64>>, diag: Vec<Complex64>, ) -> Vec<PyObject> { single_qubit_gates .iter() .enumerate() .map(|(i, raw_gate)| { let gate = raw_gate.as_array(); let res = aview2(&[[diag[2 * i], C_ZERO], [C_ZERO, diag[2 * i + 1]]]).dot(&gate); res.into_pyarray_bound(py).into() }) .collect() } #[inline(always)] #[pyfunction] fn k_s(k: usize, s: usize) -> usize { if k == 0 { 0 } else { let filter = 1 << s; k.bitand(filter) >> s } } #[inline(always)] #[pyfunction] fn a(k: usize, s: usize) -> usize { k / 2_usize.pow(s as u32) } #[inline(always)] #[pyfunction] fn b(k: usize, s: usize) -> usize { k - (a(k, s) * 2_usize.pow(s as u32)) } pub fn isometry(m: &Bound<PyModule>) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(diag_is_identity_up_to_global_phase))?; m.add_wrapped(wrap_pyfunction!(find_squs_for_disentangling))?; m.add_wrapped(wrap_pyfunction!(reverse_qubit_state))?; m.add_wrapped(wrap_pyfunction!(apply_ucg))?; m.add_wrapped(wrap_pyfunction!(apply_diagonal_gate))?; m.add_wrapped(wrap_pyfunction!(apply_diagonal_gate_to_diag))?; m.add_wrapped(wrap_pyfunction!(apply_multi_controlled_gate))?; m.add_wrapped(wrap_pyfunction!(ucg_is_identity_up_to_global_phase))?; m.add_wrapped(wrap_pyfunction!(merge_ucgate_and_diag))?; m.add_wrapped(wrap_pyfunction!(a))?; m.add_wrapped(wrap_pyfunction!(b))?; m.add_wrapped(wrap_pyfunction!(k_s))?; Ok(()) }
qiskit/crates/accelerate/src/isometry.rs/0
{ "file_path": "qiskit/crates/accelerate/src/isometry.rs", "repo_id": "qiskit", "token_count": 5353 }
168
// This code is part of Qiskit. // // (C) Copyright IBM 2022 // // This code is licensed under the Apache License, Version 2.0. You may // obtain a copy of this license in the LICENSE.txt file in the root directory // of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. // // Any modifications or derivative works of this code must retain this // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. use hashbrown::HashMap; use pyo3::exceptions::PyIndexError; use pyo3::prelude::*; use crate::nlayout::PhysicalQubit; /// A container for required swaps before a gate qubit #[pyclass(module = "qiskit._accelerate.sabre")] #[derive(Clone, Debug)] pub struct SwapMap { pub map: HashMap<usize, Vec<[PhysicalQubit; 2]>>, } #[pymethods] impl SwapMap { // Mapping Protocol pub fn __len__(&self) -> usize { self.map.len() } pub fn __contains__(&self, object: usize) -> bool { self.map.contains_key(&object) } pub fn __getitem__(&self, object: usize) -> PyResult<Vec<[PhysicalQubit; 2]>> { match self.map.get(&object) { Some(val) => Ok(val.clone()), None => Err(PyIndexError::new_err(format!( "Node index {object} not in swap mapping", ))), } } pub fn __str__(&self) -> PyResult<String> { Ok(format!("{:?}", self.map)) } }
qiskit/crates/accelerate/src/sabre/swap_map.rs/0
{ "file_path": "qiskit/crates/accelerate/src/sabre/swap_map.rs", "repo_id": "qiskit", "token_count": 560 }
169
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // This code is licensed under the Apache License, Version 2.0. You may // obtain a copy of this license in the LICENSE.txt file in the root directory // of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. // // Any modifications or derivative works of this code must retain this // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. use ndarray::ArrayViewMut1; use ndarray::{Array1, ArrayView1}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use std::vec::Vec; use qiskit_circuit::slice::PySequenceIndex; pub fn validate_permutation(pattern: &ArrayView1<i64>) -> PyResult<()> { let n = pattern.len(); let mut seen: Vec<bool> = vec![false; n]; for &x in pattern { if x < 0 { return Err(PyValueError::new_err( "Invalid permutation: input contains a negative number.", )); } if x as usize >= n { return Err(PyValueError::new_err(format!( "Invalid permutation: input has length {} and contains {}.", n, x ))); } if seen[x as usize] { return Err(PyValueError::new_err(format!( "Invalid permutation: input contains {} more than once.", x ))); } seen[x as usize] = true; } Ok(()) } pub fn invert(pattern: &ArrayView1<i64>) -> Array1<usize> { let mut inverse: Array1<usize> = Array1::zeros(pattern.len()); pattern.iter().enumerate().for_each(|(ii, &jj)| { inverse[jj as usize] = ii; }); inverse } /// Sorts the input permutation by iterating through the permutation list /// and putting each element to its correct position via a SWAP (if it's not /// at the correct position already). If ``n`` is the length of the input /// permutation, this requires at most ``n`` SWAPs. /// /// More precisely, if the input permutation is a cycle of length ``m``, /// then this creates a quantum circuit with ``m-1`` SWAPs (and of depth ``m-1``); /// if the input permutation consists of several disjoint cycles, then each cycle /// is essentially treated independently. pub fn get_ordered_swap(pattern: &ArrayView1<i64>) -> Vec<(usize, usize)> { let mut permutation: Vec<usize> = pattern.iter().map(|&x| x as usize).collect(); let mut index_map = invert(pattern); let n = permutation.len(); let mut swaps: Vec<(usize, usize)> = Vec::with_capacity(n); for ii in 0..n { let val = permutation[ii]; if val == ii { continue; } let jj = index_map[ii]; swaps.push((ii, jj)); (permutation[ii], permutation[jj]) = (permutation[jj], permutation[ii]); index_map[val] = jj; index_map[ii] = ii; } swaps[..].reverse(); swaps } /// Explore cycles in a permutation pattern. This is probably best explained in an /// example: let a pattern be [1, 2, 3, 0, 4, 6, 5], then it contains the two /// cycles [1, 2, 3, 0] and [6, 5]. The index [4] does not perform a permutation and does /// therefore not create a cycle. pub fn pattern_to_cycles(pattern: &ArrayView1<usize>) -> Vec<Vec<usize>> { // vector keeping track of which elements in the permutation pattern have been visited let mut explored: Vec<bool> = vec![false; pattern.len()]; // vector to store the cycles let mut cycles: Vec<Vec<usize>> = Vec::new(); for pos in pattern { let mut cycle: Vec<usize> = Vec::new(); // follow the cycle until we reached an entry we saw before let mut i = *pos; while !explored[i] { cycle.push(i); explored[i] = true; i = pattern[i]; } // cycles must have more than 1 element if cycle.len() > 1 { cycles.push(cycle); } } cycles } /// Periodic (or Python-like) access to a vector. /// Util used below in ``decompose_cycles``. #[inline] fn pget(vec: &[usize], index: isize) -> usize { vec[PySequenceIndex::convert_idx(index, vec.len()).unwrap()] } /// Given a disjoint cycle decomposition of a permutation pattern (see the function /// ``pattern_to_cycles``), decomposes every cycle into a series of SWAPs to implement it. /// In combination with ``pattern_to_cycle``, this function allows to implement a /// full permutation pattern by applying SWAP gates on the returned index-pairs. pub fn decompose_cycles(cycles: &Vec<Vec<usize>>) -> Vec<(usize, usize)> { let mut swaps: Vec<(usize, usize)> = Vec::new(); for cycle in cycles { let length = cycle.len() as isize; for idx in 0..(length - 1) / 2 { swaps.push((pget(cycle, idx - 1), pget(cycle, length - 3 - idx))); } for idx in 0..length / 2 { swaps.push((pget(cycle, idx - 1), pget(cycle, length - 2 - idx))); } } swaps } /// Implements a single swap layer, consisting of conditional swaps between each /// neighboring couple. The starting_point is the first qubit to use (either 0 or 1 /// for even or odd layers respectively). Mutates the permutation pattern ``pattern``. pub fn create_swap_layer( pattern: &mut ArrayViewMut1<usize>, starting_point: usize, ) -> Vec<(usize, usize)> { let num_qubits = pattern.len(); let mut gates = Vec::new(); for j in (starting_point..num_qubits - 1).step_by(2) { if pattern[j] > pattern[j + 1] { gates.push((j, j + 1)); pattern.swap(j, j + 1); } } gates }
qiskit/crates/accelerate/src/synthesis/permutation/utils.rs/0
{ "file_path": "qiskit/crates/accelerate/src/synthesis/permutation/utils.rs", "repo_id": "qiskit", "token_count": 2217 }
170
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // This code is licensed under the Apache License, Version 2.0. You may // obtain a copy of this license in the LICENSE.txt file in the root directory // of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. // // Any modifications or derivative works of this code must retain this // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. #[cfg(feature = "cache_pygates")] use std::cell::OnceCell; use std::hash::Hasher; use crate::circuit_instruction::{CircuitInstruction, OperationFromPython}; use crate::imports::QUANTUM_CIRCUIT; use crate::operations::{Operation, Param}; use crate::TupleLikeArg; use ahash::AHasher; use approx::relative_eq; use rustworkx_core::petgraph::stable_graph::NodeIndex; use numpy::IntoPyArray; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::{PyString, PyTuple}; use pyo3::{intern, IntoPy, PyObject, PyResult, ToPyObject}; /// Parent class for DAGOpNode, DAGInNode, and DAGOutNode. #[pyclass(module = "qiskit._accelerate.circuit", subclass)] #[derive(Clone, Debug)] pub struct DAGNode { pub node: Option<NodeIndex>, } impl DAGNode { #[inline] pub fn py_nid(&self) -> isize { self.node .map(|node| node.index().try_into().unwrap()) .unwrap_or(-1) } } #[pymethods] impl DAGNode { #[new] #[pyo3(signature=(nid=-1))] fn py_new(nid: isize) -> PyResult<Self> { Ok(DAGNode { node: match nid { -1 => None, nid => { let index: usize = match nid.try_into() { Ok(index) => index, Err(_) => { return Err(PyValueError::new_err( "Invalid node index, must be -1 or a non-negative integer", )) } }; Some(NodeIndex::new(index)) } }, }) } #[getter(_node_id)] fn get_py_node_id(&self) -> isize { self.py_nid() } #[setter(_node_id)] fn set_py_node_id(&mut self, nid: isize) { self.node = match nid { -1 => None, nid => Some(NodeIndex::new(nid.try_into().unwrap())), } } fn __getstate__(&self) -> Option<usize> { self.node.map(|node| node.index()) } fn __setstate__(&mut self, index: Option<usize>) { self.node = index.map(NodeIndex::new); } fn __lt__(&self, other: &DAGNode) -> bool { self.py_nid() < other.py_nid() } fn __gt__(&self, other: &DAGNode) -> bool { self.py_nid() > other.py_nid() } fn __str__(_self: &Bound<DAGNode>) -> String { format!("{}", _self.as_ptr() as usize) } fn __hash__(&self, py: Python) -> PyResult<isize> { self.py_nid().into_py(py).bind(py).hash() } } /// Object to represent an Instruction at a node in the DAGCircuit. #[pyclass(module = "qiskit._accelerate.circuit", extends=DAGNode)] pub struct DAGOpNode { pub instruction: CircuitInstruction, #[pyo3(get)] pub sort_key: PyObject, } #[pymethods] impl DAGOpNode { #[new] #[pyo3(signature = (op, qargs=None, cargs=None, *, dag=None))] pub fn py_new( py: Python, op: Bound<PyAny>, qargs: Option<TupleLikeArg>, cargs: Option<TupleLikeArg>, #[allow(unused_variables)] dag: Option<Bound<PyAny>>, ) -> PyResult<Py<Self>> { let py_op = op.extract::<OperationFromPython>()?; let qargs = qargs.map_or_else(|| PyTuple::empty_bound(py), |q| q.value); let sort_key = qargs.str().unwrap().into(); let cargs = cargs.map_or_else(|| PyTuple::empty_bound(py), |c| c.value); let instruction = CircuitInstruction { operation: py_op.operation, qubits: qargs.unbind(), clbits: cargs.unbind(), params: py_op.params, extra_attrs: py_op.extra_attrs, #[cfg(feature = "cache_pygates")] py_op: op.unbind().into(), }; Py::new( py, ( DAGOpNode { instruction, sort_key, }, DAGNode { node: None }, ), ) } fn __hash__(slf: PyRef<'_, Self>) -> PyResult<u64> { let super_ = slf.as_ref(); let mut hasher = AHasher::default(); hasher.write_isize(super_.py_nid()); hasher.write(slf.instruction.operation.name().as_bytes()); Ok(hasher.finish()) } fn __eq__(slf: PyRef<Self>, py: Python, other: &Bound<PyAny>) -> PyResult<bool> { // This check is more restrictive by design as it's intended to replace // object identitity for set/dict membership and not be a semantic equivalence // check. We have an implementation of that as part of `DAGCircuit.__eq__` and // this method is specifically to ensure nodes are the same. This means things // like parameter equality are stricter to reject things like // Param::Float(0.1) == Param::ParameterExpression(0.1) (if the expression was // a python parameter equivalent to a bound value). let Ok(other) = other.downcast::<Self>() else { return Ok(false); }; let borrowed_other = other.borrow(); let other_super = borrowed_other.as_ref(); let super_ = slf.as_ref(); if super_.py_nid() != other_super.py_nid() { return Ok(false); } if !slf .instruction .operation .py_eq(py, &borrowed_other.instruction.operation)? { return Ok(false); } let params_eq = if slf.instruction.operation.try_standard_gate().is_some() { let mut params_eq = true; for (a, b) in slf .instruction .params .iter() .zip(borrowed_other.instruction.params.iter()) { let res = match [a, b] { [Param::Float(float_a), Param::Float(float_b)] => { relative_eq!(float_a, float_b, max_relative = 1e-10) } [Param::ParameterExpression(param_a), Param::ParameterExpression(param_b)] => { param_a.bind(py).eq(param_b)? } [Param::Obj(param_a), Param::Obj(param_b)] => param_a.bind(py).eq(param_b)?, _ => false, }; if !res { params_eq = false; break; } } params_eq } else { // We've already evaluated the parameters are equal here via the Python space equality // check so if we're not comparing standard gates and we've reached this point we know // the parameters are already equal. true }; Ok(params_eq && slf .instruction .qubits .bind(py) .eq(borrowed_other.instruction.qubits.clone_ref(py))? && slf .instruction .clbits .bind(py) .eq(borrowed_other.instruction.clbits.clone_ref(py))?) } #[pyo3(signature = (instruction, /, *, deepcopy=false))] #[staticmethod] fn from_instruction( py: Python, mut instruction: CircuitInstruction, deepcopy: bool, ) -> PyResult<PyObject> { let sort_key = instruction.qubits.bind(py).str().unwrap().into(); if deepcopy { instruction.operation = instruction.operation.py_deepcopy(py, None)?; #[cfg(feature = "cache_pygates")] { instruction.py_op = OnceCell::new(); } } let base = PyClassInitializer::from(DAGNode { node: None }); let sub = base.add_subclass(DAGOpNode { instruction, sort_key, }); Ok(Py::new(py, sub)?.to_object(py)) } fn __reduce__(slf: PyRef<Self>, py: Python) -> PyResult<PyObject> { let state = (slf.as_ref().node.map(|node| node.index()), &slf.sort_key); Ok(( py.get_type_bound::<Self>(), ( slf.instruction.get_operation(py)?, &slf.instruction.qubits, &slf.instruction.clbits, ), state, ) .into_py(py)) } fn __setstate__(mut slf: PyRefMut<Self>, state: &Bound<PyAny>) -> PyResult<()> { let (index, sort_key): (Option<usize>, PyObject) = state.extract()?; slf.as_mut().node = index.map(NodeIndex::new); slf.sort_key = sort_key; Ok(()) } /// Get a `CircuitInstruction` that represents the same information as this `DAGOpNode`. If /// `deepcopy`, any internal Python objects are deep-copied. /// /// Note: this ought to be a temporary method, while the DAG/QuantumCircuit converters still go /// via Python space; this still involves copy-out and copy-in of the data, whereas doing it all /// within Rust space could directly re-pack the instruction from a `DAGOpNode` to a /// `PackedInstruction` with no intermediate copy. #[pyo3(signature = (/, *, deepcopy=false))] fn _to_circuit_instruction(&self, py: Python, deepcopy: bool) -> PyResult<CircuitInstruction> { Ok(CircuitInstruction { operation: if deepcopy { self.instruction.operation.py_deepcopy(py, None)? } else { self.instruction.operation.clone() }, qubits: self.instruction.qubits.clone_ref(py), clbits: self.instruction.clbits.clone_ref(py), params: self.instruction.params.clone(), extra_attrs: self.instruction.extra_attrs.clone(), #[cfg(feature = "cache_pygates")] py_op: OnceCell::new(), }) } #[getter] fn get_op(&self, py: Python) -> PyResult<PyObject> { self.instruction.get_operation(py) } #[setter] fn set_op(&mut self, op: &Bound<PyAny>) -> PyResult<()> { let res = op.extract::<OperationFromPython>()?; self.instruction.operation = res.operation; self.instruction.params = res.params; self.instruction.extra_attrs = res.extra_attrs; #[cfg(feature = "cache_pygates")] { self.instruction.py_op = op.clone().unbind().into(); } Ok(()) } #[getter] fn num_qubits(&self) -> u32 { self.instruction.operation.num_qubits() } #[getter] fn num_clbits(&self) -> u32 { self.instruction.operation.num_clbits() } #[getter] pub fn get_qargs(&self, py: Python) -> Py<PyTuple> { self.instruction.qubits.clone_ref(py) } #[setter] fn set_qargs(&mut self, qargs: Py<PyTuple>) { self.instruction.qubits = qargs; } #[getter] pub fn get_cargs(&self, py: Python) -> Py<PyTuple> { self.instruction.clbits.clone_ref(py) } #[setter] fn set_cargs(&mut self, cargs: Py<PyTuple>) { self.instruction.clbits = cargs; } /// Returns the Instruction name corresponding to the op for this node #[getter] fn get_name(&self, py: Python) -> Py<PyString> { self.instruction.operation.name().into_py(py) } #[getter] fn get_params(&self, py: Python) -> PyObject { self.instruction.params.to_object(py) } #[setter] fn set_params(&mut self, val: smallvec::SmallVec<[crate::operations::Param; 3]>) { self.instruction.params = val; } #[getter] fn matrix(&self, py: Python) -> Option<PyObject> { let matrix = self.instruction.operation.matrix(&self.instruction.params); matrix.map(|mat| mat.into_pyarray_bound(py).into()) } #[getter] fn label(&self) -> Option<&str> { self.instruction .extra_attrs .as_ref() .and_then(|attrs| attrs.label.as_deref()) } #[getter] fn condition(&self, py: Python) -> Option<PyObject> { self.instruction .extra_attrs .as_ref() .and_then(|attrs| attrs.condition.as_ref().map(|x| x.clone_ref(py))) } #[getter] fn duration(&self, py: Python) -> Option<PyObject> { self.instruction .extra_attrs .as_ref() .and_then(|attrs| attrs.duration.as_ref().map(|x| x.clone_ref(py))) } #[getter] fn unit(&self) -> Option<&str> { self.instruction .extra_attrs .as_ref() .and_then(|attrs| attrs.unit.as_deref()) } /// Is the :class:`.Operation` contained in this node a Qiskit standard gate? pub fn is_standard_gate(&self) -> bool { self.instruction.is_standard_gate() } /// Is the :class:`.Operation` contained in this node a subclass of :class:`.ControlledGate`? pub fn is_controlled_gate(&self, py: Python) -> PyResult<bool> { self.instruction.is_controlled_gate(py) } /// Is the :class:`.Operation` contained in this node a directive? pub fn is_directive(&self) -> bool { self.instruction.is_directive() } /// Is the :class:`.Operation` contained in this node a control-flow operation (i.e. an instance /// of :class:`.ControlFlowOp`)? pub fn is_control_flow(&self) -> bool { self.instruction.is_control_flow() } /// Does this node contain any :class:`.ParameterExpression` parameters? pub fn is_parameterized(&self) -> bool { self.instruction.is_parameterized() } #[setter] fn set_label(&mut self, val: Option<String>) { match self.instruction.extra_attrs.as_mut() { Some(attrs) => attrs.label = val, None => { if val.is_some() { self.instruction.extra_attrs = Some(Box::new( crate::circuit_instruction::ExtraInstructionAttributes { label: val, duration: None, unit: None, condition: None, }, )) } } }; if let Some(attrs) = &self.instruction.extra_attrs { if attrs.label.is_none() && attrs.duration.is_none() && attrs.unit.is_none() && attrs.condition.is_none() { self.instruction.extra_attrs = None; } } } #[getter] fn definition<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> { self.instruction .operation .definition(&self.instruction.params) .map(|data| { QUANTUM_CIRCUIT .get_bound(py) .call_method1(intern!(py, "_from_circuit_data"), (data,)) }) .transpose() } /// Sets the Instruction name corresponding to the op for this node #[setter] fn set_name(&mut self, py: Python, new_name: PyObject) -> PyResult<()> { let op = self.instruction.get_operation_mut(py)?; op.setattr(intern!(py, "name"), new_name)?; self.instruction.operation = op.extract::<OperationFromPython>()?.operation; Ok(()) } /// Returns a representation of the DAGOpNode fn __repr__(&self, py: Python) -> PyResult<String> { Ok(format!( "DAGOpNode(op={}, qargs={}, cargs={})", self.instruction.get_operation(py)?.bind(py).repr()?, self.instruction.qubits.bind(py).repr()?, self.instruction.clbits.bind(py).repr()? )) } } /// Object to represent an incoming wire node in the DAGCircuit. #[pyclass(module = "qiskit._accelerate.circuit", extends=DAGNode)] pub struct DAGInNode { #[pyo3(get)] pub wire: PyObject, #[pyo3(get)] sort_key: PyObject, } impl DAGInNode { pub fn new(py: Python, node: NodeIndex, wire: PyObject) -> (Self, DAGNode) { ( DAGInNode { wire, sort_key: intern!(py, "[]").clone().into(), }, DAGNode { node: Some(node) }, ) } } #[pymethods] impl DAGInNode { #[new] fn py_new(py: Python, wire: PyObject) -> PyResult<(Self, DAGNode)> { Ok(( DAGInNode { wire, sort_key: intern!(py, "[]").clone().into(), }, DAGNode { node: None }, )) } fn __reduce__(slf: PyRef<Self>, py: Python) -> PyObject { let state = (slf.as_ref().node.map(|node| node.index()), &slf.sort_key); (py.get_type_bound::<Self>(), (&slf.wire,), state).into_py(py) } fn __setstate__(mut slf: PyRefMut<Self>, state: &Bound<PyAny>) -> PyResult<()> { let (index, sort_key): (Option<usize>, PyObject) = state.extract()?; slf.as_mut().node = index.map(NodeIndex::new); slf.sort_key = sort_key; Ok(()) } fn __hash__(slf: PyRef<'_, Self>, py: Python) -> PyResult<u64> { let super_ = slf.as_ref(); let mut hasher = AHasher::default(); hasher.write_isize(super_.py_nid()); hasher.write_isize(slf.wire.bind(py).hash()?); Ok(hasher.finish()) } fn __eq__(slf: PyRef<Self>, py: Python, other: &Bound<PyAny>) -> PyResult<bool> { match other.downcast::<Self>() { Ok(other) => { let borrowed_other = other.borrow(); let other_super = borrowed_other.as_ref(); let super_ = slf.as_ref(); Ok(super_.py_nid() == other_super.py_nid() && slf.wire.bind(py).eq(borrowed_other.wire.clone_ref(py))?) } Err(_) => Ok(false), } } /// Returns a representation of the DAGInNode fn __repr__(&self, py: Python) -> PyResult<String> { Ok(format!("DAGInNode(wire={})", self.wire.bind(py).repr()?)) } } /// Object to represent an outgoing wire node in the DAGCircuit. #[pyclass(module = "qiskit._accelerate.circuit", extends=DAGNode)] pub struct DAGOutNode { #[pyo3(get)] pub wire: PyObject, #[pyo3(get)] sort_key: PyObject, } impl DAGOutNode { pub fn new(py: Python, node: NodeIndex, wire: PyObject) -> (Self, DAGNode) { ( DAGOutNode { wire, sort_key: intern!(py, "[]").clone().into(), }, DAGNode { node: Some(node) }, ) } } #[pymethods] impl DAGOutNode { #[new] fn py_new(py: Python, wire: PyObject) -> PyResult<(Self, DAGNode)> { Ok(( DAGOutNode { wire, sort_key: intern!(py, "[]").clone().into(), }, DAGNode { node: None }, )) } fn __reduce__(slf: PyRef<Self>, py: Python) -> PyObject { let state = (slf.as_ref().node.map(|node| node.index()), &slf.sort_key); (py.get_type_bound::<Self>(), (&slf.wire,), state).into_py(py) } fn __setstate__(mut slf: PyRefMut<Self>, state: &Bound<PyAny>) -> PyResult<()> { let (index, sort_key): (Option<usize>, PyObject) = state.extract()?; slf.as_mut().node = index.map(NodeIndex::new); slf.sort_key = sort_key; Ok(()) } fn __hash__(slf: PyRef<'_, Self>, py: Python) -> PyResult<u64> { let super_ = slf.as_ref(); let mut hasher = AHasher::default(); hasher.write_isize(super_.py_nid()); hasher.write_isize(slf.wire.bind(py).hash()?); Ok(hasher.finish()) } /// Returns a representation of the DAGOutNode fn __repr__(&self, py: Python) -> PyResult<String> { Ok(format!("DAGOutNode(wire={})", self.wire.bind(py).repr()?)) } fn __eq__(slf: PyRef<Self>, py: Python, other: &Bound<PyAny>) -> PyResult<bool> { match other.downcast::<Self>() { Ok(other) => { let borrowed_other = other.borrow(); let other_super = borrowed_other.as_ref(); let super_ = slf.as_ref(); Ok(super_.py_nid() == other_super.py_nid() && slf.wire.bind(py).eq(borrowed_other.wire.clone_ref(py))?) } Err(_) => Ok(false), } } }
qiskit/crates/circuit/src/dag_node.rs/0
{ "file_path": "qiskit/crates/circuit/src/dag_node.rs", "repo_id": "qiskit", "token_count": 10248 }
171
[package] name = "qiskit-qasm2" version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true [lib] name = "qiskit_qasm2" doctest = false [dependencies] num-bigint.workspace = true hashbrown.workspace = true pyo3.workspace = true qiskit-circuit.workspace = true
qiskit/crates/qasm2/Cargo.toml/0
{ "file_path": "qiskit/crates/qasm2/Cargo.toml", "repo_id": "qiskit", "token_count": 114 }
172
{# We show all the class's methods and attributes on the same page. By default, we document all methods, including those defined by parent classes. -#} {{ objname | escape | underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :no-members: :show-inheritance: {% block attributes_summary %} {% if attributes %} .. rubric:: Attributes {% for item in attributes %} .. autoattribute:: {{ item }} {%- endfor %} {% endif %} {% endblock -%} {% block methods_summary %} {% set wanted_methods = (methods | reject('==', '__init__') | list) %} {% if wanted_methods %} .. rubric:: Methods {% for item in wanted_methods %} .. automethod:: {{ item }} {%- endfor %} {% endif %} {% endblock %}
qiskit/docs/_templates/autosummary/class.rst/0
{ "file_path": "qiskit/docs/_templates/autosummary/class.rst", "repo_id": "qiskit", "token_count": 271 }
173
.. _qiskit-providers-basicprovider: .. automodule:: qiskit.providers.basic_provider :no-members: :no-inherited-members: :no-special-members:
qiskit/docs/apidoc/providers_basic_provider.rst/0
{ "file_path": "qiskit/docs/apidoc/providers_basic_provider.rst", "repo_id": "qiskit", "token_count": 62 }
174
.. _qiskit-transpiler-plugins: .. automodule:: qiskit.transpiler.preset_passmanagers.plugin :no-members: :no-inherited-members: :no-special-members:
qiskit/docs/apidoc/transpiler_plugins.rst/0
{ "file_path": "qiskit/docs/apidoc/transpiler_plugins.rst", "repo_id": "qiskit", "token_count": 66 }
175
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum Fourier Transform examples. """ import math from qiskit import QuantumCircuit from qiskit import transpile from qiskit.providers.basic_provider import BasicSimulator ############################################################### # make the qft ############################################################### def input_state(circ, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(j) circ.p(-math.pi / float(2 ** (j)), j) def qft(circ, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cp(math.pi / float(2 ** (j - k)), j, k) circ.h(j) qft3 = QuantumCircuit(5, 5, name="qft3") qft4 = QuantumCircuit(5, 5, name="qft4") qft5 = QuantumCircuit(5, 5, name="qft5") input_state(qft3, 3) qft3.barrier() qft(qft3, 3) qft3.barrier() for j in range(3): qft3.measure(j, j) input_state(qft4, 4) qft4.barrier() qft(qft4, 4) qft4.barrier() for j in range(4): qft4.measure(j, j) input_state(qft5, 5) qft5.barrier() qft(qft5, 5) qft5.barrier() for j in range(5): qft5.measure(j, j) print(qft3) print(qft4) print(qft5) print("Basic simulator") sim_backend = BasicSimulator() job = sim_backend.run(transpile([qft3, qft4, qft5], sim_backend), shots=1024) result = job.result() print(result.get_counts(qft3)) print(result.get_counts(qft4)) print(result.get_counts(qft5))
qiskit/examples/python/qft.py/0
{ "file_path": "qiskit/examples/python/qft.py", "repo_id": "qiskit", "token_count": 743 }
176
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Models for RunConfig and its related components.""" from types import SimpleNamespace class RunConfig(SimpleNamespace): """Class for Run Configuration. Attributes: shots (int): the number of shots seed_simulator (int): the seed to use in the simulator memory (bool): whether to request memory from backend (per-shot readouts) parameter_binds (list[dict]): List of parameter bindings """ def __init__( self, shots=None, seed_simulator=None, memory=None, parameter_binds=None, **kwargs, ): """Initialize a RunConfig object Args: shots (int): the number of shots seed_simulator (int): the seed to use in the simulator memory (bool): whether to request memory from backend (per-shot readouts) parameter_binds (list[dict]): List of parameter bindings **kwargs: optional fields """ if shots is not None: self.shots = shots if seed_simulator is not None: self.seed_simulator = seed_simulator if memory is not None: self.memory = memory if parameter_binds is not None: self.parameter_binds = parameter_binds self.__dict__.update(kwargs) @classmethod def from_dict(cls, data): """Create a new RunConfig object from a dictionary. Args: data (dict): A dictionary representing the RunConfig to create. It will be in the same format as output by :meth:`to_dict`. Returns: RunConfig: The RunConfig from the input dictionary. """ return cls(**data) def to_dict(self): """Return a dictionary format representation of the RunConfig Returns: dict: The dictionary form of the RunConfig. """ return self.__dict__
qiskit/qiskit/assembler/run_config.py/0
{ "file_path": "qiskit/qiskit/assembler/run_config.py", "repo_id": "qiskit", "token_count": 988 }
177
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Type-system definition for the expression tree.""" # Given the nature of the tree representation and that there are helper functions associated with # many of the classes whose arguments naturally share names with themselves, it's inconvenient to # use synonyms everywhere. This goes for the builtin 'type' as well. # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "Type", "Bool", "Uint", ] import typing class _Singleton(type): """Metaclass to make the child, which should take zero initialization arguments, a singleton object.""" def _get_singleton_instance(cls): return cls._INSTANCE @classmethod def __prepare__(mcs, name, bases): # pylint: disable=unused-argument return {"__new__": mcs._get_singleton_instance} @staticmethod def __new__(cls, name, bases, namespace): out = super().__new__(cls, name, bases, namespace) out._INSTANCE = object.__new__(out) # pylint: disable=invalid-name return out class Type: """Root base class of all nodes in the type tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code.""" __slots__ = () @property def kind(self): """Get the kind of this type. This is exactly equal to the Python type object that defines this type, that is ``t.kind is type(t)``, but is exposed like this to make it clear that this a hashable enum-like discriminator you can rely on.""" return self.__class__ # Enforcement of immutability. The constructor methods need to manually skip this. def __setattr__(self, _key, _value): raise AttributeError(f"'{self.kind.__name__}' instances are immutable") def __copy__(self): return self def __deepcopy__(self, _memo): return self def __setstate__(self, state): _dict, slots = state for slot, value in slots.items(): # We need to overcome the type's enforcement of immutability post initialization. super().__setattr__(slot, value) @typing.final class Bool(Type, metaclass=_Singleton): """The Boolean type. This has exactly two values: ``True`` and ``False``.""" __slots__ = () def __repr__(self): return "Bool()" def __hash__(self): return hash(self.__class__) def __eq__(self, other): return isinstance(other, Bool) @typing.final class Uint(Type): """An unsigned integer of fixed bit width.""" __slots__ = ("width",) def __init__(self, width: int): if isinstance(width, int) and width <= 0: raise ValueError("uint width must be greater than zero") super(Type, self).__setattr__("width", width) def __repr__(self): return f"Uint({self.width})" def __hash__(self): return hash((self.__class__, self.width)) def __eq__(self, other): return isinstance(other, Uint) and self.width == other.width
qiskit/qiskit/circuit/classical/types/types.py/0
{ "file_path": "qiskit/qiskit/circuit/classical/types/types.py", "repo_id": "qiskit", "token_count": 1268 }
178
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The arithmetic circuit library.""" from .functional_pauli_rotations import FunctionalPauliRotations from .integer_comparator import IntegerComparator from .linear_pauli_rotations import LinearPauliRotations from .piecewise_linear_pauli_rotations import PiecewiseLinearPauliRotations from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations from .polynomial_pauli_rotations import PolynomialPauliRotations from .weighted_adder import WeightedAdder from .quadratic_form import QuadraticForm from .linear_amplitude_function import LinearAmplitudeFunction from .adders import VBERippleCarryAdder, CDKMRippleCarryAdder, DraperQFTAdder from .piecewise_chebyshev import PiecewiseChebyshev from .multipliers import HRSCumulativeMultiplier, RGQFTMultiplier from .exact_reciprocal import ExactReciprocal
qiskit/qiskit/circuit/library/arithmetic/__init__.py/0
{ "file_path": "qiskit/qiskit/circuit/library/arithmetic/__init__.py", "repo_id": "qiskit", "token_count": 374 }
179
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise-linearly-controlled rotation.""" from __future__ import annotations import numpy as np from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit from qiskit.circuit.exceptions import CircuitError from .functional_pauli_rotations import FunctionalPauliRotations from .linear_pauli_rotations import LinearPauliRotations from .integer_comparator import IntegerComparator class PiecewiseLinearPauliRotations(FunctionalPauliRotations): r"""Piecewise-linearly-controlled Pauli rotations. For a piecewise linear (not necessarily continuous) function :math:`f(x)`, which is defined through breakpoints, slopes and offsets as follows. Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where :math:`n` is the number of state qubits. Further on, denote the corresponding slopes and offsets by :math:`a_j` and :math:`b_j` respectively. Then f(x) is defined as: .. math:: f(x) = \begin{cases} 0, x < x_0 \\ a_j (x - x_j) + b_j, x_j \leq x < x_{j+1} \end{cases} where we implicitly assume :math:`x_{J+1} = 2^n`. """ def __init__( self, num_state_qubits: int | None = None, breakpoints: list[int] | None = None, slopes: list[float] | np.ndarray | None = None, offsets: list[float] | np.ndarray | None = None, basis: str = "Y", name: str = "pw_lin", ) -> None: """Construct piecewise-linearly-controlled Pauli rotations. Args: num_state_qubits: The number of qubits representing the state. breakpoints: The breakpoints to define the piecewise-linear function. Defaults to ``[0]``. slopes: The slopes for different segments of the piecewise-linear function. Defaults to ``[1]``. offsets: The offsets for different segments of the piecewise-linear function. Defaults to ``[0]``. basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``). name: The name of the circuit. """ # store parameters self._breakpoints = breakpoints if breakpoints is not None else [0] self._slopes = slopes if slopes is not None else [1] self._offsets = offsets if offsets is not None else [0] super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name) @property def breakpoints(self) -> list[int]: """The breakpoints of the piecewise linear function. The function is linear in the intervals ``[point_i, point_{i+1}]`` where the last point implicitly is ``2**(num_state_qubits + 1)``. """ return self._breakpoints @breakpoints.setter def breakpoints(self, breakpoints: list[int]) -> None: """Set the breakpoints. Args: breakpoints: The new breakpoints. """ self._invalidate() self._breakpoints = breakpoints if self.num_state_qubits and breakpoints: self._reset_registers(self.num_state_qubits) @property def slopes(self) -> list[float] | np.ndarray: """The breakpoints of the piecewise linear function. The function is linear in the intervals ``[point_i, point_{i+1}]`` where the last point implicitly is ``2**(num_state_qubits + 1)``. """ return self._slopes @slopes.setter def slopes(self, slopes: list[float]) -> None: """Set the slopes. Args: slopes: The new slopes. """ self._invalidate() self._slopes = slopes @property def offsets(self) -> list[float] | np.ndarray: """The breakpoints of the piecewise linear function. The function is linear in the intervals ``[point_i, point_{i+1}]`` where the last point implicitly is ``2**(num_state_qubits + 1)``. """ return self._offsets @offsets.setter def offsets(self, offsets: list[float]) -> None: """Set the offsets. Args: offsets: The new offsets. """ self._invalidate() self._offsets = offsets @property def mapped_slopes(self) -> np.ndarray: """The slopes mapped to the internal representation. Returns: The mapped slopes. """ mapped_slopes = np.zeros_like(self.slopes) for i, slope in enumerate(self.slopes): mapped_slopes[i] = slope - sum(mapped_slopes[:i]) return mapped_slopes @property def mapped_offsets(self) -> np.ndarray: """The offsets mapped to the internal representation. Returns: The mapped offsets. """ mapped_offsets = np.zeros_like(self.offsets) for i, (offset, slope, point) in enumerate( zip(self.offsets, self.slopes, self.breakpoints) ): mapped_offsets[i] = offset - slope * point - sum(mapped_offsets[:i]) return mapped_offsets @property def contains_zero_breakpoint(self) -> bool | np.bool_: """Whether 0 is the first breakpoint. Returns: True, if 0 is the first breakpoint, otherwise False. """ return np.isclose(0, self.breakpoints[0]) def evaluate(self, x: float) -> float: """Classically evaluate the piecewise linear rotation. Args: x: Value to be evaluated at. Returns: Value of piecewise linear function at x. """ y = (x >= self.breakpoints[0]) * (x * self.mapped_slopes[0] + self.mapped_offsets[0]) for i in range(1, len(self.breakpoints)): y = y + (x >= self.breakpoints[i]) * ( x * self.mapped_slopes[i] + self.mapped_offsets[i] ) return y def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " f"{self.num_state_qubits + 1}." ) if len(self.breakpoints) != len(self.slopes) or len(self.breakpoints) != len(self.offsets): valid = False if raise_on_failure: raise ValueError("Mismatching sizes of breakpoints, slopes and offsets.") return valid def _reset_registers(self, num_state_qubits: int | None) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits is not None: qr_state = QuantumRegister(num_state_qubits) qr_target = QuantumRegister(1) self.qregs = [qr_state, qr_target] # add ancillas if required if len(self.breakpoints) > 1: num_ancillas = num_state_qubits qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """If not already built, build the circuit.""" if self._is_built: return super()._build() circuit = QuantumCircuit(*self.qregs, name=self.name) qr_state = circuit.qubits[: self.num_state_qubits] qr_target = [circuit.qubits[self.num_state_qubits]] qr_ancilla = circuit.ancillas # apply comparators and controlled linear rotations for i, point in enumerate(self.breakpoints): if i == 0 and self.contains_zero_breakpoint: # apply rotation lin_r = LinearPauliRotations( num_state_qubits=self.num_state_qubits, slope=self.mapped_slopes[i], offset=self.mapped_offsets[i], basis=self.basis, ) circuit.append(lin_r.to_gate(), qr_state[:] + qr_target) else: qr_compare = [qr_ancilla[0]] qr_helper = qr_ancilla[1:] # apply Comparator comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point) qr = qr_state[:] + qr_compare[:] # add ancilla as compare qubit circuit.append(comp.to_gate(), qr[:] + qr_helper[: comp.num_ancillas]) # apply controlled rotation lin_r = LinearPauliRotations( num_state_qubits=self.num_state_qubits, slope=self.mapped_slopes[i], offset=self.mapped_offsets[i], basis=self.basis, ) circuit.append(lin_r.to_gate().control(), qr_compare[:] + qr_state[:] + qr_target) # uncompute comparator circuit.append(comp.to_gate().inverse(), qr[:] + qr_helper[: comp.num_ancillas]) self.append(circuit.to_gate(), self.qubits)
qiskit/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py/0
{ "file_path": "qiskit/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py", "repo_id": "qiskit", "token_count": 4342 }
180
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Prepare a quantum state from the state where all qubits are 0.""" from typing import Union, Optional import math import numpy as np from qiskit.exceptions import QiskitError from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.gate import Gate from qiskit.circuit.library.standard_gates.x import XGate from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.s import SGate, SdgGate from qiskit.circuit.library.generalized_gates import Isometry from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.states.statevector import ( Statevector, ) # pylint: disable=cyclic-import _EPS = 1e-10 # global variable used to chop very small numbers to zero class StatePreparation(Gate): """Complex amplitude state preparation. Class that implements the (complex amplitude) state preparation of some flexible collection of qubit registers. """ def __init__( self, params: Union[str, list, int, Statevector], num_qubits: Optional[int] = None, inverse: bool = False, label: Optional[str] = None, normalize: bool = False, ): r""" Args: params: * Statevector: Statevector to initialize to. * list: vector of complex amplitudes to initialize to. * string: labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * int: an integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. num_qubits: This parameter is only used if params is an int. Indicates the total number of qubits in the `initialize` call. Example: `initialize` covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to :math:`|1\rangle` and the remaining 3 qubits to be initialized to :math:`|0\rangle`. inverse: if True, the inverse state is constructed. label: An optional label for the gate normalize (bool): Whether to normalize an input array to a unit vector. Raises: QiskitError: ``num_qubits`` parameter used when ``params`` is not an integer When a Statevector argument is passed the state is prepared based on the :class:`~.library.Isometry` synthesis described in [1]. References: 1. Iten et al., Quantum circuits for isometries (2016). `Phys. Rev. A 93, 032318 <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.93.032318>`__. """ self._params_arg = params self._inverse = inverse self._name = "state_preparation_dg" if self._inverse else "state_preparation" if label is None: self._label = "State Preparation Dg" if self._inverse else "State Preparation" else: self._label = f"{label} Dg" if self._inverse else label if isinstance(params, Statevector): params = params.data if not isinstance(params, int) and num_qubits is not None: raise QiskitError( "The num_qubits parameter to StatePreparation should only be" " used when params is an integer" ) self._from_label = isinstance(params, str) self._from_int = isinstance(params, int) # if initialized from a vector, check that the parameters are normalized if not self._from_label and not self._from_int: norm = np.linalg.norm(params) if normalize: params = np.array(params, dtype=np.complex128) / norm elif not math.isclose(norm, 1.0, abs_tol=_EPS): raise QiskitError(f"Sum of amplitudes-squared is not 1, but {norm}.") num_qubits = self._get_num_qubits(num_qubits, params) params = [params] if isinstance(params, int) else params super().__init__(self._name, num_qubits, params, label=self._label) def _define(self): if self._from_label: self.definition = self._define_from_label() elif self._from_int: self.definition = self._define_from_int() else: self.definition = self._define_synthesis_isom() def _define_from_label(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") for qubit, param in enumerate(reversed(self.params)): if param == "1": initialize_circuit.append(XGate(), [q[qubit]]) elif param == "+": initialize_circuit.append(HGate(), [q[qubit]]) elif param == "-": initialize_circuit.append(XGate(), [q[qubit]]) initialize_circuit.append(HGate(), [q[qubit]]) elif param == "r": # |+i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SGate(), [q[qubit]]) elif param == "l": # |-i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SdgGate(), [q[qubit]]) if self._inverse: initialize_circuit = initialize_circuit.inverse() return initialize_circuit def _define_from_int(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") # Convert to int since QuantumCircuit converted to complex # and make a bit string and reverse it intstr = f"{int(np.real(self.params[0])):0{self.num_qubits}b}"[::-1] # Raise if number of bits is greater than num_qubits if len(intstr) > self.num_qubits: raise QiskitError( f"StatePreparation integer has {len(intstr)} bits, but this exceeds the" f" number of qubits in the circuit, {self.num_qubits}." ) for qubit, bit in enumerate(intstr): if bit == "1": initialize_circuit.append(XGate(), [q[qubit]]) # note: X is it's own inverse, so even if self._inverse is True, # we don't need to invert anything return initialize_circuit def _define_synthesis_isom(self): """Calculate a subcircuit that implements this initialization via isometry""" q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") isom = Isometry(self.params, 0, 0) initialize_circuit.compose(isom.definition, copy=False, inplace=True) # invert the circuit to create the desired vector from zero (assuming # the qubits are in the zero state) if self._inverse is True: return initialize_circuit.inverse() return initialize_circuit def _get_num_qubits(self, num_qubits, params): """Get number of qubits needed for state preparation""" if isinstance(params, str): num_qubits = len(params) elif isinstance(params, int): if num_qubits is None: num_qubits = int(math.log2(params)) + 1 else: num_qubits = math.log2(len(params)) # Check if param is a power of 2 if num_qubits == 0 or not num_qubits.is_integer(): raise QiskitError("Desired statevector length not a positive power of 2.") num_qubits = int(num_qubits) return num_qubits def inverse(self, annotated: bool = False): """Return inverted StatePreparation""" label = ( None if self._label in ("State Preparation", "State Preparation Dg") else self._label ) return StatePreparation(self._params_arg, inverse=not self._inverse, label=label) def broadcast_arguments(self, qargs, cargs): flat_qargs = [qarg for sublist in qargs for qarg in sublist] if self.num_qubits != len(flat_qargs): raise QiskitError( f"StatePreparation parameter vector has {2**self.num_qubits}" f" elements, therefore expects {self.num_qubits} " f"qubits. However, {len(flat_qargs)} were provided." ) yield flat_qargs, [] def validate_parameter(self, parameter): """StatePreparation instruction parameter can be str, int, float, and complex.""" # StatePreparation instruction parameter can be str if isinstance(parameter, str): if parameter in ["0", "1", "+", "-", "l", "r"]: return parameter raise CircuitError( f"invalid param label {type(parameter)} for instruction {self.name}. Label should be " "0, 1, +, -, l, or r " ) # StatePreparation instruction parameter can be int, float, and complex. if isinstance(parameter, (int, float, complex)): return complex(parameter) elif isinstance(parameter, np.number): return complex(parameter.item()) else: raise CircuitError(f"invalid param type {type(parameter)} for instruction {self.name}") def _return_repeat(self, exponent: float) -> "Gate": return Gate(name=f"{self.name}*{exponent}", num_qubits=self.num_qubits, params=[]) class UniformSuperpositionGate(Gate): r"""Implements a uniform superposition state. This gate is used to create the uniform superposition state :math:`\frac{1}{\sqrt{M}} \sum_{j=0}^{M-1} |j\rangle` when it acts on an input state :math:`|0...0\rangle`. Note, that `M` is not required to be a power of 2, in which case the uniform superposition could be prepared by a single layer of Hadamard gates. .. note:: This class uses the Shukla-Vedula algorithm [1], which only needs :math:`O(\log_2 (M))` qubits and :math:`O(\log_2 (M))` gates, to prepare the superposition. **References:** [1]: A. Shukla and P. Vedula (2024), An efficient quantum algorithm for preparation of uniform quantum superposition states, `Quantum Inf Process 23, 38 <https://link.springer.com/article/10.1007/s11128-024-04258-4>`_. """ def __init__( self, num_superpos_states: int = 2, num_qubits: Optional[int] = None, ): r""" Args: num_superpos_states (int): A positive integer M = num_superpos_states (> 1) representing the number of computational basis states with an amplitude of 1/sqrt(M) in the uniform superposition state (:math:`\frac{1}{\sqrt{M}} \sum_{j=0}^{M-1} |j\rangle`, where :math:`1< M <= 2^n`). Note that the remaining (:math:`2^n - M`) computational basis states have zero amplitudes. Here M need not be an integer power of 2. num_qubits (int): A positive integer representing the number of qubits used. If num_qubits is None or is not specified, then num_qubits is set to ceil(log2(num_superpos_states)). Raises: ValueError: num_qubits must be an integer greater than or equal to log2(num_superpos_states). """ if num_superpos_states <= 1: raise ValueError("num_superpos_states must be a positive integer greater than 1.") if num_qubits is None: num_qubits = int(math.ceil(math.log2(num_superpos_states))) else: if not (isinstance(num_qubits, int) and (num_qubits >= math.log2(num_superpos_states))): raise ValueError( "num_qubits must be an integer greater than or equal to log2(num_superpos_states)." ) super().__init__("USup", num_qubits, [num_superpos_states]) def _define(self): qc = QuantumCircuit(self._num_qubits) num_superpos_states = self.params[0] if ( num_superpos_states & (num_superpos_states - 1) ) == 0: # if num_superpos_states is an integer power of 2 m = int(math.log2(num_superpos_states)) qc.h(range(m)) self.definition = qc return n_value = [int(x) for x in reversed(np.binary_repr(num_superpos_states))] k = len(n_value) l_value = [index for (index, item) in enumerate(n_value) if item == 1] # Locations of '1's qc.x(l_value[1:k]) m_current_value = 2 ** l_value[0] theta = -2 * np.arccos(np.sqrt(m_current_value / num_superpos_states)) if l_value[0] > 0: # if num_superpos_states is even qc.h(range(l_value[0])) qc.ry(theta, l_value[1]) qc.ch(l_value[1], range(l_value[0], l_value[1]), ctrl_state="0") for m in range(1, len(l_value) - 1): theta = -2 * np.arccos( np.sqrt(2 ** l_value[m] / (num_superpos_states - m_current_value)) ) qc.cry(theta, l_value[m], l_value[m + 1], ctrl_state="0") qc.ch(l_value[m + 1], range(l_value[m], l_value[m + 1]), ctrl_state="0") m_current_value = m_current_value + 2 ** l_value[m] self.definition = qc
qiskit/qiskit/circuit/library/data_preparation/state_preparation.py/0
{ "file_path": "qiskit/qiskit/circuit/library/data_preparation/state_preparation.py", "repo_id": "qiskit", "token_count": 6124 }
181
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # The structure of the code is based on Emanuel Malvetti's semester thesis at ETH in 2018, # which was supervised by Raban Iten and Prof. Renato Renner. """Uniformly controlled Pauli rotations.""" from __future__ import annotations import math import numpy as np from qiskit.circuit.gate import Gate from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.exceptions import QiskitError _EPS = 1e-10 # global variable used to chop very small numbers to zero class UCPauliRotGate(Gate): r"""Uniformly controlled Pauli rotations. Implements the :class:`.UCGate` for the special case that all unitaries are Pauli rotations, :math:`U_i = R_P(a_i)` where :math:`P \in \{X, Y, Z\}` and :math:`a_i \in \mathbb{R}` is the rotation angle. """ def __init__(self, angle_list: list[float], rot_axis: str) -> None: r""" Args: angle_list: List of rotation angles :math:`[a_0, ..., a_{2^{k-1}}]`. rot_axis: Rotation axis. Must be either of ``"X"``, ``"Y"`` or ``"Z"``. """ self.rot_axes = rot_axis # Check if angle_list has type "list" if not isinstance(angle_list, list): raise QiskitError("The angles are not provided in a list.") # Check if the angles in angle_list are real numbers for angle in angle_list: try: float(angle) except TypeError as ex: raise QiskitError( "An angle cannot be converted to type float (real angles are expected)." ) from ex num_contr = math.log2(len(angle_list)) if num_contr < 0 or not num_contr.is_integer(): raise QiskitError( "The number of controlled rotation gates is not a non-negative power of 2." ) if rot_axis not in ("X", "Y", "Z"): raise QiskitError("Rotation axis is not supported.") # Create new gate. num_qubits = int(num_contr) + 1 super().__init__("ucr" + rot_axis.lower(), num_qubits, angle_list) def _define(self): ucr_circuit = self._dec_ucrot() gate = ucr_circuit.to_instruction() q = QuantumRegister(self.num_qubits, "q") ucr_circuit = QuantumCircuit(q) ucr_circuit.append(gate, q[:]) self.definition = ucr_circuit def _dec_ucrot(self): """ Finds a decomposition of a UC rotation gate into elementary gates (C-NOTs and single-qubit rotations). """ q = QuantumRegister(self.num_qubits, "q") circuit = QuantumCircuit(q) q_target = q[0] q_controls = q[1:] if not q_controls: # equivalent to: if len(q_controls) == 0 if self.rot_axes == "X": if np.abs(self.params[0]) > _EPS: circuit.rx(self.params[0], q_target) if self.rot_axes == "Y": if np.abs(self.params[0]) > _EPS: circuit.ry(self.params[0], q_target) if self.rot_axes == "Z": if np.abs(self.params[0]) > _EPS: circuit.rz(self.params[0], q_target) else: # First, we find the rotation angles of the single-qubit rotations acting # on the target qubit angles = self.params.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) # Now, it is easy to place the C-NOT gates to get back the full decomposition. for i, angle in enumerate(angles): if self.rot_axes == "X": if np.abs(angle) > _EPS: circuit.rx(angle, q_target) if self.rot_axes == "Y": if np.abs(angle) > _EPS: circuit.ry(angle, q_target) if self.rot_axes == "Z": if np.abs(angle) > _EPS: circuit.rz(angle, q_target) # Determine the index of the qubit we want to control the C-NOT gate. # Note that it corresponds # to the number of trailing zeros in the binary representation of i+1 if not i == len(angles) - 1: binary_rep = np.binary_repr(i + 1) q_contr_index = len(binary_rep) - len(binary_rep.rstrip("0")) else: # Handle special case: q_contr_index = len(q_controls) - 1 # For X rotations, we have to additionally place some Ry gates around the # C-NOT gates. They change the basis of the NOT operation, such that the # decomposition of for uniformly controlled X rotations works correctly by symmetry # with the decomposition of uniformly controlled Z or Y rotations if self.rot_axes == "X": circuit.ry(np.pi / 2, q_target) circuit.cx(q_controls[q_contr_index], q_target) if self.rot_axes == "X": circuit.ry(-np.pi / 2, q_target) return circuit @staticmethod def _dec_uc_rotations(angles, start_index, end_index, reversed_dec): """ Calculates rotation angles for a uniformly controlled R_t gate with a C-NOT gate at the end of the circuit. The rotation angles of the gate R_t are stored in angles[start_index:end_index]. If reversed_dec == True, it decomposes the gate such that there is a C-NOT gate at the start of the circuit (in fact, the circuit topology for the reversed decomposition is the reversed one of the original decomposition) """ interval_len_half = (end_index - start_index) // 2 for i in range(start_index, start_index + interval_len_half): if not reversed_dec: angles[i], angles[i + interval_len_half] = UCPauliRotGate._update_angles( angles[i], angles[i + interval_len_half] ) else: angles[i + interval_len_half], angles[i] = UCPauliRotGate._update_angles( angles[i], angles[i + interval_len_half] ) if interval_len_half <= 1: return else: UCPauliRotGate._dec_uc_rotations( angles, start_index, start_index + interval_len_half, False ) UCPauliRotGate._dec_uc_rotations( angles, start_index + interval_len_half, end_index, True ) @staticmethod def _update_angles(angle1, angle2): """Calculate the new rotation angles according to Shende's decomposition.""" return (angle1 + angle2) / 2.0, (angle1 - angle2) / 2.0
qiskit/qiskit/circuit/library/generalized_gates/uc_pauli_rot.py/0
{ "file_path": "qiskit/qiskit/circuit/library/generalized_gates/uc_pauli_rot.py", "repo_id": "qiskit", "token_count": 3343 }
182
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A generalized QAOA quantum circuit with a support of custom initial states and mixers.""" # pylint: disable=cyclic-import from __future__ import annotations import numpy as np from qiskit.circuit.parametervector import ParameterVector from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.quantum_info import SparsePauliOp from .evolved_operator_ansatz import EvolvedOperatorAnsatz, _is_pauli_identity class QAOAAnsatz(EvolvedOperatorAnsatz): """A generalized QAOA quantum circuit with a support of custom initial states and mixers. References: [1]: Farhi et al., A Quantum Approximate Optimization Algorithm. `arXiv:1411.4028 <https://arxiv.org/pdf/1411.4028>`_ """ def __init__( self, cost_operator=None, reps: int = 1, initial_state: QuantumCircuit | None = None, mixer_operator=None, name: str = "QAOA", flatten: bool | None = None, ): r""" Args: cost_operator (BaseOperator or OperatorBase, optional): The operator representing the cost of the optimization problem, denoted as :math:`U(C, \gamma)` in the original paper. Must be set either in the constructor or via property setter. reps (int): The integer parameter p, which determines the depth of the circuit, as specified in the original paper, default is 1. initial_state (QuantumCircuit, optional): An optional initial state to use. If `None` is passed then a set of Hadamard gates is applied as an initial state to all qubits. mixer_operator (BaseOperator or OperatorBase or QuantumCircuit, optional): An optional custom mixer to use instead of the global X-rotations, denoted as :math:`U(B, \beta)` in the original paper. Can be an operator or an optionally parameterized quantum circuit. name (str): A name of the circuit, default 'qaoa' flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ super().__init__(reps=reps, name=name, flatten=flatten) self._cost_operator = None self._reps = reps self._initial_state: QuantumCircuit | None = initial_state self._mixer = mixer_operator # set this circuit as a not-built circuit self._bounds: list[tuple[float | None, float | None]] | None = None # store cost operator and set the registers if the operator is not None self.cost_operator = cost_operator def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if not super()._check_configuration(raise_on_failure): return False if self.cost_operator is None: valid = False if raise_on_failure: raise ValueError( "The operator representing the cost of the optimization problem is not set" ) if self.initial_state is not None and self.initial_state.num_qubits != self.num_qubits: valid = False if raise_on_failure: raise ValueError( f"The number of qubits of the initial state {self.initial_state.num_qubits}" " does not match " f"the number of qubits of the cost operator {self.num_qubits}" ) if self.mixer_operator is not None and self.mixer_operator.num_qubits != self.num_qubits: valid = False if raise_on_failure: raise ValueError( f"The number of qubits of the mixer {self.mixer_operator.num_qubits}" f" does not match " f"the number of qubits of the cost operator {self.num_qubits}" ) return valid @property def parameter_bounds(self) -> list[tuple[float | None, float | None]] | None: """The parameter bounds for the unbound parameters in the circuit. Returns: A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If None is returned, problem is fully unbounded. """ if self._bounds is not None: return self._bounds # if the mixer is a circuit, we set no bounds if isinstance(self.mixer_operator, QuantumCircuit): return None # default bounds: None for gamma (cost operator), [0, 2pi] for gamma (mixer operator) beta_bounds = (0, 2 * np.pi) gamma_bounds = (None, None) bounds: list[tuple[float | None, float | None]] = [] if not _is_pauli_identity(self.mixer_operator): bounds += self.reps * [beta_bounds] if not _is_pauli_identity(self.cost_operator): bounds += self.reps * [gamma_bounds] return bounds @parameter_bounds.setter def parameter_bounds(self, bounds: list[tuple[float | None, float | None]] | None) -> None: """Set the parameter bounds. Args: bounds: The new parameter bounds. """ self._bounds = bounds @property def operators(self) -> list: """The operators that are evolved in this circuit. Returns: List[Union[BaseOperator, OperatorBase, QuantumCircuit]]: The operators to be evolved (and circuits) in this ansatz. """ return [self.cost_operator, self.mixer_operator] @property def cost_operator(self): """Returns an operator representing the cost of the optimization problem. Returns: BaseOperator or OperatorBase: cost operator. """ return self._cost_operator @cost_operator.setter def cost_operator(self, cost_operator) -> None: """Sets cost operator. Args: cost_operator (BaseOperator or OperatorBase, optional): cost operator to set. """ self._cost_operator = cost_operator self.qregs = [QuantumRegister(self.num_qubits, name="q")] self._invalidate() @property def reps(self) -> int: """Returns the `reps` parameter, which determines the depth of the circuit.""" return self._reps @reps.setter def reps(self, reps: int) -> None: """Sets the `reps` parameter.""" self._reps = reps self._invalidate() @property def initial_state(self) -> QuantumCircuit | None: """Returns an optional initial state as a circuit""" if self._initial_state is not None: return self._initial_state # if no initial state is passed and we know the number of qubits, then initialize it. if self.num_qubits > 0: initial_state = QuantumCircuit(self.num_qubits) initial_state.h(range(self.num_qubits)) return initial_state # otherwise we cannot provide a default return None @initial_state.setter def initial_state(self, initial_state: QuantumCircuit | None) -> None: """Sets initial state.""" self._initial_state = initial_state self._invalidate() # we can't directly specify OperatorBase as a return type, it causes a circular import # and pylint objects if return type is not documented @property def mixer_operator(self): """Returns an optional mixer operator expressed as an operator or a quantum circuit. Returns: BaseOperator or OperatorBase or QuantumCircuit, optional: mixer operator or circuit. """ if self._mixer is not None: return self._mixer # if no mixer is passed and we know the number of qubits, then initialize it. if self.cost_operator is not None: # local imports to avoid circular imports num_qubits = self.cost_operator.num_qubits # Mixer is just a sum of single qubit X's on each qubit. Evolving by this operator # will simply produce rx's on each qubit. mixer_terms = [ ("I" * left + "X" + "I" * (num_qubits - left - 1), 1) for left in range(num_qubits) ] mixer = SparsePauliOp.from_list(mixer_terms) return mixer # otherwise we cannot provide a default return None @mixer_operator.setter def mixer_operator(self, mixer_operator) -> None: """Sets mixer operator. Args: mixer_operator (BaseOperator or OperatorBase or QuantumCircuit, optional): mixer operator or circuit to set. """ self._mixer = mixer_operator self._invalidate() @property def num_qubits(self) -> int: if self._cost_operator is None: return 0 return self._cost_operator.num_qubits def _build(self): """If not already built, build the circuit.""" if self._is_built: return super()._build() # keep old parameter order: first cost operator, then mixer operators num_cost = 0 if _is_pauli_identity(self.cost_operator) else 1 if isinstance(self.mixer_operator, QuantumCircuit): num_mixer = self.mixer_operator.num_parameters else: num_mixer = 0 if _is_pauli_identity(self.mixer_operator) else 1 betas = ParameterVector("Ξ²", self.reps * num_mixer) gammas = ParameterVector("Ξ³", self.reps * num_cost) # Create a permutation to take us from (cost_1, mixer_1, cost_2, mixer_2, ...) # to (cost_1, cost_2, ..., mixer_1, mixer_2, ...), or if the mixer is a circuit # with more than 1 parameters, from (cost_1, mixer_1a, mixer_1b, cost_2, ...) # to (cost_1, cost_2, ..., mixer_1a, mixer_1b, mixer_2a, mixer_2b, ...) reordered = [] for rep in range(self.reps): reordered.extend(gammas[rep * num_cost : (rep + 1) * num_cost]) reordered.extend(betas[rep * num_mixer : (rep + 1) * num_mixer]) self.assign_parameters(dict(zip(self.ordered_parameters, reordered)), inplace=True)
qiskit/qiskit/circuit/library/n_local/qaoa_ansatz.py/0
{ "file_path": "qiskit/qiskit/circuit/library/n_local/qaoa_ansatz.py", "repo_id": "qiskit", "token_count": 4596 }
183
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Multiple-Controlled U3 gate. Not using ancillary qubits. """ from math import pi import math from typing import Optional, Union, Tuple, List import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, Qubit, ParameterExpression from qiskit.circuit.library.standard_gates.x import MCXGate from qiskit.circuit.library.standard_gates.u3 import _generate_gray_code from qiskit.circuit.parameterexpression import ParameterValueType from qiskit.exceptions import QiskitError def _apply_cu(circuit, theta, phi, lam, control, target, use_basis_gates=True): if use_basis_gates: # pylint: disable=cyclic-import # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # control: ─ P(Ξ»/2 + Ο†/2) β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # target: ─ P(Ξ»/2 - Ο†/2) β”œβ”€ X β”œβ”€ U(-0.5*0,0,-0.5*Ξ» - 0.5*Ο†) β”œβ”€ X β”œβ”€ U(0/2,Ο†,0) β”œ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ circuit.p((lam + phi) / 2, [control]) circuit.p((lam - phi) / 2, [target]) circuit.cx(control, target) circuit.u(-theta / 2, 0, -(phi + lam) / 2, [target]) circuit.cx(control, target) circuit.u(theta / 2, phi, 0, [target]) else: circuit.cu(theta, phi, lam, 0, control, target) def _apply_mcu_graycode(circuit, theta, phi, lam, ctls, tgt, use_basis_gates): """Apply multi-controlled u gate from ctls to tgt using graycode pattern with single-step angles theta, phi, lam.""" n = len(ctls) gray_code = _generate_gray_code(n) last_pattern = None for pattern in gray_code: if "1" not in pattern: continue if last_pattern is None: last_pattern = pattern # find left most set bit lm_pos = list(pattern).index("1") # find changed bit comp = [i != j for i, j in zip(pattern, last_pattern)] if True in comp: pos = comp.index(True) else: pos = None if pos is not None: if pos != lm_pos: circuit.cx(ctls[pos], ctls[lm_pos]) else: indices = [i for i, x in enumerate(pattern) if x == "1"] for idx in indices[1:]: circuit.cx(ctls[idx], ctls[lm_pos]) # check parity and undo rotation if pattern.count("1") % 2 == 0: # inverse CU: u(theta, phi, lamb)^dagger = u(-theta, -lam, -phi) _apply_cu( circuit, -theta, -lam, -phi, ctls[lm_pos], tgt, use_basis_gates=use_basis_gates ) else: _apply_cu(circuit, theta, phi, lam, ctls[lm_pos], tgt, use_basis_gates=use_basis_gates) last_pattern = pattern def _mcsu2_real_diagonal( unitary: np.ndarray, num_controls: int, ctrl_state: Optional[str] = None, use_basis_gates: bool = False, ) -> QuantumCircuit: """ Return a multi-controlled SU(2) gate [1]_ with a real main diagonal or secondary diagonal. Args: unitary: SU(2) unitary matrix with one real diagonal. num_controls: The number of control qubits. ctrl_state: The state on which the SU(2) operation is controlled. Defaults to all control qubits being in state 1. use_basis_gates: If ``True``, use ``[p, u, cx]`` gates to implement the decomposition. Returns: A :class:`.QuantumCircuit` implementing the multi-controlled SU(2) gate. Raises: QiskitError: If the input matrix is invalid. References: .. [1]: R. Vale et al. Decomposition of Multi-controlled Special Unitary Single-Qubit Gates `arXiv:2302.06377 (2023) <https://arxiv.org/abs/2302.06377>`__ """ # pylint: disable=cyclic-import from .x import MCXVChain from qiskit.circuit.library.generalized_gates import UnitaryGate from qiskit.quantum_info.operators.predicates import is_unitary_matrix from qiskit.compiler import transpile if unitary.shape != (2, 2): raise QiskitError(f"The unitary must be a 2x2 matrix, but has shape {unitary.shape}.") if not is_unitary_matrix(unitary): raise QiskitError(f"The unitary in must be an unitary matrix, but is {unitary}.") if not np.isclose(1.0, np.linalg.det(unitary)): raise QiskitError("Invalid Value _mcsu2_real_diagonal requires det(unitary) equal to one.") is_main_diag_real = np.isclose(unitary[0, 0].imag, 0.0) and np.isclose(unitary[1, 1].imag, 0.0) is_secondary_diag_real = np.isclose(unitary[0, 1].imag, 0.0) and np.isclose( unitary[1, 0].imag, 0.0 ) if not is_main_diag_real and not is_secondary_diag_real: raise QiskitError("The unitary must have one real diagonal.") if is_secondary_diag_real: x = unitary[0, 1] z = unitary[1, 1] else: x = -unitary[0, 1].real z = unitary[1, 1] - unitary[0, 1].imag * 1.0j if np.isclose(z, -1): s_op = [[1.0, 0.0], [0.0, 1.0j]] else: alpha_r = math.sqrt((math.sqrt((z.real + 1.0) / 2.0) + 1.0) / 2.0) alpha_i = z.imag / ( 2.0 * math.sqrt((z.real + 1.0) * (math.sqrt((z.real + 1.0) / 2.0) + 1.0)) ) alpha = alpha_r + 1.0j * alpha_i beta = x / (2.0 * math.sqrt((z.real + 1.0) * (math.sqrt((z.real + 1.0) / 2.0) + 1.0))) # S gate definition s_op = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]]) s_gate = UnitaryGate(s_op) k_1 = math.ceil(num_controls / 2.0) k_2 = math.floor(num_controls / 2.0) ctrl_state_k_1 = None ctrl_state_k_2 = None if ctrl_state is not None: str_ctrl_state = f"{ctrl_state:0{num_controls}b}" ctrl_state_k_1 = str_ctrl_state[::-1][:k_1][::-1] ctrl_state_k_2 = str_ctrl_state[::-1][k_1:][::-1] circuit = QuantumCircuit(num_controls + 1, name="MCSU2") controls = list(range(num_controls)) # control indices, defined for code legibility target = num_controls # target index, defined for code legibility if not is_secondary_diag_real: circuit.h(target) mcx_1 = MCXVChain(num_ctrl_qubits=k_1, dirty_ancillas=True, ctrl_state=ctrl_state_k_1) circuit.append(mcx_1, controls[:k_1] + [target] + controls[k_1 : 2 * k_1 - 2]) circuit.append(s_gate, [target]) mcx_2 = MCXVChain( num_ctrl_qubits=k_2, dirty_ancillas=True, ctrl_state=ctrl_state_k_2, # action_only=general_su2_optimization # Requires PR #9687 ) circuit.append(mcx_2.inverse(), controls[k_1:] + [target] + controls[k_1 - k_2 + 2 : k_1]) circuit.append(s_gate.inverse(), [target]) mcx_3 = MCXVChain(num_ctrl_qubits=k_1, dirty_ancillas=True, ctrl_state=ctrl_state_k_1) circuit.append(mcx_3, controls[:k_1] + [target] + controls[k_1 : 2 * k_1 - 2]) circuit.append(s_gate, [target]) mcx_4 = MCXVChain(num_ctrl_qubits=k_2, dirty_ancillas=True, ctrl_state=ctrl_state_k_2) circuit.append(mcx_4, controls[k_1:] + [target] + controls[k_1 - k_2 + 2 : k_1]) circuit.append(s_gate.inverse(), [target]) if not is_secondary_diag_real: circuit.h(target) if use_basis_gates: circuit = transpile(circuit, basis_gates=["p", "u", "cx"], qubits_initially_zero=False) return circuit def mcrx( self, theta: ParameterValueType, q_controls: Union[QuantumRegister, List[Qubit]], q_target: Qubit, use_basis_gates: bool = False, ): """ Apply Multiple-Controlled X rotation gate Args: self (QuantumCircuit): The QuantumCircuit object to apply the mcrx gate on. theta (float): angle theta q_controls (QuantumRegister or list(Qubit)): The list of control qubits q_target (Qubit): The target qubit use_basis_gates (bool): use p, u, cx Raises: QiskitError: parameter errors """ from .rx import RXGate control_qubits = self._qbit_argument_conversion(q_controls) target_qubit = self._qbit_argument_conversion(q_target) if len(target_qubit) != 1: raise QiskitError("The mcrz gate needs a single qubit as target.") all_qubits = control_qubits + target_qubit target_qubit = target_qubit[0] self._check_dups(all_qubits) n_c = len(control_qubits) if n_c == 1: # cu _apply_cu( self, theta, -pi / 2, pi / 2, control_qubits[0], target_qubit, use_basis_gates=use_basis_gates, ) elif n_c < 4: theta_step = theta * (1 / (2 ** (n_c - 1))) _apply_mcu_graycode( self, theta_step, -pi / 2, pi / 2, control_qubits, target_qubit, use_basis_gates=use_basis_gates, ) else: if isinstance(theta, ParameterExpression): raise QiskitError(f"Cannot synthesize MCRX with unbound parameter: {theta}.") cgate = _mcsu2_real_diagonal( RXGate(theta).to_matrix(), num_controls=len(control_qubits), use_basis_gates=use_basis_gates, ) self.compose(cgate, control_qubits + [target_qubit], inplace=True) def mcry( self, theta: ParameterValueType, q_controls: Union[QuantumRegister, List[Qubit]], q_target: Qubit, q_ancillae: Optional[Union[QuantumRegister, Tuple[QuantumRegister, int]]] = None, mode: Optional[str] = None, use_basis_gates: bool = False, ): """ Apply Multiple-Controlled Y rotation gate Args: self (QuantumCircuit): The QuantumCircuit object to apply the mcry gate on. theta (float): angle theta q_controls (list(Qubit)): The list of control qubits q_target (Qubit): The target qubit q_ancillae (QuantumRegister or tuple(QuantumRegister, int)): The list of ancillary qubits. mode (string): The implementation mode to use use_basis_gates (bool): use p, u, cx Raises: QiskitError: parameter errors """ from .ry import RYGate control_qubits = self._qbit_argument_conversion(q_controls) target_qubit = self._qbit_argument_conversion(q_target) if len(target_qubit) != 1: raise QiskitError("The mcrz gate needs a single qubit as target.") ancillary_qubits = [] if q_ancillae is None else self._qbit_argument_conversion(q_ancillae) all_qubits = control_qubits + target_qubit + ancillary_qubits target_qubit = target_qubit[0] self._check_dups(all_qubits) # auto-select the best mode if mode is None: # if enough ancillary qubits are provided, use the 'v-chain' method additional_vchain = MCXGate.get_num_ancilla_qubits(len(control_qubits), "v-chain") if len(ancillary_qubits) >= additional_vchain: mode = "basic" else: mode = "noancilla" if mode == "basic": self.ry(theta / 2, q_target) self.mcx(q_controls, q_target, q_ancillae, mode="v-chain") self.ry(-theta / 2, q_target) self.mcx(q_controls, q_target, q_ancillae, mode="v-chain") elif mode == "noancilla": n_c = len(control_qubits) if n_c == 1: # cu _apply_cu( self, theta, 0, 0, control_qubits[0], target_qubit, use_basis_gates=use_basis_gates ) elif n_c < 4: theta_step = theta * (1 / (2 ** (n_c - 1))) _apply_mcu_graycode( self, theta_step, 0, 0, control_qubits, target_qubit, use_basis_gates=use_basis_gates, ) else: if isinstance(theta, ParameterExpression): raise QiskitError(f"Cannot synthesize MCRY with unbound parameter: {theta}.") cgate = _mcsu2_real_diagonal( RYGate(theta).to_matrix(), num_controls=len(control_qubits), use_basis_gates=use_basis_gates, ) self.compose(cgate, control_qubits + [target_qubit], inplace=True) else: raise QiskitError(f"Unrecognized mode for building MCRY circuit: {mode}.") def mcrz( self, lam: ParameterValueType, q_controls: Union[QuantumRegister, List[Qubit]], q_target: Qubit, use_basis_gates: bool = False, ): """ Apply Multiple-Controlled Z rotation gate Args: self (QuantumCircuit): The QuantumCircuit object to apply the mcrz gate on. lam (float): angle lambda q_controls (list(Qubit)): The list of control qubits q_target (Qubit): The target qubit use_basis_gates (bool): use p, u, cx Raises: QiskitError: parameter errors """ from .rz import CRZGate, RZGate control_qubits = self._qbit_argument_conversion(q_controls) target_qubit = self._qbit_argument_conversion(q_target) if len(target_qubit) != 1: raise QiskitError("The mcrz gate needs a single qubit as target.") all_qubits = control_qubits + target_qubit target_qubit = target_qubit[0] self._check_dups(all_qubits) n_c = len(control_qubits) if n_c == 1: if use_basis_gates: self.u(0, 0, lam / 2, target_qubit) self.cx(control_qubits[0], target_qubit) self.u(0, 0, -lam / 2, target_qubit) self.cx(control_qubits[0], target_qubit) else: self.append(CRZGate(lam), control_qubits + [target_qubit]) else: if isinstance(lam, ParameterExpression): raise QiskitError(f"Cannot synthesize MCRZ with unbound parameter: {lam}.") cgate = _mcsu2_real_diagonal( RZGate(lam).to_matrix(), num_controls=len(control_qubits), use_basis_gates=use_basis_gates, ) self.compose(cgate, control_qubits + [target_qubit], inplace=True) QuantumCircuit.mcrx = mcrx QuantumCircuit.mcry = mcry QuantumCircuit.mcrz = mcrz
qiskit/qiskit/circuit/library/standard_gates/multi_control_rotation_gates.py/0
{ "file_path": "qiskit/qiskit/circuit/library/standard_gates/multi_control_rotation_gates.py", "repo_id": "qiskit", "token_count": 6817 }
184
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """One-pulse single-qubit gate.""" from math import sqrt, pi from cmath import exp from typing import Optional import numpy from qiskit.circuit.gate import Gate from qiskit.circuit.parameterexpression import ParameterValueType from qiskit.circuit.quantumregister import QuantumRegister from qiskit._accelerate.circuit import StandardGate class U2Gate(Gate): r"""Single-qubit rotation about the X+Z axis. Implemented using one X90 pulse on IBM Quantum systems: .. warning:: This gate is deprecated. Instead, the following replacements should be used .. math:: U2(\phi, \lambda) = U\left(\frac{\pi}{2}, \phi, \lambda\right) .. code-block:: python circuit = QuantumCircuit(1) circuit.u(pi/2, phi, lambda) **Circuit symbol:** .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ U2(Ο†,Ξ») β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ **Matrix Representation:** .. math:: U2(\phi, \lambda) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & -e^{i\lambda} \\ e^{i\phi} & e^{i(\phi+\lambda)} \end{pmatrix} **Examples:** .. math:: U2(\phi,\lambda) = e^{i \frac{\phi + \lambda}{2}}RZ(\phi) RY\left(\frac{\pi}{2}\right) RZ(\lambda) = e^{- i\frac{\pi}{4}} P\left(\frac{\pi}{2} + \phi\right) \sqrt{X} P\left(\lambda- \frac{\pi}{2}\right) .. math:: U2(0, \pi) = H .. math:: U2(0, 0) = RY(\pi/2) .. math:: U2(-\pi/2, \pi/2) = RX(\pi/2) .. seealso:: :class:`~qiskit.circuit.library.standard_gates.U3Gate`: U3 is a generalization of U2 that covers all single-qubit rotations, using two X90 pulses. """ _standard_gate = StandardGate.U2Gate def __init__( self, phi: ParameterValueType, lam: ParameterValueType, label: Optional[str] = None, *, duration=None, unit="dt", ): """Create new U2 gate.""" super().__init__("u2", 1, [phi, lam], label=label, duration=duration, unit=unit) def _define(self): # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate q = QuantumRegister(1, "q") qc = QuantumCircuit(q, name=self.name) rules = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])] for instr, qargs, cargs in rules: qc._append(instr, qargs, cargs) self.definition = qc def inverse(self, annotated: bool = False): r"""Return inverted U2 gate. :math:`U2(\phi, \lambda)^{\dagger} =U2(-\lambda-\pi, -\phi+\pi))` Args: annotated: when set to ``True``, this is typically used to return an :class:`.AnnotatedOperation` with an inverse modifier set instead of a concrete :class:`.Gate`. However, for this class this argument is ignored as the inverse of this gate is always a :class:`.U2Gate` with inverse parameter values. Returns: U2Gate: inverse gate. """ return U2Gate(-self.params[1] - pi, -self.params[0] + pi) def __array__(self, dtype=None, copy=None): """Return a Numpy.array for the U2 gate.""" if copy is False: raise ValueError("unable to avoid copy while creating an array as requested") isqrt2 = 1 / sqrt(2) phi, lam = self.params phi, lam = float(phi), float(lam) return numpy.array( [ [isqrt2, -exp(1j * lam) * isqrt2], [exp(1j * phi) * isqrt2, exp(1j * (phi + lam)) * isqrt2], ], dtype=dtype or complex, )
qiskit/qiskit/circuit/library/standard_gates/u2.py/0
{ "file_path": "qiskit/qiskit/circuit/library/standard_gates/u2.py", "repo_id": "qiskit", "token_count": 1910 }
185
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The 'Store' operation.""" from __future__ import annotations import typing from .exceptions import CircuitError from .classical import expr, types from .instruction import Instruction def _handle_equal_types(lvalue: expr.Expr, rvalue: expr.Expr, /) -> tuple[expr.Expr, expr.Expr]: return lvalue, rvalue def _handle_implicit_cast(lvalue: expr.Expr, rvalue: expr.Expr, /) -> tuple[expr.Expr, expr.Expr]: return lvalue, expr.Cast(rvalue, lvalue.type, implicit=True) def _requires_lossless_cast(lvalue: expr.Expr, rvalue: expr.Expr, /) -> typing.NoReturn: raise CircuitError(f"an explicit cast is required from '{rvalue.type}' to '{lvalue.type}'") def _requires_dangerous_cast(lvalue: expr.Expr, rvalue: expr.Expr, /) -> typing.NoReturn: raise CircuitError( f"an explicit cast is required from '{rvalue.type}' to '{lvalue.type}', which may be lossy" ) def _no_cast_possible(lvalue: expr.Expr, rvalue: expr.Expr) -> typing.NoReturn: raise CircuitError(f"no cast is possible from '{rvalue.type}' to '{lvalue.type}'") _HANDLE_CAST = { types.CastKind.EQUAL: _handle_equal_types, types.CastKind.IMPLICIT: _handle_implicit_cast, types.CastKind.LOSSLESS: _requires_lossless_cast, types.CastKind.DANGEROUS: _requires_dangerous_cast, types.CastKind.NONE: _no_cast_possible, } class Store(Instruction): """A manual storage of some classical value to a classical memory location. This is a low-level primitive of the classical-expression handling (similar to how :class:`~.circuit.Measure` is a primitive for quantum measurement), and is not safe for subclassing.""" # This is a compiler/backend intrinsic operation, separate to any quantum processing. _directive = True def __init__(self, lvalue: expr.Expr, rvalue: expr.Expr): """ Args: lvalue: the memory location being stored into. rvalue: the expression result being stored. """ if not expr.is_lvalue(lvalue): raise CircuitError(f"'{lvalue}' is not an l-value") cast_kind = types.cast_kind(rvalue.type, lvalue.type) if (handler := _HANDLE_CAST.get(cast_kind)) is None: raise RuntimeError(f"unhandled cast kind required: {cast_kind}") lvalue, rvalue = handler(lvalue, rvalue) super().__init__("store", 0, 0, [lvalue, rvalue]) @property def lvalue(self): """Get the l-value :class:`~.expr.Expr` node that is being stored to.""" return self.params[0] @property def rvalue(self): """Get the r-value :class:`~.expr.Expr` node that is being written into the l-value.""" return self.params[1] def c_if(self, classical, val): """:meta hidden:""" raise NotImplementedError( "stores cannot be conditioned with `c_if`; use a full `if_test` context instead" )
qiskit/qiskit/circuit/store.py/0
{ "file_path": "qiskit/qiskit/circuit/store.py", "repo_id": "qiskit", "token_count": 1247 }
186
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a dag circuit to a dag dependency""" from qiskit.dagcircuit.dagdependency_v2 import _DAGDependencyV2 def _dag_to_dagdependency_v2(dag): """Build a ``_DAGDependencyV2`` object from a ``DAGCircuit``. Args: dag (DAGCircuit): the input dag. Return: _DAGDependencyV2: the DAG representing the input circuit as a dag dependency. """ dagdependency = _DAGDependencyV2() dagdependency.name = dag.name dagdependency.metadata = dag.metadata dagdependency.global_phase = dag.global_phase dagdependency.calibrations = dag.calibrations dagdependency.add_qubits(dag.qubits) dagdependency.add_clbits(dag.clbits) for register in dag.qregs.values(): dagdependency.add_qreg(register) for register in dag.cregs.values(): dagdependency.add_creg(register) for node in dag.topological_op_nodes(): dagdependency.apply_operation_back(node.op.copy(), node.qargs, node.cargs) return dagdependency
qiskit/qiskit/converters/dag_to_dagdependency_v2.py/0
{ "file_path": "qiskit/qiskit/converters/dag_to_dagdependency_v2.py", "repo_id": "qiskit", "token_count": 525 }
187
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019, 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Built-in pass flow controllers.""" from __future__ import annotations import logging from collections.abc import Callable, Iterable, Generator from typing import Any from .base_tasks import BaseController, Task from .compilation_status import PassManagerState, PropertySet from .exceptions import PassManagerError logger = logging.getLogger(__name__) class FlowControllerLinear(BaseController): """A standard flow controller that runs tasks one after the other.""" def __init__( self, tasks: Task | Iterable[Task] = (), *, options: dict[str, Any] | None = None, ): super().__init__(options) if not isinstance(tasks, Iterable): tasks = [tasks] self.tasks: tuple[Task] = tuple(tasks) @property def passes(self) -> list[Task]: """Alias of tasks for backward compatibility.""" return list(self.tasks) def iter_tasks(self, state: PassManagerState) -> Generator[Task, PassManagerState, None]: for task in self.tasks: state = yield task class DoWhileController(BaseController): """Run the given tasks in a loop until the ``do_while`` condition on the property set becomes ``False``. The given tasks will always run at least once, and on iteration of the loop, all the tasks will be run (with the exception of a failure state being set).""" def __init__( self, tasks: Task | Iterable[Task] = (), do_while: Callable[[PropertySet], bool] = None, *, options: dict[str, Any] | None = None, ): super().__init__(options) if not isinstance(tasks, Iterable): tasks = [tasks] self.tasks: tuple[Task] = tuple(tasks) self.do_while = do_while @property def passes(self) -> list[Task]: """Alias of tasks for backward compatibility.""" return list(self.tasks) def iter_tasks(self, state: PassManagerState) -> Generator[Task, PassManagerState, None]: max_iteration = self._options.get("max_iteration", 1000) for _ in range(max_iteration): for task in self.tasks: state = yield task if not self.do_while(state.property_set): return # Remove stored tasks from the completed task collection for next loop state.workflow_status.completed_passes.difference_update(self.tasks) raise PassManagerError(f"Maximum iteration reached. max_iteration={max_iteration}") class ConditionalController(BaseController): """A flow controller runs the pipeline once if the condition is true, or does nothing if the condition is false.""" def __init__( self, tasks: Task | Iterable[Task] = (), condition: Callable[[PropertySet], bool] = None, *, options: dict[str, Any] | None = None, ): super().__init__(options) if not isinstance(tasks, Iterable): tasks = [tasks] self.tasks: tuple[Task] = tuple(tasks) self.condition = condition @property def passes(self) -> list[Task]: """Alias of tasks for backward compatibility.""" return list(self.tasks) def iter_tasks(self, state: PassManagerState) -> Generator[Task, PassManagerState, None]: if self.condition(state.property_set): for task in self.tasks: state = yield task
qiskit/qiskit/passmanager/flow_controllers.py/0
{ "file_path": "qiskit/qiskit/passmanager/flow_controllers.py", "repo_id": "qiskit", "token_count": 1457 }
188
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Statevector Sampler V2 class """ from __future__ import annotations import warnings from dataclasses import dataclass from typing import Iterable import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit from qiskit.circuit import ControlFlowOp from qiskit.quantum_info import Statevector from .base import BaseSamplerV2 from .base.validation import _has_measure from .containers import ( BitArray, DataBin, PrimitiveResult, SamplerPubResult, SamplerPubLike, ) from .containers.sampler_pub import SamplerPub from .containers.bit_array import _min_num_bytes from .primitive_job import PrimitiveJob from .utils import bound_circuit_to_instruction @dataclass class _MeasureInfo: creg_name: str num_bits: int num_bytes: int qreg_indices: list[int] class StatevectorSampler(BaseSamplerV2): """ Simple implementation of :class:`BaseSamplerV2` using full state vector simulation. This class is implemented via :class:`~.Statevector` which turns provided circuits into pure state vectors, and is therefore incompatible with mid-circuit measurements (although other implementations may be). As seen in the example below, this sampler supports providing arrays of parameter value sets to bind against a single circuit. Each tuple of ``(circuit, <optional> parameter values, <optional> shots)``, called a sampler primitive unified bloc (PUB), produces its own array-valued result. The :meth:`~run` method can be given many pubs at once. .. code-block:: python from qiskit.circuit import ( Parameter, QuantumCircuit, ClassicalRegister, QuantumRegister ) from qiskit.primitives import StatevectorSampler import matplotlib.pyplot as plt import numpy as np # Define our circuit registers, including classical registers # called 'alpha' and 'beta'. qreg = QuantumRegister(3) alpha = ClassicalRegister(2, "alpha") beta = ClassicalRegister(1, "beta") # Define a quantum circuit with two parameters. circuit = QuantumCircuit(qreg, alpha, beta) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 2) circuit.ry(Parameter("a"), 0) circuit.rz(Parameter("b"), 0) circuit.cx(1, 2) circuit.cx(0, 1) circuit.h(0) circuit.measure([0, 1], alpha) circuit.measure([2], beta) # Define a sweep over parameter values, where the second axis is over. # the two parameters in the circuit. params = np.vstack([ np.linspace(-np.pi, np.pi, 100), np.linspace(-4 * np.pi, 4 * np.pi, 100) ]).T # Instantiate a new statevector simulation based sampler object. sampler = StatevectorSampler() # Start a job that will return shots for all 100 parameter value sets. pub = (circuit, params) job = sampler.run([pub], shots=256) # Extract the result for the 0th pub (this example only has one pub). result = job.result()[0] # There is one BitArray object for each ClassicalRegister in the # circuit. Here, we can see that the BitArray for alpha contains data # for all 100 sweep points, and that it is indeed storing data for 2 # bits over 256 shots. assert result.data.alpha.shape == (100,) assert result.data.alpha.num_bits == 2 assert result.data.alpha.num_shots == 256 # We can work directly with a binary array in performant applications. raw = result.data.alpha.array # For small registers where it is anticipated to have many counts # associated with the same bitstrings, we can turn the data from, # for example, the 22nd sweep index into a dictionary of counts. counts = result.data.alpha.get_counts(22) # Or, convert into a list of bitstrings that preserve shot order. bitstrings = result.data.alpha.get_bitstrings(22) print(bitstrings) """ def __init__(self, *, default_shots: int = 1024, seed: np.random.Generator | int | None = None): """ Args: default_shots: The default shots for the sampler if not specified during run. seed: The seed or Generator object for random number generation. If None, a random seeded default RNG will be used. """ self._default_shots = default_shots self._seed = seed @property def default_shots(self) -> int: """Return the default shots""" return self._default_shots @property def seed(self) -> np.random.Generator | int | None: """Return the seed or Generator object for random number generation.""" return self._seed def run( self, pubs: Iterable[SamplerPubLike], *, shots: int | None = None ) -> PrimitiveJob[PrimitiveResult[SamplerPubResult]]: if shots is None: shots = self._default_shots coerced_pubs = [SamplerPub.coerce(pub, shots) for pub in pubs] if any(len(pub.circuit.cregs) == 0 for pub in coerced_pubs): warnings.warn( "One of your circuits has no output classical registers and so the result " "will be empty. Did you mean to add measurement instructions?", UserWarning, ) job = PrimitiveJob(self._run, coerced_pubs) job._submit() return job def _run(self, pubs: Iterable[SamplerPub]) -> PrimitiveResult[SamplerPubResult]: results = [self._run_pub(pub) for pub in pubs] return PrimitiveResult(results, metadata={"version": 2}) def _run_pub(self, pub: SamplerPub) -> SamplerPubResult: circuit, qargs, meas_info = _preprocess_circuit(pub.circuit) bound_circuits = pub.parameter_values.bind_all(circuit) arrays = { item.creg_name: np.zeros( bound_circuits.shape + (pub.shots, item.num_bytes), dtype=np.uint8 ) for item in meas_info } for index, bound_circuit in np.ndenumerate(bound_circuits): final_state = Statevector(bound_circuit_to_instruction(bound_circuit)) final_state.seed(self._seed) if qargs: samples = final_state.sample_memory(shots=pub.shots, qargs=qargs) else: samples = [""] * pub.shots samples_array = np.array([np.fromiter(sample, dtype=np.uint8) for sample in samples]) for item in meas_info: ary = _samples_to_packed_array(samples_array, item.num_bits, item.qreg_indices) arrays[item.creg_name][index] = ary meas = { item.creg_name: BitArray(arrays[item.creg_name], item.num_bits) for item in meas_info } return SamplerPubResult( DataBin(**meas, shape=pub.shape), metadata={"shots": pub.shots, "circuit_metadata": pub.circuit.metadata}, ) def _preprocess_circuit(circuit: QuantumCircuit): num_bits_dict = {creg.name: creg.size for creg in circuit.cregs} mapping = _final_measurement_mapping(circuit) qargs = sorted(set(mapping.values())) qargs_index = {v: k for k, v in enumerate(qargs)} circuit = circuit.remove_final_measurements(inplace=False) if _has_control_flow(circuit): raise QiskitError("StatevectorSampler cannot handle ControlFlowOp and c_if") if _has_measure(circuit): raise QiskitError("StatevectorSampler cannot handle mid-circuit measurements") # num_qubits is used as sentinel to fill 0 in _samples_to_packed_array sentinel = len(qargs) indices = {key: [sentinel] * val for key, val in num_bits_dict.items()} for key, qreg in mapping.items(): creg, ind = key indices[creg.name][ind] = qargs_index[qreg] meas_info = [ _MeasureInfo( creg_name=name, num_bits=num_bits, num_bytes=_min_num_bytes(num_bits), qreg_indices=indices[name], ) for name, num_bits in num_bits_dict.items() ] return circuit, qargs, meas_info def _samples_to_packed_array( samples: NDArray[np.uint8], num_bits: int, indices: list[int] ) -> NDArray[np.uint8]: # samples of `Statevector.sample_memory` will be in the order of # qubit_last, ..., qubit_1, qubit_0. # reverse the sample order into qubit_0, qubit_1, ..., qubit_last and # pad 0 in the rightmost to be used for the sentinel introduced by _preprocess_circuit. ary = np.pad(samples[:, ::-1], ((0, 0), (0, 1)), constant_values=0) # place samples in the order of clbit_last, ..., clbit_1, clbit_0 ary = ary[:, indices[::-1]] # pad 0 in the left to align the number to be mod 8 # since np.packbits(bitorder='big') pads 0 to the right. pad_size = -num_bits % 8 ary = np.pad(ary, ((0, 0), (pad_size, 0)), constant_values=0) # pack bits in big endian order ary = np.packbits(ary, axis=-1) return ary def _final_measurement_mapping(circuit: QuantumCircuit) -> dict[tuple[ClassicalRegister, int], int]: """Return the final measurement mapping for the circuit. Parameters: circuit: Input quantum circuit. Returns: Mapping of classical bits to qubits for final measurements. """ active_qubits = set(range(circuit.num_qubits)) active_cbits = set(range(circuit.num_clbits)) # Find final measurements starting in back mapping = {} for item in circuit[::-1]: if item.operation.name == "measure": loc = circuit.find_bit(item.clbits[0]) cbit = loc.index qbit = circuit.find_bit(item.qubits[0]).index if cbit in active_cbits and qbit in active_qubits: for creg in loc.registers: mapping[creg] = qbit active_cbits.remove(cbit) elif item.operation.name not in ["barrier", "delay"]: for qq in item.qubits: _temp_qubit = circuit.find_bit(qq).index if _temp_qubit in active_qubits: active_qubits.remove(_temp_qubit) if not active_cbits or not active_qubits: break return mapping def _has_control_flow(circuit: QuantumCircuit) -> bool: return any( isinstance((op := instruction.operation), ControlFlowOp) or op.condition for instruction in circuit )
qiskit/qiskit/primitives/statevector_sampler.py/0
{ "file_path": "qiskit/qiskit/primitives/statevector_sampler.py", "repo_id": "qiskit", "token_count": 4393 }
189
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """This module defines an enumerated type for the state of backend jobs""" import enum class JobStatus(enum.Enum): """Class for job status enumerated type.""" INITIALIZING = "job is being initialized" QUEUED = "job is queued" VALIDATING = "job is being validated" RUNNING = "job is actively running" CANCELLED = "job has been cancelled" DONE = "job has successfully run" ERROR = "job incurred error" JOB_FINAL_STATES = (JobStatus.DONE, JobStatus.CANCELLED, JobStatus.ERROR)
qiskit/qiskit/providers/jobstatus.py/0
{ "file_path": "qiskit/qiskit/providers/jobstatus.py", "repo_id": "qiskit", "token_count": 302 }
190
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of functions that filter instructions in a pulse program.""" from __future__ import annotations import abc from functools import singledispatch from collections.abc import Iterable from typing import Callable, Any, List import numpy as np from qiskit.pulse import Schedule, ScheduleBlock, Instruction from qiskit.pulse.channels import Channel from qiskit.pulse.schedule import Interval from qiskit.pulse.exceptions import PulseError @singledispatch def filter_instructions( sched, filters: List[Callable[..., bool]], negate: bool = False, recurse_subroutines: bool = True, ): """A catch-TypeError function which will only get called if none of the other decorated functions, namely handle_schedule() and handle_scheduleblock(), handle the type passed. """ raise TypeError( f"Type '{type(sched)}' is not valid data format as an input to filter_instructions." ) @filter_instructions.register def handle_schedule( sched: Schedule, filters: List[Callable[..., bool]], negate: bool = False, recurse_subroutines: bool = True, ) -> Schedule: """A filtering function that takes a schedule and returns a schedule consisting of filtered instructions. Args: sched: A pulse schedule to be filtered. filters: List of callback functions that take an instruction and return boolean. negate: Set `True` to accept an instruction if a filter function returns `False`. Otherwise the instruction is accepted when the filter function returns `False`. recurse_subroutines: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: Filtered pulse schedule. """ from qiskit.pulse.transforms import flatten, inline_subroutines target_sched = flatten(sched) if recurse_subroutines: target_sched = inline_subroutines(target_sched) time_inst_tuples = np.array(target_sched.instructions) valid_insts = np.ones(len(time_inst_tuples), dtype=bool) for filt in filters: valid_insts = np.logical_and(valid_insts, np.array(list(map(filt, time_inst_tuples)))) if negate and len(filters) > 0: valid_insts = ~valid_insts filter_schedule = Schedule.initialize_from(sched) for time, inst in time_inst_tuples[valid_insts]: filter_schedule.insert(time, inst, inplace=True) return filter_schedule @filter_instructions.register def handle_scheduleblock( sched_blk: ScheduleBlock, filters: List[Callable[..., bool]], negate: bool = False, recurse_subroutines: bool = True, ) -> ScheduleBlock: """A filtering function that takes a schedule_block and returns a schedule_block consisting of filtered instructions. Args: sched_blk: A pulse schedule_block to be filtered. filters: List of callback functions that take an instruction and return boolean. negate: Set `True` to accept an instruction if a filter function returns `False`. Otherwise the instruction is accepted when the filter function returns `False`. recurse_subroutines: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: Filtered pulse schedule_block. """ from qiskit.pulse.transforms import inline_subroutines target_sched_blk = sched_blk if recurse_subroutines: target_sched_blk = inline_subroutines(target_sched_blk) def apply_filters_to_insts_in_scheblk(blk: ScheduleBlock) -> ScheduleBlock: blk_new = ScheduleBlock.initialize_from(blk) for element in blk.blocks: if isinstance(element, ScheduleBlock): inner_blk = apply_filters_to_insts_in_scheblk(element) if len(inner_blk) > 0: blk_new.append(inner_blk) elif isinstance(element, Instruction): valid_inst = all(filt(element) for filt in filters) if negate: valid_inst ^= True if valid_inst: blk_new.append(element) else: raise PulseError( f"An unexpected element '{element}' is included in ScheduleBlock.blocks." ) return blk_new filter_sched_blk = apply_filters_to_insts_in_scheblk(target_sched_blk) return filter_sched_blk def composite_filter( channels: Iterable[Channel] | Channel | None = None, instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta | None = None, time_ranges: Iterable[tuple[int, int]] | None = None, intervals: Iterable[Interval] | None = None, ) -> list[Callable]: """A helper function to generate a list of filter functions based on typical elements to be filtered. Args: channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types (Optional[Iterable[Type[qiskit.pulse.Instruction]]]): For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. Returns: List of filtering functions. """ filters = [] # An empty list is also valid input for filter generators. # See unittest `test.python.pulse.test_schedule.TestScheduleFilter.test_empty_filters`. if channels is not None: filters.append(with_channels(channels)) if instruction_types is not None: filters.append(with_instruction_types(instruction_types)) if time_ranges is not None: filters.append(with_intervals(time_ranges)) if intervals is not None: filters.append(with_intervals(intervals)) return filters def with_channels(channels: Iterable[Channel] | Channel) -> Callable: """Channel filter generator. Args: channels: List of channels to filter. Returns: A callback function to filter channels. """ channels = _if_scalar_cast_to_list(channels) @singledispatch def channel_filter(time_inst): """A catch-TypeError function which will only get called if none of the other decorated functions, namely handle_numpyndarray() and handle_instruction(), handle the type passed. """ raise TypeError( f"Type '{type(time_inst)}' is not valid data format as an input to channel_filter." ) @channel_filter.register def handle_numpyndarray(time_inst: np.ndarray) -> bool: """Filter channel. Args: time_inst (numpy.ndarray([int, Instruction])): Time Returns: If instruction matches with condition. """ return any(chan in channels for chan in time_inst[1].channels) @channel_filter.register def handle_instruction(inst: Instruction) -> bool: """Filter channel. Args: inst: Instruction Returns: If instruction matches with condition. """ return any(chan in channels for chan in inst.channels) return channel_filter def with_instruction_types(types: Iterable[abc.ABCMeta] | abc.ABCMeta) -> Callable: """Instruction type filter generator. Args: types: List of instruction types to filter. Returns: A callback function to filter instructions. """ types = _if_scalar_cast_to_list(types) @singledispatch def instruction_filter(time_inst) -> bool: """A catch-TypeError function which will only get called if none of the other decorated functions, namely handle_numpyndarray() and handle_instruction(), handle the type passed. """ raise TypeError( f"Type '{type(time_inst)}' is not valid data format as an input to instruction_filter." ) @instruction_filter.register def handle_numpyndarray(time_inst: np.ndarray) -> bool: """Filter instruction. Args: time_inst (numpy.ndarray([int, Instruction])): Time Returns: If instruction matches with condition. """ return isinstance(time_inst[1], tuple(types)) @instruction_filter.register def handle_instruction(inst: Instruction) -> bool: """Filter instruction. Args: inst: Instruction Returns: If instruction matches with condition. """ return isinstance(inst, tuple(types)) return instruction_filter def with_intervals(ranges: Iterable[Interval] | Interval) -> Callable: """Interval filter generator. Args: ranges: List of intervals ``[t0, t1]`` to filter. Returns: A callback function to filter intervals. """ ranges = _if_scalar_cast_to_list(ranges) def interval_filter(time_inst) -> bool: """Filter interval. Args: time_inst (Tuple[int, Instruction]): Time Returns: If instruction matches with condition. """ for t0, t1 in ranges: inst_start = time_inst[0] inst_stop = inst_start + time_inst[1].duration if t0 <= inst_start and inst_stop <= t1: return True return False return interval_filter def _if_scalar_cast_to_list(to_list: Any) -> list[Any]: """A helper function to create python list of input arguments. Args: to_list: Arbitrary object can be converted into a python list. Returns: Python list of input object. """ try: iter(to_list) except TypeError: to_list = [to_list] return to_list
qiskit/qiskit/pulse/filters.py/0
{ "file_path": "qiskit/qiskit/pulse/filters.py", "repo_id": "qiskit", "token_count": 3910 }
191
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Sampler decorator module for sampling of continuous pulses to discrete pulses to be exposed to user. Some atypical boilerplate has been added to solve the problem of decorators not preserving their wrapped function signatures. Below we explain the problem that samplers solve and how we implement this. A sampler is a function that takes an continuous pulse function with signature: ```python def f(times: np.ndarray, *args, **kwargs) -> np.ndarray: ... ``` and returns a new function: def f(duration: int, *args, **kwargs) -> Waveform: ... Samplers are used to build up pulse waveforms from continuous pulse functions. In Python the creation of a dynamic function that wraps another function will cause the underlying signature and documentation of the underlying function to be overwritten. In order to circumvent this issue the Python standard library provides the decorator `functools.wraps` which allows the programmer to expose the names and signature of the wrapped function as those of the dynamic function. Samplers are implemented by creating a function with signature @sampler def left(continuous_pulse: Callable, duration: int, *args, **kwargs) ... This will create a sampler function for `left`. Since it is a dynamic function it would not have the docstring of `left` available too `help`. This could be fixed by wrapping with `functools.wraps` in the `sampler`, but this would then cause the signature to be that of the sampler function which is called on the continuous pulse, below: `(continuous_pulse: Callable, duration: int, *args, **kwargs)`` This is not correct for the sampler as the output sampled functions accept only a function. For the standard sampler we get around this by not using `functools.wraps` and explicitly defining our samplers such as `left`, `right` and `midpoint` and calling `sampler` internally on the function that implements the sampling schemes such as `left_sample`, `right_sample` and `midpoint_sample` respectively. See `left` for an example of this. In this way our standard samplers will expose the proper help signature, but a user can still create their own sampler with @sampler def custom_sampler(time, *args, **kwargs): ... However, in this case it will be missing documentation of the underlying sampling methods. We believe that the definition of custom samplers will be rather infrequent. However, users will frequently apply sampler instances too continuous pulses. Therefore, a different approach was required for sampled continuous functions (the output of an continuous pulse function decorated by a sampler instance). A sampler instance is a decorator that may be used to wrap continuous pulse functions such as linear below: ```python @left def linear(times: np.ndarray, m: float, b: float) -> np.ndarray: ```Linear test function Args: times: Input times. m: Slope. b: Intercept Returns: np.ndarray ``` return m*times+b ``` Which after decoration may be called with a duration rather than an array of times ```python duration = 10 pulse_envelope = linear(10, 0.1, 0.1) ``` If one calls help on `linear` they will find ``` linear(duration:int, *args, **kwargs) -> numpy.ndarray Discretized continuous pulse function: `linear` using sampler: `_left`. The first argument (time) of the continuous pulse function has been replaced with a discretized `duration` of type (int). Args: duration (int) *args: Remaining arguments of continuous pulse function. See continuous pulse function documentation below. **kwargs: Remaining kwargs of continuous pulse function. See continuous pulse function documentation below. Sampled continuous function: function linear in module test.python.pulse.test_samplers linear(x:numpy.ndarray, m:float, b:float) -> numpy.ndarray Linear test function Args: x: Input times. m: Slope. b: Intercept Returns: np.ndarray ``` This is partly because `functools.wraps` has been used on the underlying function. This in itself is not sufficient as the signature of the sampled function has `duration`, whereas the signature of the continuous function is `time`. This is achieved by removing `__wrapped__` set by `functools.wraps` in order to preserve the correct signature and also applying `_update_annotations` and `_update_docstring` to the generated function which corrects the function annotations and adds an informative docstring respectively. The user therefore has access to the correct sampled function docstring in its entirety, while still seeing the signature for the continuous pulse function and all of its arguments. """ from __future__ import annotations import functools import textwrap import pydoc from collections.abc import Callable import numpy as np from ...exceptions import PulseError from ..waveform import Waveform from . import strategies def functional_pulse(func: Callable) -> Callable: """A decorator for generating Waveform from python callable. Args: func: A function describing pulse envelope. Raises: PulseError: when invalid function is specified. """ @functools.wraps(func) def to_pulse(duration, *args, name=None, **kwargs): """Return Waveform.""" if isinstance(duration, (int, np.integer)) and duration > 0: samples = func(duration, *args, **kwargs) samples = np.asarray(samples, dtype=np.complex128) return Waveform(samples=samples, name=name) raise PulseError("The first argument must be an integer value representing duration.") return to_pulse def _update_annotations(discretized_pulse: Callable) -> Callable: """Update annotations of discretized continuous pulse function with duration. Args: discretized_pulse: Discretized decorated continuous pulse. """ undecorated_annotations = list(discretized_pulse.__annotations__.items()) decorated_annotations = undecorated_annotations[1:] decorated_annotations.insert(0, ("duration", int)) discretized_pulse.__annotations__ = dict(decorated_annotations) return discretized_pulse def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Callable: """Update annotations of discretized continuous pulse function. Args: discretized_pulse: Discretized decorated continuous pulse. sampler_inst: Applied sampler. """ wrapped_docstring = pydoc.render_doc(discretized_pulse, "%s") header, body = wrapped_docstring.split("\n", 1) body = textwrap.indent(body, " ") wrapped_docstring = header + body updated_ds = f""" Discretized continuous pulse function: `{discretized_pulse.__name__}` using sampler: `{sampler_inst.__name__}`. The first argument (time) of the continuous pulse function has been replaced with a discretized `duration` of type (int). Args: duration (int) *args: Remaining arguments of continuous pulse function. See continuous pulse function documentation below. **kwargs: Remaining kwargs of continuous pulse function. See continuous pulse function documentation below. Sampled continuous function: {wrapped_docstring} """ discretized_pulse.__doc__ = updated_ds return discretized_pulse def sampler(sample_function: Callable) -> Callable: """Sampler decorator base method. Samplers are used for converting an continuous function to a discretized pulse. They operate on a function with the signature: `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray` Where `times` is a numpy array of floats with length n_times and the output array is a complex numpy array with length n_times. The output of the decorator is an instance of `FunctionalPulse` with signature: `def g(duration: int, *args, **kwargs) -> Waveform` Note if your continuous pulse function outputs a `complex` scalar rather than a `np.ndarray`, you should first vectorize it before applying a sampler. This class implements the sampler boilerplate for the sampler. Args: sample_function: A sampler function to be decorated. """ def generate_sampler(continuous_pulse: Callable) -> Callable: """Return a decorated sampler function.""" @functools.wraps(continuous_pulse) def call_sampler(duration: int, *args, **kwargs) -> np.ndarray: """Replace the call to the continuous function with a call to the sampler applied to the analytic pulse function.""" sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs) return np.asarray(sampled_pulse, dtype=np.complex128) # Update type annotations for wrapped continuous function to be discrete call_sampler = _update_annotations(call_sampler) # Update docstring with that of the sampler and include sampled function documentation. call_sampler = _update_docstring(call_sampler, sample_function) # Unset wrapped to return base sampler signature # but still get rest of benefits of wraps # such as __name__, __qualname__ call_sampler.__dict__.pop("__wrapped__") # wrap with functional pulse return functional_pulse(call_sampler) return generate_sampler def left(continuous_pulse: Callable) -> Callable: r"""Left sampling strategy decorator. See `pulse.samplers.sampler` for more information. For `duration`, return: $$\{f(t) \in \mathbb{C} | t \in \mathbb{Z} \wedge 0<=t<\texttt{duration}\}$$ Args: continuous_pulse: To sample. """ return sampler(strategies.left_sample)(continuous_pulse) def right(continuous_pulse: Callable) -> Callable: r"""Right sampling strategy decorator. See `pulse.samplers.sampler` for more information. For `duration`, return: $$\{f(t) \in \mathbb{C} | t \in \mathbb{Z} \wedge 0<t<=\texttt{duration}\}$$ Args: continuous_pulse: To sample. """ return sampler(strategies.right_sample)(continuous_pulse) def midpoint(continuous_pulse: Callable) -> Callable: r"""Midpoint sampling strategy decorator. See `pulse.samplers.sampler` for more information. For `duration`, return: $$\{f(t+0.5) \in \mathbb{C} | t \in \mathbb{Z} \wedge 0<=t<\texttt{duration}\}$$ Args: continuous_pulse: To sample. """ return sampler(strategies.midpoint_sample)(continuous_pulse)
qiskit/qiskit/pulse/library/samplers/decorators.py/0
{ "file_path": "qiskit/qiskit/pulse/library/samplers/decorators.py", "repo_id": "qiskit", "token_count": 3946 }
192
// Quantum Experience (QE) Standard Header // file: qelib1.inc // --- QE Hardware primitives --- // 3-parameter 2-pulse single qubit gate gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; } // 2-parameter 1-pulse single qubit gate gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; } // 1-parameter 0-pulse single qubit gate gate u1(lambda) q { U(0,0,lambda) q; } // controlled-NOT gate cx c,t { CX c,t; } // idle gate (identity) gate id a { U(0,0,0) a; } // idle gate (identity) with length gamma*sqglen gate u0(gamma) q { U(0,0,0) q; } // --- QE Standard Gates --- // generic single qubit gate gate u(theta,phi,lambda) q { U(theta,phi,lambda) q; } // phase gate gate p(lambda) q { U(0,0,lambda) q; } // Pauli gate: bit-flip gate x a { u3(pi,0,pi) a; } // Pauli gate: bit and phase flip gate y a { u3(pi,pi/2,pi/2) a; } // Pauli gate: phase flip gate z a { u1(pi) a; } // Clifford gate: Hadamard gate h a { u2(0,pi) a; } // Clifford gate: sqrt(Z) phase gate gate s a { u1(pi/2) a; } // Clifford gate: conjugate of sqrt(Z) gate sdg a { u1(-pi/2) a; } // C3 gate: sqrt(S) phase gate gate t a { u1(pi/4) a; } // C3 gate: conjugate of sqrt(S) gate tdg a { u1(-pi/4) a; } // --- Standard rotations --- // Rotation around X-axis gate rx(theta) a { u3(theta, -pi/2,pi/2) a; } // rotation around Y-axis gate ry(theta) a { u3(theta,0,0) a; } // rotation around Z axis gate rz(phi) a { u1(phi) a; } // --- QE Standard User-Defined Gates --- // sqrt(X) gate sx a { sdg a; h a; sdg a; } // inverse sqrt(X) gate sxdg a { s a; h a; s a; } // controlled-Phase gate cz a,b { h b; cx a,b; h b; } // controlled-Y gate cy a,b { sdg b; cx a,b; s b; } // swap gate swap a,b { cx a,b; cx b,a; cx a,b; } // controlled-H gate ch a,b { h b; sdg b; cx a,b; h b; t b; cx a,b; t b; h b; s b; x b; s a; } // C3 gate: Toffoli gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b; } // cswap (Fredkin) gate cswap a,b,c { cx c,b; ccx a,b,c; cx c,b; } // controlled rx rotation gate crx(lambda) a,b { u1(pi/2) b; cx a,b; u3(-lambda/2,0,0) b; cx a,b; u3(lambda/2,-pi/2,0) b; } // controlled ry rotation gate cry(lambda) a,b { ry(lambda/2) b; cx a,b; ry(-lambda/2) b; cx a,b; } // controlled rz rotation gate crz(lambda) a,b { rz(lambda/2) b; cx a,b; rz(-lambda/2) b; cx a,b; } // controlled phase rotation gate cu1(lambda) a,b { u1(lambda/2) a; cx a,b; u1(-lambda/2) b; cx a,b; u1(lambda/2) b; } gate cp(lambda) a,b { p(lambda/2) a; cx a,b; p(-lambda/2) b; cx a,b; p(lambda/2) b; } // controlled-U gate cu3(theta,phi,lambda) c, t { // implements controlled-U(theta,phi,lambda) with target t and control c u1((lambda+phi)/2) c; u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t; } // controlled-sqrt(X) gate csx a,b { h b; cu1(pi/2) a,b; h b; } // controlled-U gate gate cu(theta,phi,lambda,gamma) c, t { p(gamma) c; p((lambda+phi)/2) c; p((lambda-phi)/2) t; cx c,t; u(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u(theta/2,phi,0) t; } // two-qubit XX rotation gate rxx(theta) a,b { u3(pi/2, theta, 0) a; h b; cx a,b; u1(-theta) b; cx a,b; h b; u2(-pi, pi-theta) a; } // two-qubit ZZ rotation gate rzz(theta) a,b { cx a,b; u1(theta) b; cx a,b; } // relative-phase CCX gate rccx a,b,c { u2(0,pi) c; u1(pi/4) c; cx b, c; u1(-pi/4) c; cx a, c; u1(pi/4) c; cx b, c; u1(-pi/4) c; u2(0,pi) c; } // relative-phase 3-controlled X gate gate rc3x a,b,c,d { u2(0,pi) d; u1(pi/4) d; cx c,d; u1(-pi/4) d; u2(0,pi) d; cx a,d; u1(pi/4) d; cx b,d; u1(-pi/4) d; cx a,d; u1(pi/4) d; cx b,d; u1(-pi/4) d; u2(0,pi) d; u1(pi/4) d; cx c,d; u1(-pi/4) d; u2(0,pi) d; } // 3-controlled X gate gate c3x a,b,c,d { h d; p(pi/8) a; p(pi/8) b; p(pi/8) c; p(pi/8) d; cx a, b; p(-pi/8) b; cx a, b; cx b, c; p(-pi/8) c; cx a, c; p(pi/8) c; cx b, c; p(-pi/8) c; cx a, c; cx c, d; p(-pi/8) d; cx b, d; p(pi/8) d; cx c, d; p(-pi/8) d; cx a, d; p(pi/8) d; cx c, d; p(-pi/8) d; cx b, d; p(pi/8) d; cx c, d; p(-pi/8) d; cx a, d; h d; } // 3-controlled sqrt(X) gate, this equals the C3X gate where the CU1 rotations are -pi/8 not -pi/4 gate c3sqrtx a,b,c,d { h d; cu1(pi/8) a,d; h d; cx a,b; h d; cu1(-pi/8) b,d; h d; cx a,b; h d; cu1(pi/8) b,d; h d; cx b,c; h d; cu1(-pi/8) c,d; h d; cx a,c; h d; cu1(pi/8) c,d; h d; cx b,c; h d; cu1(-pi/8) c,d; h d; cx a,c; h d; cu1(pi/8) c,d; h d; } // 4-controlled X gate gate c4x a,b,c,d,e { h e; cu1(pi/2) d,e; h e; c3x a,b,c,d; h e; cu1(-pi/2) d,e; h e; c3x a,b,c,d; c3sqrtx a,b,c,e; }
qiskit/qiskit/qasm/libs/qelib1.inc/0
{ "file_path": "qiskit/qiskit/qasm/libs/qelib1.inc", "repo_id": "qiskit", "token_count": 2674 }
193
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name, missing-function-docstring """Helper class used to convert a pulse instruction into PulseQobjInstruction.""" import hashlib import re import warnings from enum import Enum from functools import singledispatchmethod from typing import Union, List, Iterator, Optional import numpy as np from qiskit.circuit import Parameter, ParameterExpression from qiskit.pulse import channels, instructions, library from qiskit.pulse.configuration import Kernel, Discriminator from qiskit.pulse.exceptions import QiskitError from qiskit.pulse.parser import parse_string_expr from qiskit.pulse.schedule import Schedule from qiskit.qobj import QobjMeasurementOption, PulseLibraryItem, PulseQobjInstruction from qiskit.qobj.utils import MeasLevel from qiskit.utils import deprecate_func class ParametricPulseShapes(Enum): """Map the assembled pulse names to the pulse module waveforms. The enum name is the transport layer name for pulse shapes, the value is its mapping to the OpenPulse Command in Qiskit. """ gaussian = "Gaussian" gaussian_square = "GaussianSquare" gaussian_square_drag = "GaussianSquareDrag" gaussian_square_echo = "gaussian_square_echo" drag = "Drag" constant = "Constant" @classmethod def from_instance( cls, instance: library.SymbolicPulse, ) -> "ParametricPulseShapes": """Get Qobj name from the pulse class instance. Args: instance: SymbolicPulse class. Returns: Qobj name. Raises: QiskitError: When pulse instance is not recognizable type. """ if isinstance(instance, library.SymbolicPulse): return cls(instance.pulse_type) raise QiskitError(f"'{instance}' is not valid pulse type.") @classmethod def to_type(cls, name: str) -> library.SymbolicPulse: """Get symbolic pulse class from the name. Args: name: Qobj name of the pulse. Returns: Corresponding class. """ return getattr(library, cls[name].value) class InstructionToQobjConverter: """Converts Qiskit Pulse in-memory representation into Qobj data. This converter converts the Qiskit Pulse in-memory representation into the transfer layer format to submit the data from client to the server. The transfer layer format must be the text representation that coforms to the `OpenPulse specification<https://arxiv.org/abs/1809.03452>`__. Extention to the OpenPulse can be achieved by subclassing this this with extra methods corresponding to each augmented instruction. For example, .. code-block:: python class MyConverter(InstructionToQobjConverter): def _convert_NewInstruction(self, instruction, time_offset): command_dict = { 'name': 'new_inst', 't0': time_offset + instruction.start_time, 'param1': instruction.param1, 'param2': instruction.param2 } return self._qobj_model(**command_dict) where ``NewInstruction`` must be a class name of Qiskit Pulse instruction. """ @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", additional_msg="The `Qobj` class and related functionality are part of the deprecated " "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " "workflow requires `Qobj` it likely relies on deprecated functionality and " "should be updated to use `BackendV2`.", ) def __init__( self, qobj_model: PulseQobjInstruction, **run_config, ): """Create new converter. Args: qobj_model: Transfer layer data schema. run_config: Run configuration. """ self._qobj_model = qobj_model self._run_config = run_config def __call__( self, shift: int, instruction: Union[instructions.Instruction, List[instructions.Acquire]], ) -> PulseQobjInstruction: """Convert Qiskit in-memory representation to Qobj instruction. Args: instruction: Instruction data in Qiskit Pulse. Returns: Qobj instruction data. Raises: QiskitError: When list of instruction is provided except for Acquire. """ if isinstance(instruction, list): if all(isinstance(inst, instructions.Acquire) for inst in instruction): return self._convert_bundled_acquire( instruction_bundle=instruction, time_offset=shift, ) raise QiskitError("Bundle of instruction is not supported except for Acquire.") return self._convert_instruction(instruction, shift) @singledispatchmethod def _convert_instruction( self, instruction, time_offset: int, ) -> PulseQobjInstruction: raise QiskitError( f"Pulse Qobj doesn't support {instruction.__class__.__name__}. " "This instruction cannot be submitted with Qobj." ) @_convert_instruction.register(instructions.Acquire) def _convert_acquire( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `Acquire`. Args: instruction: Qiskit Pulse acquire instruction. time_offset: Offset time. Returns: Qobj instruction data. """ meas_level = self._run_config.get("meas_level", 2) mem_slot = [] if instruction.mem_slot: mem_slot = [instruction.mem_slot.index] command_dict = { "name": "acquire", "t0": time_offset + instruction.start_time, "duration": instruction.duration, "qubits": [instruction.channel.index], "memory_slot": mem_slot, } if meas_level == MeasLevel.CLASSIFIED: # setup discriminators if instruction.discriminator: command_dict.update( { "discriminators": [ QobjMeasurementOption( name=instruction.discriminator.name, params=instruction.discriminator.params, ) ] } ) # setup register_slots if instruction.reg_slot: command_dict.update({"register_slot": [instruction.reg_slot.index]}) if meas_level in [MeasLevel.KERNELED, MeasLevel.CLASSIFIED]: # setup kernels if instruction.kernel: command_dict.update( { "kernels": [ QobjMeasurementOption( name=instruction.kernel.name, params=instruction.kernel.params ) ] } ) return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.SetFrequency) def _convert_set_frequency( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `SetFrequency`. Args: instruction: Qiskit Pulse set frequency instruction. time_offset: Offset time. Returns: Qobj instruction data. """ command_dict = { "name": "setf", "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "frequency": instruction.frequency / 10**9, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.ShiftFrequency) def _convert_shift_frequency( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `ShiftFrequency`. Args: instruction: Qiskit Pulse shift frequency instruction. time_offset: Offset time. Returns: Qobj instruction data. """ command_dict = { "name": "shiftf", "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "frequency": instruction.frequency / 10**9, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.SetPhase) def _convert_set_phase( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `SetPhase`. Args: instruction: Qiskit Pulse set phase instruction. time_offset: Offset time. Returns: Qobj instruction data. """ command_dict = { "name": "setp", "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "phase": instruction.phase, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.ShiftPhase) def _convert_shift_phase( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `ShiftPhase`. Args: instruction: Qiskit Pulse shift phase instruction. time_offset: Offset time. Returns: Qobj instruction data. """ command_dict = { "name": "fc", "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "phase": instruction.phase, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.Delay) def _convert_delay( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `Delay`. Args: instruction: Qiskit Pulse delay instruction. time_offset: Offset time. Returns: Qobj instruction data. """ command_dict = { "name": "delay", "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "duration": instruction.duration, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.Play) def _convert_play( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `Play`. Args: instruction: Qiskit Pulse play instruction. time_offset: Offset time. Returns: Qobj instruction data. """ if isinstance(instruction.pulse, library.SymbolicPulse): params = dict(instruction.pulse.parameters) # IBM backends expect "amp" to be the complex amplitude if "amp" in params and "angle" in params: params["amp"] = complex(params["amp"] * np.exp(1j * params["angle"])) del params["angle"] command_dict = { "name": "parametric_pulse", "pulse_shape": ParametricPulseShapes.from_instance(instruction.pulse).name, "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, "parameters": params, } else: command_dict = { "name": instruction.name, "t0": time_offset + instruction.start_time, "ch": instruction.channel.name, } return self._qobj_model(**command_dict) @_convert_instruction.register(instructions.Snapshot) def _convert_snapshot( self, instruction, time_offset: int, ) -> PulseQobjInstruction: """Return converted `Snapshot`. Args: time_offset: Offset time. instruction: Qiskit Pulse snapshot instruction. Returns: Qobj instruction data. """ command_dict = { "name": "snapshot", "t0": time_offset + instruction.start_time, "label": instruction.label, "type": instruction.type, } return self._qobj_model(**command_dict) def _convert_bundled_acquire( self, instruction_bundle: List[instructions.Acquire], time_offset: int, ) -> PulseQobjInstruction: """Return converted list of parallel `Acquire` instructions. Args: instruction_bundle: List of Qiskit Pulse acquire instruction. time_offset: Offset time. Returns: Qobj instruction data. Raises: QiskitError: When instructions are not aligned. QiskitError: When instructions have different duration. QiskitError: When discriminator or kernel is missing in a part of instructions. """ meas_level = self._run_config.get("meas_level", 2) t0 = instruction_bundle[0].start_time duration = instruction_bundle[0].duration memory_slots = [] register_slots = [] qubits = [] discriminators = [] kernels = [] for instruction in instruction_bundle: qubits.append(instruction.channel.index) if instruction.start_time != t0: raise QiskitError( "The supplied acquire instructions have different starting times. " "Something has gone wrong calling this code. Please report this " "issue." ) if instruction.duration != duration: raise QiskitError( "Acquire instructions beginning at the same time must have same duration." ) if instruction.mem_slot: memory_slots.append(instruction.mem_slot.index) if meas_level == MeasLevel.CLASSIFIED: # setup discriminators if instruction.discriminator: discriminators.append( QobjMeasurementOption( name=instruction.discriminator.name, params=instruction.discriminator.params, ) ) # setup register_slots if instruction.reg_slot: register_slots.append(instruction.reg_slot.index) if meas_level in [MeasLevel.KERNELED, MeasLevel.CLASSIFIED]: # setup kernels if instruction.kernel: kernels.append( QobjMeasurementOption( name=instruction.kernel.name, params=instruction.kernel.params ) ) command_dict = { "name": "acquire", "t0": time_offset + t0, "duration": duration, "qubits": qubits, } if memory_slots: command_dict["memory_slot"] = memory_slots if register_slots: command_dict["register_slot"] = register_slots if discriminators: num_discriminators = len(discriminators) if num_discriminators == len(qubits) or num_discriminators == 1: command_dict["discriminators"] = discriminators else: raise QiskitError( "A discriminator must be supplied for every acquisition or a single " "discriminator for all acquisitions." ) if kernels: num_kernels = len(kernels) if num_kernels == len(qubits) or num_kernels == 1: command_dict["kernels"] = kernels else: raise QiskitError( "A kernel must be supplied for every acquisition or a single " "kernel for all acquisitions." ) return self._qobj_model(**command_dict) class QobjToInstructionConverter: """Converts Qobj data into Qiskit Pulse in-memory representation. This converter converts data from transfer layer into the in-memory representation of the front-end of Qiskit Pulse. The transfer layer format must be the text representation that coforms to the `OpenPulse specification<https://arxiv.org/abs/1809.03452>`__. Extention to the OpenPulse can be achieved by subclassing this this with extra methods corresponding to each augmented instruction. For example, .. code-block:: python class MyConverter(QobjToInstructionConverter): def get_supported_instructions(self): instructions = super().get_supported_instructions() instructions += ["new_inst"] return instructions def _convert_new_inst(self, instruction): return NewInstruction(...) where ``NewInstruction`` must be a subclass of :class:`~qiskit.pulse.instructions.Instruction`. """ __chan_regex__ = re.compile(r"([a-zA-Z]+)(\d+)") def __init__( self, pulse_library: Optional[List[PulseLibraryItem]] = None, **run_config, ): """Create new converter. Args: pulse_library: Pulse library in Qobj format. run_config: Run configuration. """ pulse_library_dict = {} for lib_item in pulse_library: pulse_library_dict[lib_item.name] = lib_item.samples self._pulse_library = pulse_library_dict self._run_config = run_config def __call__(self, instruction: PulseQobjInstruction) -> Schedule: """Convert Qobj instruction to Qiskit in-memory representation. Args: instruction: Instruction data in Qobj format. Returns: Scheduled Qiskit Pulse instruction in Schedule format. """ schedule = Schedule() for inst in self._get_sequences(instruction): schedule.insert(instruction.t0, inst, inplace=True) return schedule def _get_sequences( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """A method to iterate over pulse instructions without creating Schedule. .. note:: This is internal fast-path function, and callers other than this converter class might directly use this method to generate schedule from multiple Qobj instructions. Because __call__ always returns a schedule with the time offset parsed instruction, composing multiple Qobj instructions to create a gate schedule is somewhat inefficient due to composing overhead of schedules. Directly combining instructions with this method is much performant. Args: instruction: Instruction data in Qobj format. Yields: Qiskit Pulse instructions. :meta public: """ try: method = getattr(self, f"_convert_{instruction.name}") except AttributeError: method = self._convert_generic yield from method(instruction) def get_supported_instructions(self) -> List[str]: """Retrun a list of supported instructions.""" return [ "acquire", "setp", "fc", "setf", "shiftf", "delay", "parametric_pulse", "snapshot", ] def get_channel(self, channel: str) -> channels.PulseChannel: """Parse and retrieve channel from ch string. Args: channel: String identifier of pulse instruction channel. Returns: Matched channel object. Raises: QiskitError: Is raised if valid channel is not matched """ match = self.__chan_regex__.match(channel) if match: prefix, index = match.group(1), int(match.group(2)) if prefix == channels.DriveChannel.prefix: return channels.DriveChannel(index) elif prefix == channels.MeasureChannel.prefix: return channels.MeasureChannel(index) elif prefix == channels.ControlChannel.prefix: return channels.ControlChannel(index) raise QiskitError(f"Channel {channel} is not valid") @staticmethod def disassemble_value(value_expr: Union[float, str]) -> Union[float, ParameterExpression]: """A helper function to format instruction operand. If parameter in string representation is specified, this method parses the input string and generates Qiskit ParameterExpression object. Args: value_expr: Operand value in Qobj. Returns: Parsed operand value. ParameterExpression object is returned if value is not number. """ if isinstance(value_expr, str): str_expr = parse_string_expr(value_expr, partial_binding=False) value_expr = str_expr(**{pname: Parameter(pname) for pname in str_expr.params}) return value_expr def _convert_acquire( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `Acquire` instruction. Args: instruction: Acquire qobj Yields: Qiskit Pulse acquire instructions """ duration = instruction.duration qubits = instruction.qubits acquire_channels = [channels.AcquireChannel(qubit) for qubit in qubits] mem_slots = [channels.MemorySlot(instruction.memory_slot[i]) for i in range(len(qubits))] if hasattr(instruction, "register_slot"): register_slots = [ channels.RegisterSlot(instruction.register_slot[i]) for i in range(len(qubits)) ] else: register_slots = [None] * len(qubits) discriminators = ( instruction.discriminators if hasattr(instruction, "discriminators") else None ) if not isinstance(discriminators, list): discriminators = [discriminators] if any(discriminators[i] != discriminators[0] for i in range(len(discriminators))): warnings.warn( "Can currently only support one discriminator per acquire. Defaulting " "to first discriminator entry." ) discriminator = discriminators[0] if discriminator: discriminator = Discriminator(name=discriminators[0].name, **discriminators[0].params) kernels = instruction.kernels if hasattr(instruction, "kernels") else None if not isinstance(kernels, list): kernels = [kernels] if any(kernels[0] != kernels[i] for i in range(len(kernels))): warnings.warn( "Can currently only support one kernel per acquire. Defaulting to first " "kernel entry." ) kernel = kernels[0] if kernel: kernel = Kernel(name=kernels[0].name, **kernels[0].params) for acquire_channel, mem_slot, reg_slot in zip(acquire_channels, mem_slots, register_slots): yield instructions.Acquire( duration, acquire_channel, mem_slot=mem_slot, reg_slot=reg_slot, kernel=kernel, discriminator=discriminator, ) def _convert_setp( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `SetPhase` instruction. Args: instruction: SetPhase qobj instruction Yields: Qiskit Pulse set phase instructions """ channel = self.get_channel(instruction.ch) phase = self.disassemble_value(instruction.phase) yield instructions.SetPhase(phase, channel) def _convert_fc( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `ShiftPhase` instruction. Args: instruction: ShiftPhase qobj instruction Yields: Qiskit Pulse shift phase schedule instructions """ channel = self.get_channel(instruction.ch) phase = self.disassemble_value(instruction.phase) yield instructions.ShiftPhase(phase, channel) def _convert_setf( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `SetFrequencyInstruction` instruction. .. note:: We assume frequency value is expressed in string with "GHz". Operand value is thus scaled by a factor of 10^9. Args: instruction: SetFrequency qobj instruction Yields: Qiskit Pulse set frequency instructions """ channel = self.get_channel(instruction.ch) frequency = self.disassemble_value(instruction.frequency) * 10**9 yield instructions.SetFrequency(frequency, channel) def _convert_shiftf( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `ShiftFrequency` instruction. .. note:: We assume frequency value is expressed in string with "GHz". Operand value is thus scaled by a factor of 10^9. Args: instruction: ShiftFrequency qobj instruction Yields: Qiskit Pulse shift frequency schedule instructions """ channel = self.get_channel(instruction.ch) frequency = self.disassemble_value(instruction.frequency) * 10**9 yield instructions.ShiftFrequency(frequency, channel) def _convert_delay( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `Delay` instruction. Args: instruction: Delay qobj instruction Yields: Qiskit Pulse delay instructions """ channel = self.get_channel(instruction.ch) duration = instruction.duration yield instructions.Delay(duration, channel) def _convert_parametric_pulse( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `Play` instruction with parametric pulse operand. .. note:: If parametric pulse label is not provided by the backend, this method naively generates a pulse name based on the pulse shape and bound parameters. This pulse name is formatted to, for example, `gaussian_a4e3`, here the last four digits are a part of the hash string generated based on the pulse shape and the parameters. Because we are using a truncated hash for readability, there may be a small risk of pulse name collision with other pulses. Basically the parametric pulse name is used just for visualization purpose and the pulse module should not have dependency on the parametric pulse names. Args: instruction: Play qobj instruction with parametric pulse Yields: Qiskit Pulse play schedule instructions """ channel = self.get_channel(instruction.ch) try: pulse_name = instruction.label except AttributeError: sorted_params = sorted(instruction.parameters.items(), key=lambda x: x[0]) base_str = f"{instruction.pulse_shape}_{str(sorted_params)}" short_pulse_id = hashlib.md5(base_str.encode("utf-8")).hexdigest()[:4] pulse_name = f"{instruction.pulse_shape}_{short_pulse_id}" params = dict(instruction.parameters) if "amp" in params and isinstance(params["amp"], complex): params["angle"] = np.angle(params["amp"]) params["amp"] = np.abs(params["amp"]) pulse = ParametricPulseShapes.to_type(instruction.pulse_shape)(**params, name=pulse_name) yield instructions.Play(pulse, channel) def _convert_snapshot( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Return converted `Snapshot` instruction. Args: instruction: Snapshot qobj instruction Yields: Qiskit Pulse snapshot instructions """ yield instructions.Snapshot(instruction.label, instruction.type) def _convert_generic( self, instruction: PulseQobjInstruction, ) -> Iterator[instructions.Instruction]: """Convert generic pulse instruction. Args: instruction: Generic qobj instruction Yields: Qiskit Pulse generic instructions Raises: QiskitError: When instruction name not found. """ if instruction.name in self._pulse_library: waveform = library.Waveform( samples=self._pulse_library[instruction.name], name=instruction.name, ) channel = self.get_channel(instruction.ch) yield instructions.Play(waveform, channel) else: if qubits := getattr(instruction, "qubits", None): msg = f"qubits {qubits}" else: msg = f"channel {instruction.ch}" raise QiskitError( f"Instruction {instruction.name} on {msg} is not found " "in Qiskit namespace. This instruction cannot be deserialized." )
qiskit/qiskit/qobj/converters/pulse_instruction.py/0
{ "file_path": "qiskit/qiskit/qobj/converters/pulse_instruction.py", "repo_id": "qiskit", "token_count": 13460 }
194
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of useful functions for post processing results.""" from __future__ import annotations import numpy as np from .make_observable import make_dict_observable def average_data(counts: dict, observable: dict | np.ndarray | list) -> float: """Compute the mean value of an diagonal observable. Takes in a diagonal observable in dictionary, list or matrix format and then calculates the sum_i value(i) P(i) where value(i) is the value of the observable for state i. Args: counts (dict): a dict of outcomes from an experiment observable (dict or matrix or list): The observable to be averaged over. As an example, ZZ on qubits can be given as: * dict: {"00": 1, "11": 1, "01": -1, "10": -1} * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]] * matrix diagonal (list): [1, -1, -1, 1] Returns: Double: Average of the observable """ if not isinstance(observable, dict): observable = make_dict_observable(observable) temp = 0 tot = sum(counts.values()) for key in counts: if key in observable: temp += counts[key] * observable[key] / tot return temp
qiskit/qiskit/quantum_info/analysis/average.py/0
{ "file_path": "qiskit/qiskit/quantum_info/analysis/average.py", "repo_id": "qiskit", "token_count": 585 }
195
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Predicates for operators. """ from __future__ import annotations import numpy as np ATOL_DEFAULT = 1e-8 RTOL_DEFAULT = 1e-5 def matrix_equal(mat1, mat2, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT, props=None): # pylint: disable-next=consider-using-f-string """Test if two arrays are equal. The final comparison is implemented using Numpy.allclose. See its documentation for additional information on tolerance parameters. If ignore_phase is True both matrices will be multiplied by exp(-1j * theta) where `theta` is the first nphase for a first non-zero matrix element `|a| * exp(1j * theta)`. Args: mat1 (matrix_like): a matrix mat2 (matrix_like): a matrix ignore_phase (bool): ignore complex-phase differences between matrices [Default: False] rtol (double): the relative tolerance parameter [Default {}]. atol (double): the absolute tolerance parameter [Default {}]. props (dict | None): if not ``None`` and ``ignore_phase`` is ``True`` returns the phase difference between the two matrices under ``props['phase_difference']`` Returns: bool: True if the matrices are equal or False otherwise. """.format( RTOL_DEFAULT, ATOL_DEFAULT ) if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT if not isinstance(mat1, np.ndarray): mat1 = np.array(mat1) if not isinstance(mat2, np.ndarray): mat2 = np.array(mat2) if mat1.shape != mat2.shape: return False if ignore_phase: phase_difference = 0 # Get phase of first non-zero entry of mat1 and mat2 # and multiply all entries by the conjugate for elt in mat1.flat: if abs(elt) > atol: angle = np.angle(elt) phase_difference -= angle mat1 = np.exp(-1j * angle) * mat1 break for elt in mat2.flat: if abs(elt) > atol: angle = np.angle(elt) phase_difference += angle mat2 = np.exp(-1j * np.angle(elt)) * mat2 break if props is not None: props["phase_difference"] = phase_difference return np.allclose(mat1, mat2, rtol=rtol, atol=atol) def is_square_matrix(mat): """Test if an array is a square matrix.""" mat = np.array(mat) if mat.ndim != 2: return False shape = mat.shape return shape[0] == shape[1] def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is a diagonal matrix""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(mat) if mat.ndim != 2: return False return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol) def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is a symmetric matrix""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(op) if mat.ndim != 2: return False return np.allclose(mat, mat.T, rtol=rtol, atol=atol) def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is a Hermitian matrix""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(mat) if mat.ndim != 2: return False return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol) def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if a matrix is positive semidefinite""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT if not is_hermitian_matrix(mat, rtol=rtol, atol=atol): return False # Check eigenvalues are all positive vals = np.linalg.eigvalsh(mat) for v in vals: if v < -atol: return False return True def is_identity_matrix(mat, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is an identity matrix.""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(mat) if mat.ndim != 2: return False if ignore_phase: # If the matrix is equal to an identity up to a phase, we can # remove the phase by multiplying each entry by the complex # conjugate of the phase of the [0, 0] entry. theta = np.angle(mat[0, 0]) mat = np.exp(-1j * theta) * mat # Check if square identity iden = np.eye(len(mat)) return np.allclose(mat, iden, rtol=rtol, atol=atol) def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is a unitary matrix.""" mat = np.array(mat) # Compute A^dagger.A and see if it is identity matrix mat = np.conj(mat.T).dot(mat) return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol) def is_isometry(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is an isometry.""" mat = np.array(mat) # Compute A^dagger.A and see if it is identity matrix iden = np.eye(mat.shape[1]) mat = np.conj(mat.T).dot(mat) return np.allclose(mat, iden, rtol=rtol, atol=atol)
qiskit/qiskit/quantum_info/operators/predicates.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/predicates.py", "repo_id": "qiskit", "token_count": 2551 }
196
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A module for using quaternions. """ from __future__ import annotations import math import numpy as np class Quaternion: """A class representing a Quaternion.""" def __init__(self, data): self.data = np.asarray(data, dtype=float) def __call__(self, idx): return self.data[idx] def __repr__(self): return np.array_str(self.data) def __str__(self): return np.array_str(self.data) def __mul__(self, r): if isinstance(r, Quaternion): q = self out_data = np.zeros(4, dtype=float) out_data[0] = r(0) * q(0) - r(1) * q(1) - r(2) * q(2) - r(3) * q(3) out_data[1] = r(0) * q(1) + r(1) * q(0) - r(2) * q(3) + r(3) * q(2) out_data[2] = r(0) * q(2) + r(1) * q(3) + r(2) * q(0) - r(3) * q(1) out_data[3] = r(0) * q(3) - r(1) * q(2) + r(2) * q(1) + r(3) * q(0) return Quaternion(out_data) else: return NotImplemented def norm(self): """Norm of quaternion.""" import scipy.linalg as la return la.norm(self.data) def normalize(self, inplace: bool = False) -> Quaternion: """Normalizes a Quaternion to unit length so that it represents a valid rotation. Args: inplace (bool): Do an inplace normalization. Returns: Quaternion: Normalized quaternion. """ if inplace: nrm = self.norm() self.data /= nrm return None nrm = self.norm() data_copy = np.array(self.data, copy=True) data_copy /= nrm return Quaternion(data_copy) def to_matrix(self) -> np.ndarray: """Converts a unit-length quaternion to a rotation matrix. Returns: ndarray: Rotation matrix. """ w, x, y, z = self.normalize().data mat = np.array( [ [1 - 2 * y**2 - 2 * z**2, 2 * x * y - 2 * z * w, 2 * x * z + 2 * y * w], [2 * x * y + 2 * z * w, 1 - 2 * x**2 - 2 * z**2, 2 * y * z - 2 * x * w], [2 * x * z - 2 * y * w, 2 * y * z + 2 * x * w, 1 - 2 * x**2 - 2 * y**2], ], dtype=float, ) return mat def to_zyz(self) -> np.ndarray: """Converts a unit-length quaternion to a sequence of ZYZ Euler angles. Returns: ndarray: Array of Euler angles. """ mat = self.to_matrix() euler = np.zeros(3, dtype=float) if mat[2, 2] < 1: if mat[2, 2] > -1: euler[0] = math.atan2(mat[1, 2], mat[0, 2]) euler[1] = math.acos(mat[2, 2]) euler[2] = math.atan2(mat[2, 1], -mat[2, 0]) else: euler[0] = -math.atan2(mat[1, 0], mat[1, 1]) euler[1] = np.pi else: euler[0] = math.atan2(mat[1, 0], mat[1, 1]) return euler @classmethod def from_axis_rotation(cls, angle: float, axis: str) -> Quaternion: """Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis. """ out = np.zeros(4, dtype=float) if axis == "x": out[1] = 1 elif axis == "y": out[2] = 1 elif axis == "z": out[3] = 1 else: raise ValueError("Invalid axis input.") out *= math.sin(angle / 2.0) out[0] = math.cos(angle / 2.0) return cls(out) @classmethod def from_euler(cls, angles: list | np.ndarray, order: str = "yzy") -> Quaternion: """Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation. """ angles = np.asarray(angles, dtype=float) quat = ( cls.from_axis_rotation(angles[0], order[0]) * cls.from_axis_rotation(angles[1], order[1]) * cls.from_axis_rotation(angles[2], order[2]) ) quat.normalize(inplace=True) return quat
qiskit/qiskit/quantum_info/quaternion.py/0
{ "file_path": "qiskit/qiskit/quantum_info/quaternion.py", "repo_id": "qiskit", "token_count": 2481 }
197
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Mapping a scheduled QuantumCircuit to a pulse Schedule. """ from collections import defaultdict from typing import Optional, Union from qiskit.circuit.barrier import Barrier from qiskit.circuit.measure import Measure from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.pulse.schedule import Schedule from qiskit.pulse.transforms import pad from qiskit.scheduler.config import ScheduleConfig from qiskit.scheduler.lowering import lower_gates from qiskit.providers import BackendV1, BackendV2 def sequence( scheduled_circuit: QuantumCircuit, schedule_config: ScheduleConfig, backend: Optional[Union[BackendV1, BackendV2]] = None, ) -> Schedule: """ Return the pulse Schedule which implements the input scheduled circuit. Assume all measurements are done at once at the last of the circuit. Schedules according to the command definition given by the schedule_config. Args: scheduled_circuit: The scheduled quantum circuit to translate. schedule_config: Backend specific parameters used for building the Schedule. backend: A backend used to build the Schedule, the backend could be BackendV1 or BackendV2 Returns: A schedule corresponding to the input ``circuit``. Raises: QiskitError: If invalid scheduled circuit is supplied. """ circ_pulse_defs = lower_gates(scheduled_circuit, schedule_config, backend) # find the measurement start time (assume measurement once) def _meas_start_time(): _qubit_time_available = defaultdict(int) for instruction in scheduled_circuit.data: if isinstance(instruction.operation, Measure): return _qubit_time_available[instruction.qubits[0]] for q in instruction.qubits: _qubit_time_available[q] += instruction.operation.duration return None meas_time = _meas_start_time() # restore start times qubit_time_available = {} start_times = [] out_circ_pulse_defs = [] for circ_pulse_def in circ_pulse_defs: active_qubits = [q for q in circ_pulse_def.qubits if q in qubit_time_available] start_time = max((qubit_time_available[q] for q in active_qubits), default=0) for q in active_qubits: if qubit_time_available[q] != start_time: # print(q, ":", qubit_time_available[q], "!=", start_time) raise QiskitError("Invalid scheduled circuit.") stop_time = start_time if not isinstance(circ_pulse_def.schedule, Barrier): stop_time += circ_pulse_def.schedule.duration delay_overlaps_meas = False for q in circ_pulse_def.qubits: qubit_time_available[q] = stop_time if ( meas_time is not None and circ_pulse_def.schedule.name == "delay" and stop_time > meas_time ): qubit_time_available[q] = meas_time delay_overlaps_meas = True # skip to delays overlapping measures and barriers if not delay_overlaps_meas and not isinstance(circ_pulse_def.schedule, Barrier): start_times.append(start_time) out_circ_pulse_defs.append(circ_pulse_def) timed_schedules = [(time, cpd.schedule) for time, cpd in zip(start_times, out_circ_pulse_defs)] sched = Schedule(*timed_schedules, name=scheduled_circuit.name) return pad(sched)
qiskit/qiskit/scheduler/sequence.py/0
{ "file_path": "qiskit/qiskit/scheduler/sequence.py", "repo_id": "qiskit", "token_count": 1509 }
198
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Synthesize a single qubit gate to a discrete basis set.""" from __future__ import annotations import numpy as np from .gate_sequence import GateSequence from .commutator_decompose import commutator_decompose from .generate_basis_approximations import generate_basic_approximations, _1q_gates, _1q_inverses class SolovayKitaevDecomposition: """The Solovay Kitaev discrete decomposition algorithm. This class is called recursively by the transpiler pass, which is why it is separeted. See :class:`qiskit.transpiler.passes.SolovayKitaev` for more information. """ def __init__( self, basic_approximations: str | dict[str, np.ndarray] | list[GateSequence] | None = None ) -> None: """ Args: basic_approximations: A specification of the basic SU(2) approximations in terms of discrete gates. At each iteration this algorithm, the remaining error is approximated with the closest sequence of gates in this set. If a ``str``, this specifies a ``.npy`` filename from which to load the approximation. If a ``dict``, then this contains ``{gates: effective_SO3_matrix}`` pairs, e.g. ``{"h t": np.array([[0, 0.7071, -0.7071], [0, -0.7071, -0.7071], [-1, 0, 0]]}``. If a list, this contains the same information as the dict, but already converted to :class:`.GateSequence` objects, which contain the SO(3) matrix and gates. """ if basic_approximations is None: # generate a default basic approximation basic_approximations = generate_basic_approximations( basis_gates=["h", "t", "tdg"], depth=10 ) self.basic_approximations = self.load_basic_approximations(basic_approximations) @staticmethod def load_basic_approximations(data: list | str | dict) -> list[GateSequence]: """Load basic approximations. Args: data: If a string, specifies the path to the file from where to load the data. If a dictionary, directly specifies the decompositions as ``{gates: matrix}`` or ``{gates: (matrix, global_phase)}``. There, ``gates`` are the names of the gates producing the SO(3) matrix ``matrix``, e.g. ``{"h t": np.array([[0, 0.7071, -0.7071], [0, -0.7071, -0.7071], [-1, 0, 0]]}`` and the ``global_phase`` can be given to account for a global phase difference between the U(2) matrix of the quantum gates and the stored SO(3) matrix. If not given, the ``global_phase`` will be assumed to be 0. Returns: A list of basic approximations as type ``GateSequence``. Raises: ValueError: If the number of gate combinations and associated matrices does not match. """ # is already a list of GateSequences if isinstance(data, list): return data # if a file, load the dictionary if isinstance(data, str): data = np.load(data, allow_pickle=True).item() sequences = [] for gatestring, matrix_and_phase in data.items(): if isinstance(matrix_and_phase, tuple): matrix, global_phase = matrix_and_phase else: matrix, global_phase = matrix_and_phase, 0 sequence = GateSequence() sequence.gates = [_1q_gates[element] for element in gatestring.split()] sequence.labels = [gate.name for gate in sequence.gates] sequence.product = np.asarray(matrix) sequence.global_phase = global_phase sequences.append(sequence) return sequences def run( self, gate_matrix: np.ndarray, recursion_degree: int, return_dag: bool = False, check_input: bool = True, ) -> "QuantumCircuit" | "DAGCircuit": r"""Run the algorithm. Args: gate_matrix: The 2x2 matrix representing the gate. This matrix has to be SU(2) up to global phase. recursion_degree: The recursion degree, called :math:`n` in the paper. return_dag: If ``True`` return a :class:`.DAGCircuit`, else a :class:`.QuantumCircuit`. check_input: If ``True`` check that the input matrix is valid for the decomposition. Returns: A one-qubit circuit approximating the ``gate_matrix`` in the specified discrete basis. """ # make input matrix SU(2) and get the according global phase z = 1 / np.sqrt(np.linalg.det(gate_matrix)) gate_matrix_su2 = GateSequence.from_matrix(z * gate_matrix) global_phase = np.arctan2(np.imag(z), np.real(z)) # get the decomposition as GateSequence type decomposition = self._recurse(gate_matrix_su2, recursion_degree, check_input=check_input) # simplify _remove_identities(decomposition) _remove_inverse_follows_gate(decomposition) # convert to a circuit and attach the right phases if return_dag: out = decomposition.to_dag() else: out = decomposition.to_circuit() out.global_phase = decomposition.global_phase - global_phase return out def _recurse(self, sequence: GateSequence, n: int, check_input: bool = True) -> GateSequence: """Performs ``n`` iterations of the Solovay-Kitaev algorithm on ``sequence``. Args: sequence: ``GateSequence`` to which the Solovay-Kitaev algorithm is applied. n: The number of iterations that the algorithm needs to run. check_input: If ``True`` check that the input matrix represented by ``GateSequence`` is valid for the decomposition. Returns: GateSequence that approximates ``sequence``. Raises: ValueError: If the matrix in ``GateSequence`` does not represent an SO(3)-matrix. """ if sequence.product.shape != (3, 3): raise ValueError("Shape of U must be (3, 3) but is", sequence.shape) if n == 0: return self.find_basic_approximation(sequence) u_n1 = self._recurse(sequence, n - 1, check_input=check_input) v_n, w_n = commutator_decompose( sequence.dot(u_n1.adjoint()).product, check_input=check_input ) v_n1 = self._recurse(v_n, n - 1, check_input=check_input) w_n1 = self._recurse(w_n, n - 1, check_input=check_input) return v_n1.dot(w_n1).dot(v_n1.adjoint()).dot(w_n1.adjoint()).dot(u_n1) def find_basic_approximation(self, sequence: GateSequence) -> GateSequence: """Find ``GateSequence`` in ``self._basic_approximations`` that approximates ``sequence``. Args: sequence: ``GateSequence`` to find the approximation to. Returns: ``GateSequence`` in ``self._basic_approximations`` that approximates ``sequence``. """ # TODO explore using a k-d tree here def key(x): return np.linalg.norm(np.subtract(x.product, sequence.product)) best = min(self.basic_approximations, key=key) return best def _remove_inverse_follows_gate(sequence): index = 0 while index < len(sequence.gates) - 1: curr_gate = sequence.gates[index] next_gate = sequence.gates[index + 1] if curr_gate.name in _1q_inverses: remove = _1q_inverses[curr_gate.name] == next_gate.name else: remove = curr_gate.inverse() == next_gate if remove: # remove gates at index and index + 1 sequence.remove_cancelling_pair([index, index + 1]) # take a step back to see if we have uncovered a new pair, e.g. # [h, s, sdg, h] at index = 1 removes s, sdg but if we continue at index 1 # we miss the uncovered [h, h] pair at indices 0 and 1 if index > 0: index -= 1 else: # next index index += 1 def _remove_identities(sequence): index = 0 while index < len(sequence.gates): if sequence.gates[index].name == "id": sequence.gates.pop(index) else: index += 1
qiskit/qiskit/synthesis/discrete_basis/solovay_kitaev.py/0
{ "file_path": "qiskit/qiskit/synthesis/discrete_basis/solovay_kitaev.py", "repo_id": "qiskit", "token_count": 3756 }
199
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Synthesis of an n-qubit circuit containing only CZ gates for linear nearest neighbor (LNN) connectivity, using CX and phase (S, Sdg or Z) gates. The two-qubit depth of the circuit is bounded by 2*n+2. This algorithm reverts the order of qubits. References: [1]: Dmitri Maslov, Martin Roetteler, Shorter stabilizer circuits via Bruhat decomposition and quantum circuit transformations, `arXiv:1705.09176 <https://arxiv.org/abs/1705.09176>`_. """ import numpy as np from qiskit.circuit import QuantumCircuit from qiskit._accelerate.synthesis.linear_phase import ( synth_cz_depth_line_mr as synth_cz_depth_line_mr_inner, ) def synth_cz_depth_line_mr(mat: np.ndarray) -> QuantumCircuit: r"""Synthesis of a CZ circuit for linear nearest neighbor (LNN) connectivity, based on Maslov and Roetteler. Note that this method *reverts* the order of qubits in the circuit, and returns a circuit containing :class:`.CXGate`\s and phase gates (:class:`.SGate`, :class:`.SdgGate` or :class:`.ZGate`). Args: mat: an upper-diagonal matrix representing the CZ circuit. ``mat[i][j]=1 for i<j`` represents a ``cz(i,j)`` gate Returns: A circuit implementation of the CZ circuit of depth :math:`2n+2` for LNN connectivity. References: 1. Dmitri Maslov, Martin Roetteler, *Shorter stabilizer circuits via Bruhat decomposition and quantum circuit transformations*, `arXiv:1705.09176 <https://arxiv.org/abs/1705.09176>`_. """ # Call Rust implementaton return QuantumCircuit._from_circuit_data(synth_cz_depth_line_mr_inner(mat.astype(bool)))
qiskit/qiskit/synthesis/linear_phase/cz_depth_lnn.py/0
{ "file_path": "qiskit/qiskit/synthesis/linear_phase/cz_depth_lnn.py", "repo_id": "qiskit", "token_count": 745 }
200
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ These are the CNOT structure methods: anything that you need for creating CNOT structures. """ import logging import math import numpy as np _NETWORK_LAYOUTS = ["sequ", "spin", "cart", "cyclic_spin", "cyclic_line"] _CONNECTIVITY_TYPES = ["full", "line", "star"] logger = logging.getLogger(__name__) def _lower_limit(num_qubits: int) -> int: """ Returns lower limit on the number of CNOT units that guarantees exact representation of a unitary operator by quantum gates. Args: num_qubits: number of qubits. Returns: lower limit on the number of CNOT units. """ num_cnots = math.ceil((4**num_qubits - 3 * num_qubits - 1) / 4.0) return num_cnots def make_cnot_network( num_qubits: int, network_layout: str = "spin", connectivity_type: str = "full", depth: int = 0, ) -> np.ndarray: """ Generates a network consisting of building blocks each containing a CNOT gate and possibly some single-qubit ones. This network models a quantum operator in question. Note, each building block has 2 input and outputs corresponding to a pair of qubits. What we actually return here is a chain of indices of qubit pairs shared by every building block in a row. Args: num_qubits: number of qubits. network_layout: type of network geometry, ``{"sequ", "spin", "cart", "cyclic_spin", "cyclic_line"}``. connectivity_type: type of inter-qubit connectivity, ``{"full", "line", "star"}``. depth: depth of the CNOT-network, i.e. the number of layers, where each layer consists of a single CNOT-block; default value will be selected, if ``L <= 0``. Returns: A matrix of size ``(2, N)`` matrix that defines layers in cnot-network, where ``N`` is either equal ``L``, or defined by a concrete type of the network. Raises: ValueError: if unsupported type of CNOT-network layout or number of qubits or combination of parameters are passed. """ if num_qubits < 2: raise ValueError("Number of qubits must be greater or equal to 2") if depth <= 0: new_depth = _lower_limit(num_qubits) logger.debug( "Number of CNOT units chosen as the lower limit: %d, got a non-positive value: %d", new_depth, depth, ) depth = new_depth if network_layout == "sequ": links = _get_connectivity(num_qubits=num_qubits, connectivity=connectivity_type) return _sequential_network(num_qubits=num_qubits, links=links, depth=depth) elif network_layout == "spin": return _spin_network(num_qubits=num_qubits, depth=depth) elif network_layout == "cart": cnots = _cartan_network(num_qubits=num_qubits) logger.debug( "Optimal lower bound: %d; Cartan CNOTs: %d", _lower_limit(num_qubits), cnots.shape[1] ) return cnots elif network_layout == "cyclic_spin": if connectivity_type != "full": raise ValueError(f"'{network_layout}' layout expects 'full' connectivity") return _cyclic_spin_network(num_qubits, depth) elif network_layout == "cyclic_line": if connectivity_type != "line": raise ValueError(f"'{network_layout}' layout expects 'line' connectivity") return _cyclic_line_network(num_qubits, depth) else: raise ValueError( f"Unknown type of CNOT-network layout, expects one of {_NETWORK_LAYOUTS}, " f"got {network_layout}" ) def _get_connectivity(num_qubits: int, connectivity: str) -> dict: """ Generates connectivity structure between qubits. Args: num_qubits: number of qubits. connectivity: type of connectivity structure, ``{"full", "line", "star"}``. Returns: dictionary of allowed links between qubits. Raises: ValueError: if unsupported type of CNOT-network layout is passed. """ if num_qubits == 1: links = {0: [0]} elif connectivity == "full": # Full connectivity between qubits. links = {i: list(range(num_qubits)) for i in range(num_qubits)} elif connectivity == "line": # Every qubit is connected to its immediate neighbors only. links = {i: [i - 1, i, i + 1] for i in range(1, num_qubits - 1)} # first qubit links[0] = [0, 1] # last qubit links[num_qubits - 1] = [num_qubits - 2, num_qubits - 1] elif connectivity == "star": # Every qubit is connected to the first one only. links = {i: [0, i] for i in range(1, num_qubits)} # first qubit links[0] = list(range(num_qubits)) else: raise ValueError( f"Unknown connectivity type, expects one of {_CONNECTIVITY_TYPES}, got {connectivity}" ) return links def _sequential_network(num_qubits: int, links: dict, depth: int) -> np.ndarray: """ Generates a sequential network. Args: num_qubits: number of qubits. links: dictionary of connectivity links. depth: depth of the network (number of layers of building blocks). Returns: A matrix of ``(2, N)`` that defines layers in qubit network. """ layer = 0 cnots = np.zeros((2, depth), dtype=int) while True: for i in range(0, num_qubits - 1): for j in range(i + 1, num_qubits): if j in links[i]: cnots[0, layer] = i cnots[1, layer] = j layer += 1 if layer >= depth: return cnots def _spin_network(num_qubits: int, depth: int) -> np.ndarray: """ Generates a spin-like network. Args: num_qubits: number of qubits. depth: depth of the network (number of layers of building blocks). Returns: A matrix of size ``2 x L`` that defines layers in qubit network. """ layer = 0 cnots = np.zeros((2, depth), dtype=int) while True: for i in range(0, num_qubits - 1, 2): cnots[0, layer] = i cnots[1, layer] = i + 1 layer += 1 if layer >= depth: return cnots for i in range(1, num_qubits - 1, 2): cnots[0, layer] = i cnots[1, layer] = i + 1 layer += 1 if layer >= depth: return cnots def _cartan_network(num_qubits: int) -> np.ndarray: """ Cartan decomposition in a recursive way, starting from n = 3. Args: num_qubits: number of qubits. Returns: 2xN matrix that defines layers in qubit network, where N is the depth of Cartan decomposition. Raises: ValueError: if number of qubits is less than 3. """ n = num_qubits if n > 3: cnots = np.asarray([[0, 0, 0], [1, 1, 1]]) mult = np.asarray([[n - 2, n - 3, n - 2, n - 3], [n - 1, n - 1, n - 1, n - 1]]) for _ in range(n - 2): cnots = np.hstack((np.tile(np.hstack((cnots, mult)), 3), cnots)) mult[0, -1] -= 1 mult = np.tile(mult, 2) elif n == 3: cnots = np.asarray( [ [0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], ] ) else: raise ValueError(f"The number of qubits must be >= 3, got {n}.") return cnots def _cyclic_spin_network(num_qubits: int, depth: int) -> np.ndarray: """ Same as in the spin-like network, but the first and the last qubits are also connected. Args: num_qubits: number of qubits. depth: depth of the network (number of layers of building blocks). Returns: A matrix of size ``2 x L`` that defines layers in qubit network. """ cnots = np.zeros((2, depth), dtype=int) z = 0 while True: for i in range(0, num_qubits, 2): if i + 1 <= num_qubits - 1: cnots[0, z] = i cnots[1, z] = i + 1 z += 1 if z >= depth: return cnots for i in range(1, num_qubits, 2): if i + 1 <= num_qubits - 1: cnots[0, z] = i cnots[1, z] = i + 1 z += 1 elif i == num_qubits - 1: cnots[0, z] = i cnots[1, z] = 0 z += 1 if z >= depth: return cnots def _cyclic_line_network(num_qubits: int, depth: int) -> np.ndarray: """ Generates a line based CNOT structure. Args: num_qubits: number of qubits. depth: depth of the network (number of layers of building blocks). Returns: A matrix of size ``2 x L`` that defines layers in qubit network. """ cnots = np.zeros((2, depth), dtype=int) for i in range(depth): cnots[0, i] = (i + 0) % num_qubits cnots[1, i] = (i + 1) % num_qubits return cnots
qiskit/qiskit/synthesis/unitary/aqc/cnot_structures.py/0
{ "file_path": "qiskit/qiskit/synthesis/unitary/aqc/cnot_structures.py", "repo_id": "qiskit", "token_count": 4236 }
201
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ =================================================== Transpiler Passes (:mod:`qiskit.transpiler.passes`) =================================================== .. currentmodule:: qiskit.transpiler.passes Layout Selection (Placement) ============================ .. autosummary:: :toctree: ../stubs/ SetLayout TrivialLayout DenseLayout SabreLayout CSPLayout VF2Layout ApplyLayout Layout2qDistance EnlargeWithAncilla FullAncillaAllocation SabrePreLayout Routing ======= .. autosummary:: :toctree: ../stubs/ BasicSwap LookaheadSwap StochasticSwap SabreSwap Commuting2qGateRouter StarPreRouting Basis Change ============ .. autosummary:: :toctree: ../stubs/ BasisTranslator Decompose TranslateParameterizedGates Unroll3qOrMore UnrollCustomDefinitions Optimizations ============= .. autosummary:: :toctree: ../stubs/ Optimize1qGates Optimize1qGatesDecomposition Collect1qRuns Collect2qBlocks CollectMultiQBlocks CollectLinearFunctions CollectCliffords ConsolidateBlocks CXCancellation InverseCancellation CommutationAnalysis CommutativeCancellation CommutativeInverseCancellation Optimize1qGatesSimpleCommutation RemoveDiagonalGatesBeforeMeasure RemoveResetInZeroState RemoveFinalReset HoareOptimizer TemplateOptimization EchoRZXWeylDecomposition ResetAfterMeasureSimplification OptimizeCliffords ElidePermutations NormalizeRXAngle OptimizeAnnotated Split2QUnitaries Calibration ============= .. autosummary:: :toctree: ../stubs/ PulseGates RZXCalibrationBuilder RZXCalibrationBuilderNoEcho RXCalibrationBuilder .. autofunction:: rzx_templates Scheduling ============= .. autosummary:: :toctree: ../stubs/ TimeUnitConversion ALAPScheduleAnalysis ASAPScheduleAnalysis PadDynamicalDecoupling PadDelay ConstrainedReschedule ValidatePulseGates InstructionDurationCheck SetIOLatency ALAPSchedule ASAPSchedule DynamicalDecoupling AlignMeasures Circuit Analysis ================ .. autosummary:: :toctree: ../stubs/ Width Depth Size CountOps CountOpsLongestPath NumTensorFactors DAGLongestPath Synthesis ========= The synthesis transpiler plugin documentation can be found in the :mod:`qiskit.transpiler.passes.synthesis.plugin` page. .. autosummary:: :toctree: ../stubs/ UnitarySynthesis LinearFunctionsToPermutations HighLevelSynthesis HLSConfig SolovayKitaev Post Layout =========== These are post qubit selection. .. autosummary:: :toctree: ../stubs/ VF2PostLayout Additional Passes ================= .. autosummary:: :toctree: ../stubs/ CheckMap CheckGateDirection GateDirection MergeAdjacentBarriers RemoveBarriers BarrierBeforeFinalMeasurements RemoveFinalMeasurements DAGFixedPoint FixedPoint MinimumPoint ContainsInstruction GatesInBasis ConvertConditionsToIfOps UnrollForLoops FilterOpNodes """ # layout selection (placement) from .layout import SetLayout from .layout import TrivialLayout from .layout import DenseLayout from .layout import SabreLayout from .layout import CSPLayout from .layout import VF2Layout from .layout import VF2PostLayout from .layout import ApplyLayout from .layout import Layout2qDistance from .layout import EnlargeWithAncilla from .layout import FullAncillaAllocation from .layout import SabrePreLayout # routing from .routing import BasicSwap from .routing import LayoutTransformation from .routing import LookaheadSwap from .routing import StochasticSwap from .routing import SabreSwap from .routing import Commuting2qGateRouter from .routing import StarPreRouting # basis change from .basis import Decompose from .basis import UnrollCustomDefinitions from .basis import Unroll3qOrMore from .basis import BasisTranslator from .basis import TranslateParameterizedGates # optimization from .optimization import Optimize1qGates from .optimization import Optimize1qGatesDecomposition from .optimization import Collect2qBlocks from .optimization import Collect1qRuns from .optimization import CollectMultiQBlocks from .optimization import ConsolidateBlocks from .optimization import CommutationAnalysis from .optimization import CommutativeCancellation from .optimization import CommutativeInverseCancellation from .optimization import CXCancellation from .optimization import Optimize1qGatesSimpleCommutation from .optimization import OptimizeSwapBeforeMeasure from .optimization import RemoveResetInZeroState from .optimization import RemoveFinalReset from .optimization import RemoveDiagonalGatesBeforeMeasure from .optimization import HoareOptimizer from .optimization import TemplateOptimization from .optimization import InverseCancellation from .optimization import EchoRZXWeylDecomposition from .optimization import CollectLinearFunctions from .optimization import CollectCliffords from .optimization import ResetAfterMeasureSimplification from .optimization import OptimizeCliffords from .optimization import ElidePermutations from .optimization import NormalizeRXAngle from .optimization import OptimizeAnnotated from .optimization import Split2QUnitaries # circuit analysis from .analysis import ResourceEstimation from .analysis import Depth from .analysis import Size from .analysis import Width from .analysis import CountOps from .analysis import CountOpsLongestPath from .analysis import NumTensorFactors from .analysis import DAGLongestPath # synthesis from .synthesis import UnitarySynthesis from .synthesis import unitary_synthesis_plugin_names from .synthesis import LinearFunctionsToPermutations from .synthesis import HighLevelSynthesis from .synthesis import HLSConfig from .synthesis import SolovayKitaev from .synthesis import SolovayKitaevSynthesis from .synthesis import AQCSynthesisPlugin # calibration from .calibration import PulseGates from .calibration import RZXCalibrationBuilder from .calibration import RZXCalibrationBuilderNoEcho from .calibration import RXCalibrationBuilder from .calibration.rzx_templates import rzx_templates # circuit scheduling from .scheduling import TimeUnitConversion from .scheduling import ALAPScheduleAnalysis from .scheduling import ASAPScheduleAnalysis from .scheduling import PadDynamicalDecoupling from .scheduling import ValidatePulseGates from .scheduling import PadDelay from .scheduling import ConstrainedReschedule from .scheduling import InstructionDurationCheck from .scheduling import SetIOLatency from .scheduling import ALAPSchedule from .scheduling import ASAPSchedule from .scheduling import DynamicalDecoupling from .scheduling import AlignMeasures # additional utility passes from .utils import CheckMap from .utils import CheckGateDirection from .utils import GateDirection from .utils import BarrierBeforeFinalMeasurements from .utils import RemoveFinalMeasurements from .utils import MergeAdjacentBarriers from .utils import DAGFixedPoint from .utils import FixedPoint from .utils import MinimumPoint from .utils import Error from .utils import RemoveBarriers from .utils import ContainsInstruction from .utils import GatesInBasis from .utils import ConvertConditionsToIfOps from .utils import UnrollForLoops from .utils import FilterOpNodes
qiskit/qiskit/transpiler/passes/__init__.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/__init__.py", "repo_id": "qiskit", "token_count": 2344 }
202
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Unrolls instructions with custom definitions.""" from qiskit.exceptions import QiskitError from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow from qiskit.circuit import ControlledGate, ControlFlowOp from qiskit.converters.circuit_to_dag import circuit_to_dag class UnrollCustomDefinitions(TransformationPass): """Unrolls instructions with custom definitions.""" def __init__(self, equivalence_library, basis_gates=None, target=None, min_qubits=0): """Unrolls instructions with custom definitions. Args: equivalence_library (EquivalenceLibrary): The equivalence library which will be used by the BasisTranslator pass. (Instructions in this library will not be unrolled by this pass.) basis_gates (Optional[list[str]]): Target basis names to unroll to, e.g. ``['u3', 'cx']``. Ignored if ``target`` is also specified. target (Optional[Target]): The :class:`~.Target` object corresponding to the compilation target. When specified, any argument specified for ``basis_gates`` is ignored. min_qubits (int): The minimum number of qubits for operations in the input dag to translate. """ super().__init__() self._equiv_lib = equivalence_library self._basis_gates = basis_gates self._target = target self._min_qubits = min_qubits def run(self, dag): """Run the UnrollCustomDefinitions pass on `dag`. Args: dag (DAGCircuit): input dag Raises: QiskitError: if unable to unroll given the basis due to undefined decomposition rules (such as a bad basis) or excessive recursion. Returns: DAGCircuit: output unrolled dag """ if self._basis_gates is None and self._target is None: return dag device_insts = {"measure", "reset", "barrier", "snapshot", "delay", "store"} if self._target is None: device_insts |= set(self._basis_gates) for node in dag.op_nodes(): if isinstance(node.op, ControlFlowOp): dag.substitute_node( node, control_flow.map_blocks(self.run, node.op), propagate_condition=False ) continue if getattr(node.op, "_directive", False): continue if dag.has_calibration_for(node) or len(node.qargs) < self._min_qubits: continue controlled_gate_open_ctrl = isinstance(node.op, ControlledGate) and node.op._open_ctrl if not controlled_gate_open_ctrl: if self._target is not None: inst_supported = self._target.instruction_supported( operation_name=node.op.name, qargs=tuple(dag.find_bit(x).index for x in node.qargs), ) else: inst_supported = node.name in device_insts if inst_supported or self._equiv_lib.has_entry(node.op): continue try: unrolled = getattr(node.op, "definition", None) except TypeError as err: raise QiskitError(f"Error decomposing node {node.name}: {err}") from err if unrolled is None: # opaque node raise QiskitError( f"Cannot unroll the circuit to the given basis, {str(self._basis_gates)}. " f"Instruction {node.op.name} not found in equivalence library " "and no rule found to expand." ) decomposition = circuit_to_dag(unrolled, copy_operations=False) unrolled_dag = self.run(decomposition) dag.substitute_node_with_dag(node, unrolled_dag) return dag
qiskit/qiskit/transpiler/passes/basis/unroll_custom_definitions.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/basis/unroll_custom_definitions.py", "repo_id": "qiskit", "token_count": 1939 }
203
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Allocate all idle nodes from the coupling map as ancilla on the layout.""" from qiskit.circuit import QuantumRegister from qiskit.transpiler.basepasses import AnalysisPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.target import Target class FullAncillaAllocation(AnalysisPass): """Allocate all idle nodes from the coupling map or target as ancilla on the layout. A pass for allocating all idle physical qubits (those that exist in coupling map or target but not the dag circuit) as ancilla. It will also choose new virtual qubits to correspond to those physical ancilla. Note: This is an analysis pass, and only responsible for choosing physical ancilla locations and their corresponding virtual qubits. A separate transformation pass must add those virtual qubits to the circuit. """ def __init__(self, coupling_map): """FullAncillaAllocation initializer. Args: coupling_map (Union[CouplingMap, Target]): directed graph representing a coupling map. """ super().__init__() if isinstance(coupling_map, Target): self.target = coupling_map self.coupling_map = self.target.build_coupling_map() else: self.target = None self.coupling_map = coupling_map self.ancilla_name = "ancilla" def run(self, dag): """Run the FullAncillaAllocation pass on `dag`. Extend the layout with new (physical qubit, virtual qubit) pairs. The dag signals which virtual qubits are already in the circuit. This pass will allocate new virtual qubits such that no collision occurs (i.e. Layout bijectivity is preserved) The coupling_map and layout together determine which physical qubits are free. Args: dag (DAGCircuit): circuit to analyze Returns: DAGCircuit: returns the same dag circuit, unmodified Raises: TranspilerError: If there is not layout in the property set or not set at init time. """ layout = self.property_set.get("layout") if layout is None: raise TranspilerError('FullAncillaAllocation pass requires property_set["layout"].') virtual_bits = layout.get_virtual_bits() physical_bits = layout.get_physical_bits() if layout: FullAncillaAllocation.validate_layout(virtual_bits, set(dag.qubits)) layout_physical_qubits = list(range(max(physical_bits) + 1)) else: layout_physical_qubits = [] idle_physical_qubits = [q for q in layout_physical_qubits if q not in physical_bits] if self.target is not None and self.target.num_qubits is not None: idle_physical_qubits = [ q for q in range(self.target.num_qubits) if q not in physical_bits ] elif self.coupling_map: idle_physical_qubits = [ q for q in self.coupling_map.physical_qubits if q not in physical_bits ] if idle_physical_qubits: if self.ancilla_name in dag.qregs: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = self.ancilla_name qreg = QuantumRegister(len(idle_physical_qubits)) QuantumRegister.prefix = save_prefix else: qreg = QuantumRegister(len(idle_physical_qubits), name=self.ancilla_name) for idx, idle_q in enumerate(idle_physical_qubits): self.property_set["layout"][idle_q] = qreg[idx] self.property_set["layout"].add_register(qreg) return dag @staticmethod def validate_layout(layout_qubits, dag_qubits): """ Checks if all the qregs in ``layout_qregs`` already exist in ``dag_qregs``. Otherwise, raise. """ for qreg in layout_qubits: if qreg not in dag_qubits: raise TranspilerError( "FullAncillaAllocation: The layout refers to a qubit " "that does not exist in circuit." )
qiskit/qiskit/transpiler/passes/layout/full_ancilla_allocation.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/layout/full_ancilla_allocation.py", "repo_id": "qiskit", "token_count": 1864 }
204
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Collect sequences of uninterrupted gates acting on a number of qubits.""" from qiskit.transpiler.basepasses import AnalysisPass from qiskit.circuit import Gate from qiskit.dagcircuit import DAGOpNode, DAGInNode class CollectMultiQBlocks(AnalysisPass): """Collect sequences of uninterrupted gates acting on groups of qubits. ``max_block_size`` specifies the maximum number of qubits that can be acted upon by any single group of gates Traverse the DAG and find blocks of gates that act consecutively on groups of qubits. Write the blocks to ``property_set`` as a list of blocks of the form:: [[g0, g1, g2], [g4, g5]] Blocks are reported in a valid topological order. Further, the gates within each block are also reported in topological order Some gates may not be present in any block (e.g. if the number of operands is greater than ``max_block_size``) A Disjoint Set Union data structure (DSU) is used to maintain blocks as gates are processed. This data structure points each qubit to a set at all times and the sets correspond to current blocks. These change over time and the data structure allows these changes to be done quickly. """ def __init__(self, max_block_size=2): super().__init__() self.parent = {} # parent array for the union # the dicts belowed are keyed by a qubit signifying the root of a # set in the DSU data structure self.bit_groups = {} # current groups of bits stored at top of trees self.gate_groups = {} # current gate lists for the groups self.max_block_size = max_block_size # maximum block size def find_set(self, index): """DSU function for finding root of set of items If my parent is myself, I am the root. Otherwise we recursively find the root for my parent. After that, we assign my parent to be my root, saving recursion in the future. """ if index not in self.parent: self.parent[index] = index self.bit_groups[index] = [index] self.gate_groups[index] = [] if self.parent[index] == index: return index self.parent[index] = self.find_set(self.parent[index]) return self.parent[index] def union_set(self, set1, set2): """DSU function for unioning two sets together Find the roots of each set. Then assign one to have the other as its parent, thus liking the sets. Merges smaller set into larger set in order to have better runtime """ set1 = self.find_set(set1) set2 = self.find_set(set2) if set1 == set2: return if len(self.gate_groups[set1]) < len(self.gate_groups[set2]): set1, set2 = set2, set1 self.parent[set2] = set1 self.gate_groups[set1].extend(self.gate_groups[set2]) self.bit_groups[set1].extend(self.bit_groups[set2]) self.gate_groups[set2].clear() self.bit_groups[set2].clear() def run(self, dag): """Run the CollectMultiQBlocks pass on `dag`. The blocks contain "op" nodes in topological sort order such that all gates in a block act on the same set of qubits and are adjacent in the circuit. The blocks are built by examining predecessors and successors of "cx" gates in the circuit. u1, u2, u3, cx, id gates will be included. After the execution, ``property_set['block_list']`` is set to a list of tuples of ``DAGNode`` objects """ self.parent = {} # reset all variables on run self.bit_groups = {} self.gate_groups = {} block_list = [] def collect_key(x): """special key function for topological ordering. Heuristic for this is to push all gates involving measurement or barriers, etc. as far back as possible (because they force blocks to end). After that, we process gates in order of lowest number of qubits acted on to largest number of qubits acted on because these have less chance of increasing the size of blocks The key also processes all the non operation notes first so that input nodes do not mess with the top sort of op nodes """ if isinstance(x, DAGInNode): return "a" if not isinstance(x, DAGOpNode): return "d" if isinstance(x.op, Gate): if x.op.is_parameterized() or getattr(x.op, "condition", None) is not None: return "c" return "b" + chr(ord("a") + len(x.qargs)) return "d" op_nodes = dag.topological_op_nodes(key=collect_key) for nd in op_nodes: can_process = True makes_too_big = False # check if the node is a gate and if it is parameterized if ( getattr(nd.op, "condition", None) is not None or nd.op.is_parameterized() or not isinstance(nd.op, Gate) ): can_process = False cur_qubits = {dag.find_bit(bit).index for bit in nd.qargs} if can_process: # if the gate is valid, check if grouping up the bits # in the gate would fit within our desired max size c_tops = set() for bit in cur_qubits: c_tops.add(self.find_set(bit)) tot_size = 0 for group in c_tops: tot_size += len(self.bit_groups[group]) if tot_size > self.max_block_size: makes_too_big = True if not can_process: # resolve the case where we cannot process this node for bit in cur_qubits: # create a gate out of me bit = self.find_set(bit) if len(self.gate_groups[bit]) == 0: continue block_list.append(self.gate_groups[bit][:]) cur_set = set(self.bit_groups[bit]) for v in cur_set: # reset this bit self.parent[v] = v self.bit_groups[v] = [v] self.gate_groups[v] = [] if makes_too_big: # adding in all of the new qubits would make the group too big # we must block off sub portions of the groups until the new # group would no longer be too big savings = {} tot_size = 0 for bit in cur_qubits: top = self.find_set(bit) if top in savings: savings[top] = savings[top] - 1 else: savings[top] = len(self.bit_groups[top]) - 1 tot_size += len(self.bit_groups[top]) slist = [] for item, value in savings.items(): slist.append((value, item)) slist.sort(reverse=True) savings_need = tot_size - self.max_block_size for item in slist: # remove groups until the size created would be acceptable # start with blocking out the group that would decrease # the new size the most. This heuristic for which blocks we # create does not necessarily give the optimal blocking. Other # heuristics may be worth considering if savings_need > 0: savings_need = savings_need - item[0] if len(self.gate_groups[item[1]]) >= 1: block_list.append(self.gate_groups[item[1]][:]) cur_set = set(self.bit_groups[item[1]]) for v in cur_set: self.parent[v] = v self.bit_groups[v] = [v] self.gate_groups[v] = [] if can_process: # if the operation is a gate, either skip it if it is too large # or group up all of the qubits involved in the gate if len(cur_qubits) > self.max_block_size: # gates acting on more qubits than max_block_size cannot # be a part of any block and thus we skip them here. # we have already finalized the blocks involving the gate's # qubits in the above makes_too_big block continue # unable to be part of a group prev = -1 for bit in cur_qubits: if prev != -1: self.union_set(prev, bit) prev = bit self.gate_groups[self.find_set(prev)].append(nd) # need to turn all groups that still exist into their own blocks for index, item in self.parent.items(): if item == index and len(self.gate_groups[index]) != 0: block_list.append(self.gate_groups[index][:]) self.property_set["block_list"] = block_list return dag
qiskit/qiskit/transpiler/passes/optimization/collect_multiqubit_blocks.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/collect_multiqubit_blocks.py", "repo_id": "qiskit", "token_count": 4517 }
205
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Remove the swaps followed by measurement (and adapt the measurement).""" from qiskit.circuit import Measure from qiskit.circuit.library.standard_gates import SwapGate from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow from qiskit.dagcircuit import DAGCircuit, DAGOpNode, DAGOutNode class OptimizeSwapBeforeMeasure(TransformationPass): """Remove the swaps followed by measurement (and adapt the measurement). Transpiler pass to remove swaps in front of measurements by re-targeting the classical bit of the measure instruction. """ @control_flow.trivial_recurse def run(self, dag): """Run the OptimizeSwapBeforeMeasure pass on `dag`. Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. """ swaps = dag.op_nodes(SwapGate) for swap in swaps[::-1]: if getattr(swap.op, "condition", None) is not None: continue final_successor = [] for successor in dag.descendants(swap): final_successor.append( isinstance(successor, DAGOutNode) or (isinstance(successor, DAGOpNode) and isinstance(successor.op, Measure)) ) if all(final_successor): # the node swap needs to be removed and, if a measure follows, needs to be adapted swap_qargs = swap.qargs measure_layer = DAGCircuit() for qreg in dag.qregs.values(): measure_layer.add_qreg(qreg) for creg in dag.cregs.values(): measure_layer.add_creg(creg) for successor in list(dag.descendants(swap)): if isinstance(successor, DAGOpNode) and isinstance(successor.op, Measure): # replace measure node with a new one, where qargs is set with the "other" # swap qarg. dag.remove_op_node(successor) old_measure_qarg = successor.qargs[0] new_measure_qarg = swap_qargs[swap_qargs.index(old_measure_qarg) - 1] measure_layer.apply_operation_back( Measure(), (new_measure_qarg,), (successor.cargs[0],), check=False ) dag.compose(measure_layer) dag.remove_op_node(swap) return dag
qiskit/qiskit/transpiler/passes/optimization/optimize_swap_before_measure.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/optimize_swap_before_measure.py", "repo_id": "qiskit", "token_count": 1346 }
206
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Validation and optimization for hardware instruction alignment constraints. This is a control electronics aware analysis pass group. In many quantum computing architectures gates (instructions) are implemented with shaped analog stimulus signals. These signals are digitally stored in the waveform memory of the control electronics and converted into analog voltage signals by electronic components called digital to analog converters (DAC). In a typical hardware implementation of superconducting quantum processors, a single qubit instruction is implemented by a microwave signal with the duration of around several tens of ns with a per-sample time resolution of ~0.1-10ns, as reported by ``backend.configuration().dt``. In such systems requiring higher DAC bandwidth, control electronics often defines a `pulse granularity`, in other words a data chunk, to allow the DAC to perform the signal conversion in parallel to gain the bandwidth. A control electronics, i.e. micro-architecture, of the real quantum backend may impose some constraints on the start time of microinstructions. In Qiskit SDK, the duration of :class:`qiskit.circuit.Delay` can take arbitrary value in units of dt, thus circuits involving delays may violate the constraints, which may result in failure in the circuit execution on the backend. There are two alignment constraint values reported by your quantum backend. In addition, if you want to define a custom instruction as a pulse gate, i.e. calibration, the underlying pulse instruction should satisfy other two waveform constraints. Pulse alignment constraint This value is reported by ``timing_constraints["pulse_alignment"]`` in the backend configuration in units of dt. The start time of the all pulse instruction should be multiple of this value. Violation of this constraint may result in the backend execution failure. In most of the scenarios, the scheduled start time of ``DAGOpNode`` corresponds to the start time of the underlying pulse instruction composing the node operation. However, this assumption can be intentionally broken by defining a pulse gate, i.e. calibration, with the schedule involving pre-buffer, i.e. some random pulse delay followed by a pulse instruction. Because this pass is not aware of such edge case, the user must take special care of pulse gates if any. Acquire alignment constraint This value is reported by ``timing_constraints["acquire_alignment"]`` in the backend configuration in units of dt. The start time of the :class:`~qiskit.circuit.Measure` instruction should be multiple of this value. Granularity constraint This value is reported by ``timing_constraints["granularity"]`` in the backend configuration in units of dt. This is the constraint for a single pulse :class:`Play` instruction that may constitute your pulse gate. The length of waveform samples should be multiple of this constraint value. Violation of this constraint may result in failue in backend execution. Minimum pulse length constraint This value is reported by ``timing_constraints["min_length"]`` in the backend configuration in units of dt. This is the constraint for a single pulse :class:`Play` instruction that may constitute your pulse gate. The length of waveform samples should be greater than this constraint value. Violation of this constraint may result in failue in backend execution. """ from .check_durations import InstructionDurationCheck from .pulse_gate_validation import ValidatePulseGates from .reschedule import ConstrainedReschedule from .align_measures import AlignMeasures
qiskit/qiskit/transpiler/passes/scheduling/alignments/__init__.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/scheduling/alignments/__init__.py", "repo_id": "qiskit", "token_count": 1009 }
207
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Set classical IO latency information to circuit.""" from qiskit.transpiler.basepasses import AnalysisPass from qiskit.dagcircuit import DAGCircuit class SetIOLatency(AnalysisPass): """Set IOLatency information to the input circuit. The ``clbit_write_latency`` and ``conditional_latency`` are added to the property set of pass manager. This information can be shared among the passes that perform scheduling on instructions acting on classical registers. Once these latencies are added to the property set, this information is also copied to the output circuit object as protected attributes, so that it can be utilized outside the transpilation, for example, the timeline visualization can use latency to accurately show time occupation by instructions on the classical registers. """ def __init__( self, clbit_write_latency: int = 0, conditional_latency: int = 0, ): """Create pass with latency information. Args: clbit_write_latency: A control flow constraints. Because standard superconducting quantum processor implement dispersive QND readout, the actual data transfer to the clbit happens after the round-trip stimulus signal is buffered and discriminated into quantum state. The interval ``[t0, t0 + clbit_write_latency]`` is regarded as idle time for clbits associated with the measure instruction. This defaults to 0 dt which is identical to Qiskit Pulse scheduler. conditional_latency: A control flow constraints. This value represents a latency of reading a classical register for the conditional operation. The gate operation occurs after this latency. This appears as a delay in front of the DAGOpNode of the gate. This defaults to 0 dt. """ super().__init__() self._conditional_latency = conditional_latency self._clbit_write_latency = clbit_write_latency def run(self, dag: DAGCircuit): """Add IO latency information. Args: dag: Input DAG circuit. """ self.property_set["conditional_latency"] = self._conditional_latency self.property_set["clbit_write_latency"] = self._clbit_write_latency
qiskit/qiskit/transpiler/passes/scheduling/scheduling/set_io_latency.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/scheduling/scheduling/set_io_latency.py", "repo_id": "qiskit", "token_count": 968 }
208
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Internal utilities for working with control-flow operations.""" import functools from typing import Callable from qiskit.circuit import ControlFlowOp from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.dagcircuit import DAGCircuit def map_blocks(dag_mapping: Callable[[DAGCircuit], DAGCircuit], op: ControlFlowOp) -> ControlFlowOp: """Use the ``dag_mapping`` function to replace the blocks of a :class:`.ControlFlowOp` with new ones. Each block will be automatically converted to a :class:`.DAGCircuit` and then returned to a :class:`.QuantumCircuit`.""" return op.replace_blocks( [ dag_to_circuit(dag_mapping(circuit_to_dag(block)), copy_operations=False) for block in op.blocks ] ) def trivial_recurse(method): """Decorator that causes :class:`.BasePass.run` to iterate over all control-flow nodes, replacing their operations with a new :class:`.ControlFlowOp` whose blocks have all had :class`.BasePass.run` called on them. This is only suitable for simple run calls that store no state between calls, do not need circuit-specific information feeding into them (such as via a :class:`.PropertySet`), and will safely do nothing to control-flow operations that are in the DAG. If slightly finer control is needed on when the control-flow operations are modified, one can use :func:`map_blocks` as:: if isinstance(node.op, ControlFlowOp): dag.substitute_node(node, map_blocks(self.run, node.op)) from with :meth:`.BasePass.run`.""" @functools.wraps(method) def out(self, dag): def bound_wrapped_method(dag): return out(self, dag) control_flow_nodes = dag.control_flow_op_nodes() if control_flow_nodes is not None: for node in control_flow_nodes: dag.substitute_node( node, map_blocks(bound_wrapped_method, node.op), propagate_condition=False ) return method(self, dag) return out
qiskit/qiskit/transpiler/passes/utils/control_flow.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/utils/control_flow.py", "repo_id": "qiskit", "token_count": 899 }
209
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Built-in transpiler stage plugins for preset pass managers.""" import os from qiskit.transpiler.passes.optimization.split_2q_unitaries import Split2QUnitaries from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler.passes import LookaheadSwap from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler.passes import SabreSwap from qiskit.transpiler.passes import Error from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes import VF2Layout from qiskit.transpiler.passes import SabreLayout from qiskit.transpiler.passes import DenseLayout from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.passes import CheckMap from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements from qiskit.transpiler.passes import ElidePermutations from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure from qiskit.transpiler.preset_passmanagers import common from qiskit.transpiler.preset_passmanagers.plugin import ( PassManagerStagePlugin, PassManagerStagePluginManager, ) from qiskit.transpiler.passes.optimization import ( Optimize1qGatesDecomposition, CommutativeCancellation, Collect2qBlocks, ConsolidateBlocks, InverseCancellation, ) from qiskit.transpiler.passes import Depth, Size, FixedPoint, MinimumPoint from qiskit.transpiler.passes.utils.gates_basis import GatesInBasis from qiskit.transpiler.passes.synthesis.unitary_synthesis import UnitarySynthesis from qiskit.passmanager.flow_controllers import ConditionalController, DoWhileController from qiskit.transpiler.timing_constraints import TimingConstraints from qiskit.transpiler.passes.layout.vf2_layout import VF2LayoutStopReason from qiskit.circuit.library.standard_gates import ( CXGate, ECRGate, CZGate, XGate, YGate, ZGate, TGate, TdgGate, SwapGate, SGate, SdgGate, HGate, CYGate, SXGate, SXdgGate, ) from qiskit.utils.parallel import CPU_COUNT from qiskit import user_config CONFIG = user_config.get_config() _discrete_skipped_ops = { "delay", "reset", "measure", "switch_case", "if_else", "for_loop", "while_loop", } class DefaultInitPassManager(PassManagerStagePlugin): """Plugin class for default init stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: if optimization_level == 0: init = None if ( pass_manager_config.initial_layout or pass_manager_config.coupling_map or ( pass_manager_config.target is not None and pass_manager_config.target.build_coupling_map() is not None ) ): init = common.generate_unroll_3q( pass_manager_config.target, pass_manager_config.basis_gates, pass_manager_config.approximation_degree, pass_manager_config.unitary_synthesis_method, pass_manager_config.unitary_synthesis_plugin_config, pass_manager_config.hls_config, pass_manager_config.qubits_initially_zero, ) elif optimization_level == 1: init = PassManager() if ( pass_manager_config.initial_layout or pass_manager_config.coupling_map or ( pass_manager_config.target is not None and pass_manager_config.target.build_coupling_map() is not None ) ): init += common.generate_unroll_3q( pass_manager_config.target, pass_manager_config.basis_gates, pass_manager_config.approximation_degree, pass_manager_config.unitary_synthesis_method, pass_manager_config.unitary_synthesis_plugin_config, pass_manager_config.hls_config, pass_manager_config.qubits_initially_zero, ) init.append( InverseCancellation( [ CXGate(), ECRGate(), CZGate(), CYGate(), XGate(), YGate(), ZGate(), HGate(), SwapGate(), (TGate(), TdgGate()), (SGate(), SdgGate()), (SXGate(), SXdgGate()), ] ) ) elif optimization_level in {2, 3}: init = common.generate_unroll_3q( pass_manager_config.target, pass_manager_config.basis_gates, pass_manager_config.approximation_degree, pass_manager_config.unitary_synthesis_method, pass_manager_config.unitary_synthesis_plugin_config, pass_manager_config.hls_config, pass_manager_config.qubits_initially_zero, ) init.append(ElidePermutations()) init.append(RemoveDiagonalGatesBeforeMeasure()) init.append( InverseCancellation( [ CXGate(), ECRGate(), CZGate(), CYGate(), XGate(), YGate(), ZGate(), HGate(), SwapGate(), (TGate(), TdgGate()), (SGate(), SdgGate()), (SXGate(), SXdgGate()), ] ) ) init.append(CommutativeCancellation()) init.append(Collect2qBlocks()) init.append(ConsolidateBlocks()) # If approximation degree is None that indicates a request to approximate up to the # error rates in the target. However, in the init stage we don't yet know the target # qubits being used to figure out the fidelity so just use the default fidelity parameter # in this case. if pass_manager_config.approximation_degree is not None: init.append(Split2QUnitaries(pass_manager_config.approximation_degree)) else: init.append(Split2QUnitaries()) else: raise TranspilerError(f"Invalid optimization level {optimization_level}") return init class BasisTranslatorPassManager(PassManagerStagePlugin): """Plugin class for translation stage with :class:`~.BasisTranslator`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: return common.generate_translation_passmanager( pass_manager_config.target, basis_gates=pass_manager_config.basis_gates, method="translator", approximation_degree=pass_manager_config.approximation_degree, coupling_map=pass_manager_config.coupling_map, backend_props=pass_manager_config.backend_properties, unitary_synthesis_method=pass_manager_config.unitary_synthesis_method, unitary_synthesis_plugin_config=pass_manager_config.unitary_synthesis_plugin_config, hls_config=pass_manager_config.hls_config, qubits_initially_zero=pass_manager_config.qubits_initially_zero, ) class UnitarySynthesisPassManager(PassManagerStagePlugin): """Plugin class for translation stage with :class:`~.BasisTranslator`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: return common.generate_translation_passmanager( pass_manager_config.target, basis_gates=pass_manager_config.basis_gates, method="synthesis", approximation_degree=pass_manager_config.approximation_degree, coupling_map=pass_manager_config.coupling_map, backend_props=pass_manager_config.backend_properties, unitary_synthesis_method=pass_manager_config.unitary_synthesis_method, unitary_synthesis_plugin_config=pass_manager_config.unitary_synthesis_plugin_config, hls_config=pass_manager_config.hls_config, qubits_initially_zero=pass_manager_config.qubits_initially_zero, ) class BasicSwapPassManager(PassManagerStagePlugin): """Plugin class for routing stage with :class:`~.BasicSwap`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build routing stage PassManager.""" seed_transpiler = pass_manager_config.seed_transpiler target = pass_manager_config.target coupling_map = pass_manager_config.coupling_map backend_properties = pass_manager_config.backend_properties if target is None: routing_pass = BasicSwap(coupling_map) else: routing_pass = BasicSwap(target) vf2_call_limit, vf2_max_trials = common.get_vf2_limits( optimization_level, pass_manager_config.layout_method, pass_manager_config.initial_layout, ) if optimization_level == 0: return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 1: return common.generate_routing_passmanager( routing_pass, target, coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, check_trivial=True, use_barrier_before_measurement=True, ) if optimization_level == 2: return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 3: return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) raise TranspilerError(f"Invalid optimization level specified: {optimization_level}") class StochasticSwapPassManager(PassManagerStagePlugin): """Plugin class for routing stage with :class:`~.StochasticSwap`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build routing stage PassManager.""" seed_transpiler = pass_manager_config.seed_transpiler target = pass_manager_config.target coupling_map = pass_manager_config.coupling_map coupling_map_routing = target if coupling_map_routing is None: coupling_map_routing = coupling_map backend_properties = pass_manager_config.backend_properties vf2_call_limit, vf2_max_trials = common.get_vf2_limits( optimization_level, pass_manager_config.layout_method, pass_manager_config.initial_layout, ) if optimization_level == 3: routing_pass = StochasticSwap(coupling_map_routing, trials=200, seed=seed_transpiler) else: routing_pass = StochasticSwap(coupling_map_routing, trials=20, seed=seed_transpiler) if optimization_level == 0: return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 1: return common.generate_routing_passmanager( routing_pass, target, coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, check_trivial=True, use_barrier_before_measurement=True, ) if optimization_level in {2, 3}: return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) raise TranspilerError(f"Invalid optimization level specified: {optimization_level}") class LookaheadSwapPassManager(PassManagerStagePlugin): """Plugin class for routing stage with :class:`~.LookaheadSwap`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build routing stage PassManager.""" seed_transpiler = pass_manager_config.seed_transpiler target = pass_manager_config.target coupling_map = pass_manager_config.coupling_map coupling_map_routing = target if coupling_map_routing is None: coupling_map_routing = coupling_map backend_properties = pass_manager_config.backend_properties vf2_call_limit, vf2_max_trials = common.get_vf2_limits( optimization_level, pass_manager_config.layout_method, pass_manager_config.initial_layout, ) if optimization_level == 0: routing_pass = LookaheadSwap(coupling_map_routing, search_depth=2, search_width=2) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 1: routing_pass = LookaheadSwap(coupling_map_routing, search_depth=4, search_width=4) return common.generate_routing_passmanager( routing_pass, target, coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, check_trivial=True, use_barrier_before_measurement=True, ) if optimization_level == 2: routing_pass = LookaheadSwap(coupling_map_routing, search_depth=5, search_width=6) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 3: routing_pass = LookaheadSwap(coupling_map_routing, search_depth=5, search_width=6) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) raise TranspilerError(f"Invalid optimization level specified: {optimization_level}") class SabreSwapPassManager(PassManagerStagePlugin): """Plugin class for routing stage with :class:`~.SabreSwap`""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build routing stage PassManager.""" seed_transpiler = pass_manager_config.seed_transpiler target = pass_manager_config.target coupling_map = pass_manager_config.coupling_map coupling_map_routing = target if coupling_map_routing is None: coupling_map_routing = coupling_map backend_properties = pass_manager_config.backend_properties vf2_call_limit, vf2_max_trials = common.get_vf2_limits( optimization_level, pass_manager_config.layout_method, pass_manager_config.initial_layout, ) if optimization_level == 0: trial_count = _get_trial_count(5) routing_pass = SabreSwap( coupling_map_routing, heuristic="basic", seed=seed_transpiler, trials=trial_count, ) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 1: trial_count = _get_trial_count(5) routing_pass = SabreSwap( coupling_map_routing, heuristic="decay", seed=seed_transpiler, trials=trial_count, ) return common.generate_routing_passmanager( routing_pass, target, coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, check_trivial=True, use_barrier_before_measurement=True, ) if optimization_level == 2: trial_count = _get_trial_count(20) routing_pass = SabreSwap( coupling_map_routing, heuristic="decay", seed=seed_transpiler, trials=trial_count, ) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) if optimization_level == 3: trial_count = _get_trial_count(20) routing_pass = SabreSwap( coupling_map_routing, heuristic="decay", seed=seed_transpiler, trials=trial_count, ) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, vf2_call_limit=vf2_call_limit, vf2_max_trials=vf2_max_trials, backend_properties=backend_properties, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) raise TranspilerError(f"Invalid optimization level specified: {optimization_level}") class NoneRoutingPassManager(PassManagerStagePlugin): """Plugin class for routing stage with error on routing.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build routing stage PassManager.""" seed_transpiler = pass_manager_config.seed_transpiler target = pass_manager_config.target coupling_map = pass_manager_config.coupling_map routing_pass = Error( msg="No routing method selected, but circuit is not routed to device. " "CheckMap Error: {check_map_msg}", action="raise", ) return common.generate_routing_passmanager( routing_pass, target, coupling_map=coupling_map, seed_transpiler=seed_transpiler, use_barrier_before_measurement=True, ) class OptimizationPassManager(PassManagerStagePlugin): """Plugin class for optimization stage""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build pass manager for optimization stage.""" # Obtain the translation method required for this pass to work translation_method = pass_manager_config.translation_method or "translator" optimization = PassManager() if optimization_level != 0: plugin_manager = PassManagerStagePluginManager() _depth_check = [Depth(recurse=True), FixedPoint("depth")] _size_check = [Size(recurse=True), FixedPoint("size")] # Minimum point check for optimization level 3. _minimum_point_check = [ Depth(recurse=True), Size(recurse=True), MinimumPoint(["depth", "size"], "optimization_loop"), ] def _opt_control(property_set): return (not property_set["depth_fixed_point"]) or ( not property_set["size_fixed_point"] ) translation = plugin_manager.get_passmanager_stage( "translation", translation_method, pass_manager_config, optimization_level=optimization_level, ) if optimization_level == 1: # Steps for optimization level 1 _opt = [ Optimize1qGatesDecomposition( basis=pass_manager_config.basis_gates, target=pass_manager_config.target ), InverseCancellation( [ CXGate(), ECRGate(), CZGate(), CYGate(), XGate(), YGate(), ZGate(), HGate(), SwapGate(), (TGate(), TdgGate()), (SGate(), SdgGate()), (SXGate(), SXdgGate()), ] ), ] elif optimization_level == 2: _opt = [ Optimize1qGatesDecomposition( basis=pass_manager_config.basis_gates, target=pass_manager_config.target ), CommutativeCancellation(target=pass_manager_config.target), ] elif optimization_level == 3: # Steps for optimization level 3 _opt = [ Collect2qBlocks(), ConsolidateBlocks( basis_gates=pass_manager_config.basis_gates, target=pass_manager_config.target, approximation_degree=pass_manager_config.approximation_degree, ), UnitarySynthesis( pass_manager_config.basis_gates, approximation_degree=pass_manager_config.approximation_degree, coupling_map=pass_manager_config.coupling_map, backend_props=pass_manager_config.backend_properties, method=pass_manager_config.unitary_synthesis_method, plugin_config=pass_manager_config.unitary_synthesis_plugin_config, target=pass_manager_config.target, ), Optimize1qGatesDecomposition( basis=pass_manager_config.basis_gates, target=pass_manager_config.target ), CommutativeCancellation(target=pass_manager_config.target), ] def _opt_control(property_set): return not property_set["optimization_loop_minimum_point"] else: raise TranspilerError(f"Invalid optimization_level: {optimization_level}") unroll = translation.to_flow_controller() # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] # Check if any gate is not in the basis, and if so, run unroll passes _unroll_if_out_of_basis = [ GatesInBasis(pass_manager_config.basis_gates, target=pass_manager_config.target), ConditionalController(unroll, condition=_unroll_condition), ] if optimization_level == 3: optimization.append(_minimum_point_check) elif optimization_level == 2: optimization.append( [ Collect2qBlocks(), ConsolidateBlocks( basis_gates=pass_manager_config.basis_gates, target=pass_manager_config.target, approximation_degree=pass_manager_config.approximation_degree, ), UnitarySynthesis( pass_manager_config.basis_gates, approximation_degree=pass_manager_config.approximation_degree, coupling_map=pass_manager_config.coupling_map, backend_props=pass_manager_config.backend_properties, method=pass_manager_config.unitary_synthesis_method, plugin_config=pass_manager_config.unitary_synthesis_plugin_config, target=pass_manager_config.target, ), ] ) optimization.append(_depth_check + _size_check) else: optimization.append(_depth_check + _size_check) opt_loop = ( _opt + _unroll_if_out_of_basis + _minimum_point_check if optimization_level == 3 else _opt + _unroll_if_out_of_basis + _depth_check + _size_check ) optimization.append(DoWhileController(opt_loop, do_while=_opt_control)) return optimization else: return None class AlapSchedulingPassManager(PassManagerStagePlugin): """Plugin class for alap scheduling stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build scheduling stage PassManager""" instruction_durations = pass_manager_config.instruction_durations scheduling_method = pass_manager_config.scheduling_method timing_constraints = pass_manager_config.timing_constraints inst_map = pass_manager_config.inst_map target = pass_manager_config.target return common.generate_scheduling( instruction_durations, scheduling_method, timing_constraints, inst_map, target ) class AsapSchedulingPassManager(PassManagerStagePlugin): """Plugin class for alap scheduling stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build scheduling stage PassManager""" instruction_durations = pass_manager_config.instruction_durations scheduling_method = pass_manager_config.scheduling_method timing_constraints = pass_manager_config.timing_constraints inst_map = pass_manager_config.inst_map target = pass_manager_config.target return common.generate_scheduling( instruction_durations, scheduling_method, timing_constraints, inst_map, target ) class DefaultSchedulingPassManager(PassManagerStagePlugin): """Plugin class for alap scheduling stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: """Build scheduling stage PassManager""" instruction_durations = pass_manager_config.instruction_durations scheduling_method = None timing_constraints = pass_manager_config.timing_constraints or TimingConstraints() inst_map = pass_manager_config.inst_map target = pass_manager_config.target return common.generate_scheduling( instruction_durations, scheduling_method, timing_constraints, inst_map, target ) class DefaultLayoutPassManager(PassManagerStagePlugin): """Plugin class for default layout stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: _given_layout = SetLayout(pass_manager_config.initial_layout) def _choose_layout_condition(property_set): return not property_set["layout"] def _layout_not_perfect(property_set): """Return ``True`` if the first attempt at layout has been checked and found to be imperfect. In this case, perfection means "does not require any swap routing".""" return property_set["is_swap_mapped"] is not None and not property_set["is_swap_mapped"] def _vf2_match_not_found(property_set): # If a layout hasn't been set by the time we run vf2 layout we need to # run layout if property_set["layout"] is None: return True # if VF2 layout stopped for any reason other than solution found we need # to run layout since VF2 didn't converge. return ( property_set["VF2Layout_stop_reason"] is not None and property_set["VF2Layout_stop_reason"] is not VF2LayoutStopReason.SOLUTION_FOUND ) def _swap_mapped(property_set): return property_set["final_layout"] is None if pass_manager_config.target is None: coupling_map = pass_manager_config.coupling_map else: coupling_map = pass_manager_config.target layout = PassManager() layout.append(_given_layout) if optimization_level == 0: layout.append( ConditionalController( TrivialLayout(coupling_map), condition=_choose_layout_condition ) ) layout += common.generate_embed_passmanager(coupling_map) return layout elif optimization_level == 1: layout.append( ConditionalController( [TrivialLayout(coupling_map), CheckMap(coupling_map)], condition=_choose_layout_condition, ) ) choose_layout_1 = VF2Layout( coupling_map=pass_manager_config.coupling_map, seed=pass_manager_config.seed_transpiler, call_limit=int(5e4), # Set call limit to ~100ms with rustworkx 0.10.2 properties=pass_manager_config.backend_properties, target=pass_manager_config.target, max_trials=2500, # Limits layout scoring to < 600ms on ~400 qubit devices ) layout.append(ConditionalController(choose_layout_1, condition=_layout_not_perfect)) trial_count = _get_trial_count(5) choose_layout_2 = SabreLayout( coupling_map, max_iterations=2, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) layout.append( ConditionalController( [ BarrierBeforeFinalMeasurements( "qiskit.transpiler.internal.routing.protection.barrier" ), choose_layout_2, ], condition=_vf2_match_not_found, ) ) elif optimization_level == 2: choose_layout_0 = VF2Layout( coupling_map=pass_manager_config.coupling_map, seed=pass_manager_config.seed_transpiler, call_limit=int(5e6), # Set call limit to ~10s with rustworkx 0.10.2 properties=pass_manager_config.backend_properties, target=pass_manager_config.target, max_trials=2500, # Limits layout scoring to < 600ms on ~400 qubit devices ) layout.append( ConditionalController(choose_layout_0, condition=_choose_layout_condition) ) trial_count = _get_trial_count(20) choose_layout_1 = SabreLayout( coupling_map, max_iterations=2, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) layout.append( ConditionalController( [ BarrierBeforeFinalMeasurements( "qiskit.transpiler.internal.routing.protection.barrier" ), choose_layout_1, ], condition=_vf2_match_not_found, ) ) elif optimization_level == 3: choose_layout_0 = VF2Layout( coupling_map=pass_manager_config.coupling_map, seed=pass_manager_config.seed_transpiler, call_limit=int(3e7), # Set call limit to ~60s with rustworkx 0.10.2 properties=pass_manager_config.backend_properties, target=pass_manager_config.target, max_trials=250000, # Limits layout scoring to < 60s on ~400 qubit devices ) layout.append( ConditionalController(choose_layout_0, condition=_choose_layout_condition) ) trial_count = _get_trial_count(20) choose_layout_1 = SabreLayout( coupling_map, max_iterations=4, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) layout.append( ConditionalController( [ BarrierBeforeFinalMeasurements( "qiskit.transpiler.internal.routing.protection.barrier" ), choose_layout_1, ], condition=_vf2_match_not_found, ) ) else: raise TranspilerError(f"Invalid optimization level: {optimization_level}") embed = common.generate_embed_passmanager(coupling_map) layout.append(ConditionalController(embed.to_flow_controller(), condition=_swap_mapped)) return layout class TrivialLayoutPassManager(PassManagerStagePlugin): """Plugin class for trivial layout stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: _given_layout = SetLayout(pass_manager_config.initial_layout) def _choose_layout_condition(property_set): return not property_set["layout"] if pass_manager_config.target is None: coupling_map = pass_manager_config.coupling_map else: coupling_map = pass_manager_config.target layout = PassManager() layout.append(_given_layout) layout.append( ConditionalController(TrivialLayout(coupling_map), condition=_choose_layout_condition) ) layout += common.generate_embed_passmanager(coupling_map) return layout class DenseLayoutPassManager(PassManagerStagePlugin): """Plugin class for dense layout stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: _given_layout = SetLayout(pass_manager_config.initial_layout) def _choose_layout_condition(property_set): return not property_set["layout"] if pass_manager_config.target is None: coupling_map = pass_manager_config.coupling_map else: coupling_map = pass_manager_config.target layout = PassManager() layout.append(_given_layout) layout.append( ConditionalController( DenseLayout( coupling_map=pass_manager_config.coupling_map, backend_prop=pass_manager_config.backend_properties, target=pass_manager_config.target, ), condition=_choose_layout_condition, ) ) layout += common.generate_embed_passmanager(coupling_map) return layout class SabreLayoutPassManager(PassManagerStagePlugin): """Plugin class for sabre layout stage.""" def pass_manager(self, pass_manager_config, optimization_level=None) -> PassManager: _given_layout = SetLayout(pass_manager_config.initial_layout) def _choose_layout_condition(property_set): return not property_set["layout"] def _swap_mapped(property_set): return property_set["final_layout"] is None if pass_manager_config.target is None: coupling_map = pass_manager_config.coupling_map else: coupling_map = pass_manager_config.target layout = PassManager() layout.append(_given_layout) if optimization_level == 0: trial_count = _get_trial_count(5) layout_pass = SabreLayout( coupling_map, max_iterations=1, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) elif optimization_level == 1: trial_count = _get_trial_count(5) layout_pass = SabreLayout( coupling_map, max_iterations=2, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) elif optimization_level == 2: trial_count = _get_trial_count(20) layout_pass = SabreLayout( coupling_map, max_iterations=2, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) elif optimization_level == 3: trial_count = _get_trial_count(20) layout_pass = SabreLayout( coupling_map, max_iterations=4, seed=pass_manager_config.seed_transpiler, swap_trials=trial_count, layout_trials=trial_count, skip_routing=pass_manager_config.routing_method is not None and pass_manager_config.routing_method != "sabre", ) else: raise TranspilerError(f"Invalid optimization level: {optimization_level}") layout.append( ConditionalController( [ BarrierBeforeFinalMeasurements( "qiskit.transpiler.internal.routing.protection.barrier" ), layout_pass, ], condition=_choose_layout_condition, ) ) embed = common.generate_embed_passmanager(coupling_map) layout.append(ConditionalController(embed.to_flow_controller(), condition=_swap_mapped)) return layout def _get_trial_count(default_trials=5): if CONFIG.get("sabre_all_threads", None) or os.getenv("QISKIT_SABRE_ALL_THREADS"): return max(CPU_COUNT, default_trials) return default_trials
qiskit/qiskit/transpiler/preset_passmanagers/builtin_plugins.py/0
{ "file_path": "qiskit/qiskit/transpiler/preset_passmanagers/builtin_plugins.py", "repo_id": "qiskit", "token_count": 21003 }
210
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ .. currentmodule:: qiskit.utils.optionals Qiskit has several features that are enabled only if certain *optional* dependencies are satisfied. This module, :mod:`qiskit.utils.optionals`, has a collection of objects that can be used to test if certain functionality is available, and optionally raise :class:`.MissingOptionalLibraryError` if the functionality is not available. Available Testers ================= Qiskit Components ----------------- .. list-table:: :widths: 25 75 * - .. py:data:: HAS_AER - `Qiskit Aer <https://qiskit.github.io/qiskit-aer/>` provides high-performance simulators for the quantum circuits constructed within Qiskit. * - .. py:data:: HAS_IBMQ - The :mod:`Qiskit IBMQ Provider <qiskit.providers.ibmq>` is used for accessing IBM Quantum hardware in the IBM cloud. * - .. py:data:: HAS_IGNIS - :mod:`Qiskit Ignis <qiskit.ignis>` provides tools for quantum hardware verification, noise characterization, and error correction. * - .. py:data:: HAS_TOQM - `Qiskit TOQM <https://github.com/qiskit-toqm/qiskit-toqm>`__ provides transpiler passes for the `Time-optimal Qubit mapping algorithm <https://doi.org/10.1145/3445814.3446706>`__. External Python Libraries ------------------------- .. list-table:: :widths: 25 75 * - .. py:data:: HAS_CONSTRAINT - `python-constraint <https://github.com/python-constraint/python-constraint>`__ is a constraint satisfaction problem solver, used in the :class:`~.CSPLayout` transpiler pass. * - .. py:data:: HAS_CPLEX - The `IBM CPLEX Optimizer <https://www.ibm.com/analytics/cplex-optimizer>`__ is a high-performance mathematical programming solver for linear, mixed-integer and quadratic programming. This is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility. * - .. py:data:: HAS_CVXPY - `CVXPY <https://www.cvxpy.org/>`__ is a Python package for solving convex optimization problems. It is required for calculating diamond norms with :func:`.quantum_info.diamond_norm`. * - .. py:data:: HAS_DOCPLEX - `IBM Decision Optimization CPLEX Modelling <http://ibmdecisionoptimization.github.io/docplex-doc/>`__ is a library for prescriptive analysis. Like CPLEX, this is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility. * - .. py:data:: HAS_FIXTURES - The test suite has additional features that are available if the optional `fixtures <https://launchpad.net/python-fixtures>`__ module is installed. This generally also needs :data:`HAS_TESTTOOLS` as well. This is generally only needed for Qiskit developers. * - .. py:data:: HAS_IPYTHON - If `the IPython kernel <https://ipython.org/>`__ is available, certain additional visualizations and line magics are made available. * - .. py:data:: HAS_IPYWIDGETS - Monitoring widgets for jobs running on external backends can be provided if `ipywidgets <https://ipywidgets.readthedocs.io/en/latest/>`__ is available. * - .. py:data:: HAS_JAX - Some methods of gradient calculation within :mod:`.opflow.gradients` require `JAX <https://github.com/google/jax>`__ for autodifferentiation. * - .. py:data:: HAS_JUPYTER - Some of the tests require a complete `Jupyter <https://jupyter.org/>`__ installation to test interactivity features. * - .. py:data:: HAS_MATPLOTLIB - Qiskit provides several visualization tools in the :mod:`.visualization` module. Almost all of these are built using `Matplotlib <https://matplotlib.org/>`__, which must be installed in order to use them. * - .. py:data:: HAS_NETWORKX - No longer used by Qiskit. Internally, Qiskit now uses the high-performance `rustworkx <https://github.com/Qiskit/rustworkx>`__ library as a core dependency, and during the change-over period, it was sometimes convenient to convert things into the Python-only `NetworkX <https://networkx.org/>`__ format. Some tests of application modules, such as `Qiskit Nature <https://qiskit-community.github.io/qiskit-nature/>`__ still use NetworkX. * - .. py:data:: HAS_NLOPT - `NLopt <https://nlopt.readthedocs.io/en/latest/>`__ is a nonlinear optimization library, used by the global optimizers in the :mod:`.algorithms.optimizers` module. * - .. py:data:: HAS_PIL - PIL is a Python image-manipulation library. Qiskit actually uses the `pillow <https://pillow.readthedocs.io/en/stable/>`__ fork of PIL if it is available when generating certain visualizations, for example of both :class:`.QuantumCircuit` and :class:`.DAGCircuit` in certain modes. * - .. py:data:: HAS_PYDOT - For some graph visualizations, Qiskit uses `pydot <https://github.com/pydot/pydot>`__ as an interface to GraphViz (see :data:`HAS_GRAPHVIZ`). * - .. py:data:: HAS_PYGMENTS - Pygments is a code highlighter and formatter used by many environments that involve rich display of code blocks, including Sphinx and Jupyter. Qiskit uses this when producing rich output for these environments. * - .. py:data:: HAS_PYLATEX - Various LaTeX-based visualizations, especially the circuit drawers, need access to the `pylatexenc <https://github.com/phfaist/pylatexenc>`__ project to work correctly. * - .. py:data:: HAS_QASM3_IMPORT - The functions :func:`.qasm3.load` and :func:`.qasm3.loads` for importing OpenQASM 3 programs into :class:`.QuantumCircuit` instances use `an external importer package <https://qiskit.github.io/qiskit-qasm3-import>`__. * - .. py:data:: HAS_SEABORN - Qiskit provides several visualization tools in the :mod:`.visualization` module. Some of these are built using `Seaborn <https://seaborn.pydata.org/>`__, which must be installed in order to use them. * - .. py:data:: HAS_SKLEARN - Some of the gradient functions in :mod:`.opflow.gradients` use regularisation methods from `Scikit Learn <https://scikit-learn.org/stable/>`__. * - .. py:data:: HAS_SKQUANT - Some of the optimisers in :mod:`.algorithms.optimizers` are based on those found in `Scikit Quant <https://github.com/scikit-quant/scikit-quant>`__, which must be installed to use them. * - .. py:data:: HAS_SQSNOBFIT - `SQSnobFit <https://pypi.org/project/SQSnobFit/>`__ is a library for the "stable noisy optimization by branch and fit" algorithm. It is used by the :class:`.SNOBFIT` optimizer. * - .. py:data:: HAS_SYMENGINE - `Symengine <https://github.com/symengine/symengine>`__ is a fast C++ backend for the symbolic-manipulation library `Sympy <https://www.sympy.org/en/index.html>`__. Qiskit uses special methods from Symengine to accelerate its handling of :class:`~.circuit.Parameter`\\ s if available. * - .. py:data:: HAS_TESTTOOLS - Qiskit's test suite has more advanced functionality available if the optional `testtools <https://pypi.org/project/testtools/>`__ library is installed. This is generally only needed for Qiskit developers. * - .. py:data:: HAS_TWEEDLEDUM - `Tweedledum <https://github.com/boschmitt/tweedledum>`__ is an extension library for synthesis and optimization of circuits that may involve classical oracles. Qiskit's :class:`.PhaseOracle` uses this, which is used in turn by amplification algorithms via the :class:`.AmplificationProblem`. * - .. py:data:: HAS_Z3 - `Z3 <https://github.com/Z3Prover/z3>`__ is a theorem prover, used in the :class:`.CrosstalkAdaptiveSchedule` and :class:`.HoareOptimizer` transpiler passes. External Command-Line Tools --------------------------- .. list-table:: :widths: 25 75 * - .. py:data:: HAS_GRAPHVIZ - For some graph visualizations, Qiskit uses the `GraphViz <https://graphviz.org/>`__ visualization tool via its ``pydot`` interface (see :data:`HAS_PYDOT`). * - .. py:data:: HAS_PDFLATEX - Visualization tools that use LaTeX in their output, such as the circuit drawers, require ``pdflatex`` to be available. You will generally need to ensure that you have a working LaTeX installation available, and the ``qcircuit.tex`` package. * - .. py:data:: HAS_PDFTOCAIRO - Visualization tools that convert LaTeX-generated files into rasterized images use the ``pdftocairo`` tool. This is part of the `Poppler suite of PDF tools <https://poppler.freedesktop.org/>`__. Lazy Checker Classes ==================== .. currentmodule:: qiskit.utils Each of the lazy checkers is an instance of :class:`.LazyDependencyManager` in one of its two subclasses: :class:`.LazyImportTester` and :class:`.LazySubprocessTester`. These should be imported from :mod:`.utils` directly if required, such as:: from qiskit.utils import LazyImportTester .. autoclass:: qiskit.utils.LazyDependencyManager :members: .. autoclass:: qiskit.utils.LazyImportTester .. autoclass:: qiskit.utils.LazySubprocessTester """ # NOTE: If you're changing this file, sync it with `requirements-optional.txt` and potentially # `pyproject.toml` as well. import logging as _logging from .lazy_tester import ( LazyImportTester as _LazyImportTester, LazySubprocessTester as _LazySubprocessTester, ) _logger = _logging.getLogger(__name__) HAS_AER = _LazyImportTester( "qiskit_aer", name="Qiskit Aer", install="pip install qiskit-aer", ) HAS_IBMQ = _LazyImportTester( "qiskit.providers.ibmq", name="IBMQ Provider", install="pip install qiskit-ibmq-provider", ) HAS_IGNIS = _LazyImportTester( "qiskit.ignis", name="Qiskit Ignis", install="pip install qiskit-ignis", ) HAS_TOQM = _LazyImportTester("qiskit_toqm", name="Qiskit TOQM", install="pip install qiskit-toqm") HAS_CONSTRAINT = _LazyImportTester( "constraint", name="python-constraint", install="pip install python-constraint", ) HAS_CPLEX = _LazyImportTester( "cplex", install="pip install cplex", msg="This may not be possible for all Python versions and OSes", ) HAS_CVXPY = _LazyImportTester("cvxpy", install="pip install cvxpy") HAS_DOCPLEX = _LazyImportTester( {"docplex": (), "docplex.mp.model": ("Model",)}, install="pip install docplex", msg="This may not be possible for all Python versions and OSes", ) HAS_FIXTURES = _LazyImportTester("fixtures", install="pip install fixtures") HAS_IPYTHON = _LazyImportTester("IPython", install="pip install ipython") HAS_IPYWIDGETS = _LazyImportTester("ipywidgets", install="pip install ipywidgets") HAS_JAX = _LazyImportTester( {"jax": ("grad", "jit"), "jax.numpy": ()}, name="jax", install="pip install jax", ) HAS_JUPYTER = _LazyImportTester(["jupyter", "nbformat", "nbconvert"], install="pip install jupyter") HAS_MATPLOTLIB = _LazyImportTester( ("matplotlib.patches", "matplotlib.pyplot"), name="matplotlib", install="pip install matplotlib", ) HAS_NETWORKX = _LazyImportTester("networkx", install="pip install networkx") HAS_NLOPT = _LazyImportTester("nlopt", name="NLopt Optimizer", install="pip install nlopt") HAS_PIL = _LazyImportTester("PIL.Image", name="pillow", install="pip install pillow") HAS_PYDOT = _LazyImportTester("pydot", install="pip install pydot") HAS_PYGMENTS = _LazyImportTester("pygments", install="pip install pygments") HAS_PYLATEX = _LazyImportTester( { "pylatexenc.latex2text": ("LatexNodes2Text",), "pylatexenc.latexencode": ("utf8tolatex",), }, name="pylatexenc", install="pip install pylatexenc", ) HAS_QASM3_IMPORT = _LazyImportTester( "qiskit_qasm3_import", install="pip install qiskit_qasm3_import" ) HAS_SEABORN = _LazyImportTester("seaborn", install="pip install seaborn") HAS_SKLEARN = _LazyImportTester( {"sklearn.linear_model": ("Ridge", "Lasso")}, name="scikit-learn", install="pip install scikit-learn", ) HAS_SKQUANT = _LazyImportTester( "skquant.opt", name="scikit-quant", install="pip install scikit-quant", ) HAS_SQSNOBFIT = _LazyImportTester("SQSnobFit", install="pip install SQSnobFit") HAS_SYMENGINE = _LazyImportTester("symengine", install="pip install symengine") HAS_TESTTOOLS = _LazyImportTester("testtools", install="pip install testtools") HAS_TWEEDLEDUM = _LazyImportTester("tweedledum", install="pip install tweedledum") HAS_Z3 = _LazyImportTester("z3", install="pip install z3-solver") HAS_GRAPHVIZ = _LazySubprocessTester( ("dot", "-V"), name="Graphviz", msg=( "To install, follow the instructions at https://graphviz.org/download/." " Qiskit needs the Graphviz binaries, which the 'graphviz' package on pip does not install." " You must install the actual Graphviz software" ), ) HAS_PDFLATEX = _LazySubprocessTester( ("pdflatex", "-version"), msg="You will likely need to install a full LaTeX distribution for your system", ) HAS_PDFTOCAIRO = _LazySubprocessTester( ("pdftocairo", "-v"), msg="This is part of the 'poppler' set of PDF utilities", )
qiskit/qiskit/utils/optionals.py/0
{ "file_path": "qiskit/qiskit/utils/optionals.py", "repo_id": "qiskit", "token_count": 5113 }
211
{ "name": "iqx-dark", "textcolor": "#FFFFFF", "gatetextcolor": "#FFFFFF", "subtextcolor": "#FFFFFF", "linecolor": "#FFFFFF", "creglinecolor": "#778899", "gatefacecolor": "#FF7EB6", "barrierfacecolor": "#8D8D8D", "backgroundcolor": "#262626", "edgecolor": null, "fontsize": 13, "subfontsize": 8, "showindex": false, "figwidth": -1, "dpi": 150, "margin": [ 2.0, 0.1, 0.1, 0.3 ], "creglinestyle": "doublet", "displaytext": { "u1": "U_1", "u2": "U_2", "u3": "U_3", "id": "I", "sdg": "S^\\dagger", "sx": "\\sqrt{X}", "sxdg": "\\sqrt{X}^\\dagger", "tdg": "T^\\dagger", "ms": "MS", "rx": "R_X", "ry": "R_Y", "rz": "R_Z", "rxx": "R_{XX}", "ryy": "R_{YY}", "rzx": "R_{ZX}", "rzz": "ZZ", "reset": "\\left|0\\right\\rangle", "initialize": "$|\\psi\\rangle$" }, "displaycolor": { "u1": [ "#BAE6FF", "#000000" ], "u2": [ "#FF7EB6", "#000000" ], "u3": [ "#FF7EB6", "#000000" ], "u": [ "#FF7EB6", "#000000" ], "p": [ "#BAE6FF", "#000000" ], "id": [ "#4589FF", "#000000" ], "x": [ "#4589FF", "#000000" ], "y": [ "#FF7EB6", "#000000" ], "z": [ "#BAE6FF", "#000000" ], "h": [ "#FA4D56", "#000000" ], "cx": [ "#4589FF", "#000000" ], "ccx": [ "#4589FF", "#000000" ], "mcx": [ "#4589FF", "#000000" ], "mcx_gray": [ "#4589FF", "#000000" ], "cy": [ "#FF7EB6", "#000000" ], "cz": [ "#BAE6FF", "#000000" ], "cp": [ "#BAE6FF", "#000000" ], "mcphase": [ "#BAE6FF", "#000000" ], "swap": [ "#4589FF", "#000000" ], "cswap": [ "#4589FF", "#000000" ], "ccswap": [ "#4589FF", "#000000" ], "dcx": [ "#4589FF", "#000000" ], "cdcx": [ "#4589FF", "#000000" ], "ccdcx": [ "#4589FF", "#000000" ], "iswap": [ "#FF7EB6", "#000000" ], "s": [ "#BAE6FF", "#000000" ], "sdg": [ "#BAE6FF", "#000000" ], "t": [ "#BAE6FF", "#000000" ], "tdg": [ "#BAE6FF", "#000000" ], "sx": [ "#FF7EB6", "#000000" ], "sxdg": [ "#FF7EB6", "#000000" ], "r": [ "#FF7EB6", "#000000" ], "rx": [ "#FF7EB6", "#000000" ], "ry": [ "#FF7EB6", "#000000" ], "rz": [ "#BAE6FF", "#000000" ], "rxx": [ "#FF7EB6", "#000000" ], "ryy": [ "#FF7EB6", "#000000" ], "rzx": [ "#FF7EB6", "#000000" ], "rzz": [ "#BAE6FF", "#000000" ], "reset": [ "#8D8D8D", "#000000" ], "target": [ "#262626", "#262626" ], "measure": [ "#8D8D8D", "#000000" ] } }
qiskit/qiskit/visualization/circuit/styles/iqp-dark.json/0
{ "file_path": "qiskit/qiskit/visualization/circuit/styles/iqp-dark.json", "repo_id": "qiskit", "token_count": 2910 }
212
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Customizable object generators for pulse drawer. """ from qiskit.visualization.pulse_v2.generators.barrier import gen_barrier from qiskit.visualization.pulse_v2.generators.chart import ( gen_baseline, gen_channel_freqs, gen_chart_name, gen_chart_scale, ) from qiskit.visualization.pulse_v2.generators.frame import ( gen_formatted_frame_values, gen_formatted_freq_mhz, gen_formatted_phase, gen_frame_symbol, gen_raw_operand_values_compact, ) from qiskit.visualization.pulse_v2.generators.snapshot import gen_snapshot_name, gen_snapshot_symbol from qiskit.visualization.pulse_v2.generators.waveform import ( gen_filled_waveform_stepwise, gen_ibmq_latex_waveform_name, gen_waveform_max_value, )
qiskit/qiskit/visualization/pulse_v2/generators/__init__.py/0
{ "file_path": "qiskit/qiskit/visualization/pulse_v2/generators/__init__.py", "repo_id": "qiskit", "token_count": 428 }
213
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Drawing objects for timeline drawer. Drawing objects play two important roles: - Allowing unittests of visualization module. Usually it is hard for image files to be tested. - Removing program parser from each plotter interface. We can easily add new plotter. This module is based on the structure of matplotlib as it is the primary plotter of the timeline drawer. However this interface is agnostic to the actual plotter. Design concept ~~~~~~~~~~~~~~ When we think about dynamically updating drawings, it will be most efficient to update only the changed properties of drawings rather than regenerating entirely from scratch. Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates all possible drawings in the beginning and then the canvas instance manages visibility of each drawing according to the end-user request. Data key ~~~~~~~~ In the abstract class ``ElementaryData`` common attributes to represent a drawing are specified. In addition, drawings have the `data_key` property that returns an unique hash of the object for comparison. This key is generated from a data type, the location of the drawing in the canvas, and associated qubit or classical bit objects. See py:mod:`qiskit.visualization.timeline.types` for detail on the data type. If a data key cannot distinguish two independent objects, you need to add a new data type. The data key may be used in the plotter interface to identify the object. Drawing objects ~~~~~~~~~~~~~~~ To support not only `matplotlib` but also multiple plotters, those drawings should be universal and designed without strong dependency on modules in `matplotlib`. This means drawings that represent primitive geometries are preferred. It should be noted that there will be no unittest for each plotter API, which takes drawings and outputs image data, we should avoid adding a complicated geometry that has a context of the scheduled circuit program. For example, a two qubit scheduled gate may be drawn by two rectangles that represent time occupation of two quantum registers during the gate along with a line connecting these rectangles to identify the pair. This shape can be represented with two box-type objects with one line-type object instead of defining a new object dedicated to the two qubit gate. As many plotters don't support an API that visualizes such a linked-box shape, if we introduce such complex drawings and write a custom wrapper function on top of the existing API, it could be difficult to prevent bugs with the CI tools due to lack of the effective unittest for image data. Link between gates ~~~~~~~~~~~~~~~~~~ The ``GateLinkData`` is the special subclass of drawing that represents a link between bits. Usually objects are associated to the specific bit, but ``GateLinkData`` can be associated with multiple bits to illustrate relationship between quantum or classical bits during a gate operation. """ from abc import ABC from enum import Enum from typing import Optional, Dict, Any, List, Union import numpy as np from qiskit import circuit from qiskit.visualization.timeline import types from qiskit.visualization.exceptions import VisualizationError class ElementaryData(ABC): """Base class of the scheduled circuit visualization object. Note that drawings are mutable. """ __hash__ = None def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bits: Optional[Union[types.Bits, List[types.Bits]]] = None, meta: Optional[Dict[str, Any]] = None, styles: Optional[Dict[str, Any]] = None, ): """Create new drawing. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bits: Qubit or Clbit object bound to this drawing. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)): bits = [bits] if isinstance(data_type, Enum): data_type = data_type.value self.data_type = str(data_type) self.xvals = xvals self.yvals = yvals self.bits = bits self.meta = meta self.styles = styles @property def data_key(self): """Return unique hash of this object.""" return str( hash( ( self.__class__.__name__, self.data_type, tuple(self.bits), tuple(self.xvals), tuple(self.yvals), ) ) ) def __repr__(self): return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})" def __eq__(self, other): return isinstance(other, self.__class__) and self.data_key == other.data_key class LineData(ElementaryData): """Drawing object that represents line shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new line. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class BoxData(ElementaryData): """Drawing object that represents box shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new box. Args: data_type: String representation of this drawing. xvals: Left and right coordinate that the object is drawn. yvals: Top and bottom coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. Raises: VisualizationError: When number of data points are not equals to 2. """ if len(xvals) != 2 or len(yvals) != 2: raise VisualizationError("Length of data points are not equals to 2.") super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class TextData(ElementaryData): """Drawing object that represents a text on canvas.""" def __init__( self, data_type: Union[str, Enum], xval: types.Coordinate, yval: types.Coordinate, bit: types.Bits, text: str, latex: Optional[str] = None, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new text. Args: data_type: String representation of this drawing. xval: Horizontal coordinate that the object is drawn. yval: Vertical coordinate that the object is drawn. bit: Bit associated to this object. text: A string to draw on the canvas. latex: If set this string is used instead of `text`. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ self.text = text self.latex = latex super().__init__( data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles ) class GateLinkData(ElementaryData): """A special drawing data type that represents bit link of multi-bit gates. Note this object takes multiple bits and dedicates them to the bit link. This may appear as a line on the canvas. """ def __init__( self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None ): """Create new bit link. Args: xval: Horizontal coordinate that the object is drawn. bits: Bit associated to this object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=types.LineType.GATE_LINK, xvals=[xval], yvals=[0], bits=bits, meta=None, styles=styles, )
qiskit/qiskit/visualization/timeline/drawings.py/0
{ "file_path": "qiskit/qiskit/visualization/timeline/drawings.py", "repo_id": "qiskit", "token_count": 3561 }
214
--- features: - | Introduced new methods in ``QuantumCircuit`` which allows the seamless adding or removing of measurements at the end of a circuit. ``measure_all()`` Adds a ``barrier`` followed by a ``measure`` operation to all qubits in the circuit. Creates a ``ClassicalRegister`` of size equal to the number of qubits in the circuit, which store the measurements. ``measure_active()`` Adds a ``barrier`` followed by a ``measure`` operation to all active qubits in the circuit. A qubit is active if it has at least one other operation acting upon it. Creates a ``ClassicalRegister`` of size equal to the number of active qubits in the circuit, which store the measurements. ``remove_final_measurements()`` Removes all final measurements and preceeding ``barrier`` from a circuit. A measurement is considered "final" if it is not followed by any other operation, excluding barriers and other measurements. After the measurements are removed, if all of the classical bits in the ``ClassicalRegister`` are idle (have no operations attached to them), then the ``ClassicalRegister`` is removed. Examples:: # Using measure_all() circuit = QuantumCircuit(2) circuit.h(0) circuit.measure_all() circuit.draw() # A ClassicalRegister with prefix measure was created. # It has 2 clbits because there are 2 qubits to measure β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” q_0: |0>─ H β”œβ”€β–‘β”€β”€Mβ”œβ”€β”€β”€ β””β”€β”€β”€β”˜ β–‘ β””β•₯β”˜β”Œβ”€β” q_1: |0>──────░──╫──Mβ”œ β–‘ β•‘ β””β•₯β”˜ measure_0: 0 ═════════╩══╬═ β•‘ measure_1: 0 ════════════╩═ # Using measure_active() circuit = QuantumCircuit(2) circuit.h(0) circuit.measure_active() circuit.draw() # This ClassicalRegister only has 1 clbit because only 1 qubit is active β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” q_0: |0>─ H β”œβ”€β–‘β”€β”€Mβ”œ β””β”€β”€β”€β”˜ β–‘ β””β•₯β”˜ q_1: |0>──────░──╫─ β–‘ β•‘ measure_0: 0 ═════════╩═ # Using remove_final_measurements() # Assuming circuit_all and circuit_active are the circuits from the measure_all and # measure_active examples above respectively circuit_all.remove_final_measurements() circuit_all.draw() # The ClassicalRegister is removed because, after the measurements were removed, # all of its clbits were idle β”Œβ”€β”€β”€β” q_0: |0>─ H β”œ β””β”€β”€β”€β”˜ q_1: |0>───── circuit_active.remove_final_measurements() circuit_active.draw() # This will result in the same circuit β”Œβ”€β”€β”€β” q_0: |0>─ H β”œ β””β”€β”€β”€β”˜ q_1: |0>─────
qiskit/releasenotes/notes/0.10/add-methods-to-add-and-remove-final-measurements-bcdd9977eacf8380.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.10/add-methods-to-add-and-remove-final-measurements-bcdd9977eacf8380.yaml", "repo_id": "qiskit", "token_count": 1441 }
215
--- features: - | Introduced a new pulse command ``Delay`` which may be inserted into a pulse ``Schedule``. This command accepts a ``duration`` and may be added to any ``Channel``. Other commands may not be scheduled on a channel during a delay. The delay can be added just like any other pulse command. For example:: from qiskit import pulse from qiskit.pulse.utils import pad dc0 = pulse.DriveChannel(0) delay = pulse.Delay(1) test_pulse = pulse.SamplePulse([1.0]) sched = pulse.Schedule() sched += test_pulse(dc0).shift(1) # build padded schedule by hand ref_sched = delay(dc0) | sched # pad schedule padded_sched = pad(sched) assert padded_sched == ref_sched One may also pass additional channels to be padded and a time to pad until, for example:: from qiskit import pulse from qiskit.pulse.utils import pad dc0 = pulse.DriveChannel(0) dc1 = pulse.DriveChannel(1) delay = pulse.Delay(1) test_pulse = pulse.SamplePulse([1.0]) sched = pulse.Schedule() sched += test_pulse(dc0).shift(1) # build padded schedule by hand ref_sched = delay(dc0) | delay(dc1) | sched # pad schedule across both channels until up until the first time step padded_sched = pad(sched, channels=[dc0, dc1], until=1) assert padded_sched == ref_sched
qiskit/releasenotes/notes/0.10/schedule-pad-method-a56c952fcfdfbf08.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.10/schedule-pad-method-a56c952fcfdfbf08.yaml", "repo_id": "qiskit", "token_count": 533 }
216
--- features: - | ``PulseDefaults`` (accessed normally as ``backend.defaults()``) has an attribute, ``circuit_instruction_map`` which has the methods of CmdDef. The new `circuit_instruction_map` is an ``InstructionScheduleMap`` object with three new functions beyond what CmdDef had: * qubit_instructions(qubits) returns the operations defined for the qubits * assert_has(instruction, qubits) raises an error if the op isn't defined * remove(instruction, qubits) like pop, but doesn't require parameters There are some differences from the CmdDef: * ``__init__`` takes no arguments * ``cmds`` and ``cmd_qubits`` are deprecated and replaced with ``instructions`` and ``qubits_with_instruction`` Example:: backend = provider.get_backend(backend_name) inst_map = backend.defaults().circuit_instruction_map qubit = inst_map.qubits_with_instruction('u3')[0] x_gate = inst_map.get('u3', qubit, P0=np.pi, P1=0, P2=np.pi) pulse_schedule = x_gate(DriveChannel(qubit)) upgrade: - | In PulseDefaults (accessed normally as backend.defaults()), ``qubit_freq_est`` and ``meas_freq_est`` are now returned in Hz rather than GHz. This means the new return values are 1e9 * their previous value.
qiskit/releasenotes/notes/0.11/extend-backend-defaults-4370f983d599a26b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/extend-backend-defaults-4370f983d599a26b.yaml", "repo_id": "qiskit", "token_count": 468 }
217
--- upgrade: - | The previously deprecated gate ``U0Gate``, which was deprecated in the 0.9 release, has been removed. The gate ``IdGate`` should be used instead to insert delays.
qiskit/releasenotes/notes/0.11/remove_u0-6514a8ddcf51f609.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/remove_u0-6514a8ddcf51f609.yaml", "repo_id": "qiskit", "token_count": 60 }
218
--- features: - | The :class:`qiskit.circuit.QuantumCircuit` methods :meth:`qiskit.circuit.QuantumCircuit.measure_active`, :meth:`qiskit.circuit.QuantumCircuit.measure_all`, and :meth:`qiskit.circuit.QuantumCircuit.remove_final_measurements` now have an addition kwarg ``inplace``. When ``inplace`` is set to ``False`` the function will return a modified **copy** of the circuit. This is different from the default behavior which will modify the circuit object in-place and return nothing.
qiskit/releasenotes/notes/0.12/copy-measure-methods-562f0c1096f93145.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/copy-measure-methods-562f0c1096f93145.yaml", "repo_id": "qiskit", "token_count": 185 }
219
--- deprecations: - | The ``scaling`` parameter of the ``draw()`` method for the ``Schedule`` and ``Pulse`` objects was deprecated and will be removed in a future release. Instead the new ``scale`` parameter should be used. This was done to have a consistent argument between pulse and circuit drawings. For example:: #The consistency in parameters is seen below #For circuits circuit = QuantumCircuit() circuit.draw(scale=0.2) #For pulses pulse = SamplePulse() pulse.draw(scale=0.2) #For schedules schedule = Schedule() schedule.draw(scale=0.2)
qiskit/releasenotes/notes/0.12/update-scaling-draw-option-7f28e83ff3e3939f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/update-scaling-draw-option-7f28e83ff3e3939f.yaml", "repo_id": "qiskit", "token_count": 234 }
220
--- features: - | A new method :meth:`~qiskit.dagcircuit.DAGCircuit.compose` has been added to the :class:`~qiskit.dagcircuit.DAGCircuit` class for composing two circuits via their DAGs. .. code-block:: python dag_left.compose(dag_right, edge_map={right_qubit0: self.left_qubit1, right_qubit1: self.left_qubit4, right_clbit0: self.left_clbit1, right_clbit1: self.left_clbit0}) .. parsed-literal:: β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β” lqr_1_0: ──── H β”œβ”€β”€β”€ rqr_0: ──■─── Tdg β”œβ”€Mβ”œ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”¬β”€β”¬β”€β”˜β””β•₯β”˜ lqr_1_1: ──── X β”œβ”€β”€β”€ rqr_1: ─ X β”œβ”€β”€β”€Mβ”œβ”€β”€β”€β•«β”€ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”€β”€β”˜ β””β•₯β”˜ β•‘ lqr_1_2: ─ U1(0.1) β”œ + rcr_0: ════════╬════╩═ = β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ lqr_2_0: ─────■───── rcr_1: ════════╩══════ β”Œβ”€β”΄β”€β” lqr_2_1: ──── X β”œβ”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: ═══════════ lcr_1: ═══════════ β”Œβ”€β”€β”€β” lqr_1_0: ──── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β” lqr_1_1: ──── X β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€ Tdg β”œβ”€Mβ”œ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β””β”€β”€β”€β”€β”€β”˜β””β•₯β”˜ lqr_1_2: ─ U1(0.1) β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β•‘ lqr_2_0: ─────■───────┼──────────╫─ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β”Œβ”€β” β•‘ lqr_2_1: ──── X β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€Mβ”œβ”€β”€β”€β•«β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β•₯β”˜ β•‘ lcr_0: ═══════════════════╩════╬═ β•‘ lcr_1: ════════════════════════╩═ deprecations: - | The ``DAGCircuit.compose_back()`` and ``DAGCircuit.extend_back()`` methods are deprecated and will be removed in a future release. Instead you should use the :meth:`qiskit.dagcircuit.DAGCircuit.compose` method, which is a more general and more flexible method that provides the same functionality.
qiskit/releasenotes/notes/0.13/dag_compose-3847f210c6624f88.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/dag_compose-3847f210c6624f88.yaml", "repo_id": "qiskit", "token_count": 1473 }
221
--- features: - | Adds the ability to set ``qargs`` to objects which are subclasses of the abstract ``BaseOperator`` class. This is done by calling the object ``op(qargs)`` (where ``op`` is an operator class) and will return a shallow copy of the original object with a qargs property set. When such an object is used with the :meth:`~qiskit.quantum_info.Operator.compose` or :meth:`~qiskit.quantum_info.Operator.dot` methods the internal value for qargs will be used when the ``qargs`` method kwarg is not used. This allows for subsystem composition using binary operators, for example:: from qiskit.quantum_info import Operator init = Operator.from_label('III') x = Operator.from_label('X') h = Operator.from_label('H') init @ x([0]) @ h([1])
qiskit/releasenotes/notes/0.13/operator-qargs-aeb2254b5a643013.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/operator-qargs-aeb2254b5a643013.yaml", "repo_id": "qiskit", "token_count": 289 }
222
--- features: - | There has been a significant simplification to the style in which Pulse instructions are built. With the previous style, ``Command`` s were called with channels to make an :py:class:`~qiskit.pulse.instructions.Instruction`. The usage of both commands and instructions was a point of confusion. This was the previous style:: sched += Delay(5)(DriveChannel(0)) sched += ShiftPhase(np.pi)(DriveChannel(0)) sched += SamplePulse([1.0, ...])(DriveChannel(0)) sched += Acquire(100)(AcquireChannel(0), MemorySlot(0)) or, equivalently (though less used):: sched += DelayInstruction(Delay(5), DriveChannel(0)) sched += ShiftPhaseInstruction(ShiftPhase(np.pi), DriveChannel(0)) sched += PulseInstruction(SamplePulse([1.0, ...]), DriveChannel(0)) sched += AcquireInstruction(Acquire(100), AcquireChannel(0), MemorySlot(0)) Now, rather than build a command *and* an instruction, each command has been migrated into an instruction:: sched += Delay(5, DriveChannel(0)) sched += ShiftPhase(np.pi, DriveChannel(0)) sched += Play(SamplePulse([1.0, ...]), DriveChannel(0)) sched += SetFrequency(5.5, DriveChannel(0)) # New instruction! sched += Acquire(100, AcquireChannel(0), MemorySlot(0)) - | There is now a :py:class:`~qiskit.pulse.instructions.Play` instruction which takes a description of a pulse envelope and a channel. There is a new :py:class:`~qiskit.pulse.pulse_lib.Pulse` class in the :mod:`~qiskit.pulse.pulse_lib` from which the pulse envelope description should subclass. For example:: Play(SamplePulse([0.1]*10), DriveChannel(0)) Play(ConstantPulse(duration=10, amp=0.1), DriveChannel(0)) deprecations: - | :py:class:`~qiskit.pulse.pulse_lib.SamplePulse` and :py:class:`~qiskit.pulse.pulse_lib.ParametricPulse` s (e.g. ``Gaussian``) now subclass from :py:class:`~qiskit.pulse.pulse_lib.Pulse` and have been moved to the :mod:`qiskit.pulse.pulse_lib`. The previous path via ``pulse.commands`` is deprecated and will be removed in a future release. - | ``DelayInstruction`` has been deprecated and replaced by :py:class:`~qiskit.pulse.instruction.Delay`. This new instruction has been taken over the previous ``Command`` ``Delay``. The migration pattern is:: Delay(<duration>)(<channel>) -> Delay(<duration>, <channel>) DelayInstruction(Delay(<duration>), <channel>) -> Delay(<duration>, <channel>) Until the deprecation period is over, the previous ``Delay`` syntax of calling a command on a channel will also be supported:: Delay(<phase>)(<channel>) The new ``Delay`` instruction does not support a ``command`` attribute. - | ``FrameChange`` and ``FrameChangeInstruction`` have been deprecated and replaced by :py:class:`~qiskit.pulse.instructions.ShiftPhase`. The changes are:: FrameChange(<phase>)(<channel>) -> ShiftPhase(<phase>, <channel>) FrameChangeInstruction(FrameChange(<phase>), <channel>) -> ShiftPhase(<phase>, <channel>) Until the deprecation period is over, the previous FrameChange syntax of calling a command on a channel will be supported:: ShiftPhase(<phase>)(<channel>) - | The ``call`` method of :py:class:`~qiskit.pulse.pulse_lib.SamplePulse` and :py:class:`~qiskit.pulse.pulse_lib.ParametricPulse` s have been deprecated. The migration is as follows:: Pulse(<*args>)(<channel>) -> Play(Pulse(*args), <channel>) - | ``AcquireInstruction`` has been deprecated and replaced by :py:class:`~qiskit.pulse.instructions.Acquire`. The changes are:: Acquire(<duration>)(<**channels>) -> Acquire(<duration>, <**channels>) AcquireInstruction(Acquire(<duration>), <**channels>) -> Acquire(<duration>, <**channels>) Until the deprecation period is over, the previous Acquire syntax of calling the command on a channel will be supported:: Acquire(<duration>)(<**channels>)
qiskit/releasenotes/notes/0.13/unify-instructions-and-commands-aaa6d8724b8a29d3.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/unify-instructions-and-commands-aaa6d8724b8a29d3.yaml", "repo_id": "qiskit", "token_count": 1535 }
223
--- features: - | The circuit library module :mod:`qiskit.circuit.library` now provides a new boolean logic AND circuit, :class:`qiskit.circuit.library.AND`, and OR circuit, :class:`qiskit.circuit.library.OR`, which implement the respective operations on a variable number of provided qubits. deprecations: - | The ``AND`` and ``OR`` methods of :class:`qiskit.circuit.QuantumCircuit` are deprecated and will be removed in a future release. Instead you should use the circuit library boolean logic classes :class:`qiskit.circuit.library.AND` amd :class:`qiskit.circuit.library.OR` and then append those objects to your class. For example:: from qiskit import QuantumCircuit from qiskit.circuit.library import AND qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc_and = AND(2) qc.compose(qc_and, inplace=True)
qiskit/releasenotes/notes/0.14/logical-and-or-circuits-edcffef0b4b8ee62.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.14/logical-and-or-circuits-edcffef0b4b8ee62.yaml", "repo_id": "qiskit", "token_count": 330 }
224
--- features: - | A new ``translation_method`` keyword argument has been added to :func:`~qiskit.compiler.transpile` to allow selection of the method to be used for translating circuits to the available device gates. For example, ``transpile(circ, backend, translation_method='translator')``. Valid choices are: * ``'unroller'``: to use the :class:`~qiskit.transpiler.passes.Unroller` pass * ``'translator'``: to use the :class:`~qiskit.transpiler.passes.BasisTranslator` pass. * ``'synthesis'``: to use the :class:`~qiskit.transpiler.passes.UnitarySynthesis` pass. The default value is ``'translator'``. upgrade: - | By default the preset passmanagers in :mod:`qiskit.transpiler.preset_passmanagers` are using :class:`~qiskit.transpiler.passes.UnrollCustomDefinitions` and :class:`~qiskit.transpiler.passes.BasisTranslator` to handle basis changing instead of the previous default :class:`~qiskit.transpiler.passes.Unroller`. This was done because the new passes are more flexible and allow targeting any basis set, however the output may differ. To use the previous default you can set the ``translation_method`` kwarg on :func:`~qiskit.compiler.transpile` to ``'unroller'``.
qiskit/releasenotes/notes/0.15/add-basistranslator-to-default-levels-1c0de250f8ca4a59.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/add-basistranslator-to-default-levels-1c0de250f8ca4a59.yaml", "repo_id": "qiskit", "token_count": 458 }
225
--- features: - | A new class, :class:`~qiskit.test.mock.utils.ConfigurableFakeBackend`, has been added to the :mod:`qiskit.test.mock.utils` module. This new class enables the creation of configurable mock backends for use in testing. For example:: from qiskit.test.mock.utils import ConfigurableFakeBackend backend = ConfigurableFakeBackend("Tashkent", n_qubits=100, version="0.0.1", basis_gates=['u1'], qubit_t1=99., qubit_t2=146., qubit_frequency=5., qubit_readout_error=0.01, single_qubit_gates=['u1']) will create a backend object with 100 qubits and all the other parameters specified in the constructor.
qiskit/releasenotes/notes/0.15/configurable-backend-af0623b43bdcc35e.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/configurable-backend-af0623b43bdcc35e.yaml", "repo_id": "qiskit", "token_count": 575 }
226
--- upgrade: - | The deprecated kwarg ``line_length`` for the :func:`qiskit.visualization.circuit_drawer` function and :meth:`qiskit.circuit.QuantumCircuit.draw` method has been removed. It had been deprecated since the 0.10.0 release. Instead you can use the ``fold`` kwarg to adjust the width of the circuit diagram.
qiskit/releasenotes/notes/0.15/line_length_remove_0.10-d13e5a15524e67c0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/line_length_remove_0.10-d13e5a15524e67c0.yaml", "repo_id": "qiskit", "token_count": 118 }
227
--- upgrade: - | All classes and function in the ``qiskit.tool.qi`` module were deprecated in the 0.12.0 release and have now been removed. Instead use the :mod:`qiskit.quantum_info` module and the new methods and classes that it has for working with quantum states and operators. - | The ``qiskit.quantum_info.basis_state`` and ``qiskit.quantum_info.projector`` functions are deprecated as of Qiskit Terra 0.12.0 as are now removed. Use the :class:`qiskit.quantum_info.QuantumState` and its derivatives :class:`qiskit.quantum_info.Statevector` and :class:`qiskit.quantum_info.DensityMatrix` to work with states.
qiskit/releasenotes/notes/0.15/remove-deprecated-qi-b7d5a8ca00849b02.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/remove-deprecated-qi-b7d5a8ca00849b02.yaml", "repo_id": "qiskit", "token_count": 230 }
228
--- features: - | A new kwarg, ``cregbundle`` has been added to the :func:`qiskit.visualization.circuit_drawer` function and the :class:`~qiskit.circuit.QuantumCircuit` method :meth:`~qiskit.circuit.QuantumCircuit.draw`. When set to ``True`` the cregs will be bundled into a single line in circuit visualizations for the ``text`` and ``mpl`` drawers. The default value is ``True``. Addresses issue `#4290 <https://github.com/Qiskit/qiskit-terra/issues/4290>`_. For example: .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.measure_all() circuit.draw(output='mpl', cregbundle=True) - | A new kwarg, ``initial_state`` has been added to the :func:`qiskit.visualization.circuit_drawer` function and the :class:`~qiskit.circuit.QuantumCircuit` method :meth:`~qiskit.circuit.QuantumCircuit.draw`. When set to ``True`` the initial state will now be included in circuit visualizations for all drawers. Addresses issue `#4293 <https://github.com/Qiskit/qiskit-terra/issues/4293>`_. For example: .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.measure_all() circuit.draw(output='mpl', initial_state=True) - | Labels will now be displayed when using the 'mpl' drawer. There are 2 types of labels - gate labels and control labels. Gate labels will replace the gate name in the display. Control labels will display above or below the controls for a gate. Fixes issues #3766, #4580 Addresses issues `#3766 <https://github.com/Qiskit/qiskit-terra/issues/3766>`_ and `#4580 <https://github.com/Qiskit/qiskit-terra/issues/4580>`_. For example: .. code-block:: from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import YGate circuit = QuantumCircuit(2) circuit.append(YGate(label='A Y Gate').control(label='Y Control'), [0, 1]) circuit.draw(output='mpl') deprecations: - | The style dictionary key ``cregbundle`` has been deprecated and will be removed in a future release. This has been replaced by the kwarg ``cregbundle`` added to the :func:`qiskit.visualization.circuit_drawer` function and the :class:`~qiskit.circuit.QuantumCircuit` method :meth:`~qiskit.circuit.QuantumCircuit.draw`. fixes: - | In some situations long gate and register names would overflow, or leave excessive empty space around them when using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function. This has been fixed by using correct text widths for a proportional font. Fixes `#4611 <https://github.com/Qiskit/qiskit-terra/issues/4611>`__, `#4605 <https://github.com/Qiskit/qiskit-terra/issues/4605>`__, `#4545 <https://github.com/Qiskit/qiskit-terra/issues/4545>`__, `#4497 <https://github.com/Qiskit/qiskit-terra/issues/4497>`__, `#4449 <https://github.com/Qiskit/qiskit-terra/issues/4449>`__, and `#3641 <https://github.com/Qiskit/qiskit-terra/issues/3641>`__. - | When using the ``style` kwarg on the :meth:`qiskit.circuit.QuantumCircuit.draw` or :func:`qiskit.visualization.circuit_drawer` with the ``'mpl'`` output backend the dictionary key ``'showindex'`` set to ``True``, the index numbers at the top of the column did not line up properly. This has been fixed. - | When using ``cregbunde=True`` with the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function and measuring onto a second fold, the measure arrow would overwrite the creg count. The count was moved to the left to prevent this. Fixes `#4148 <https://github.com/Qiskit/qiskit-terra/issues/4148>`__. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function :class:`~qiskit.circuit.library.CSwapGate` gates and a controlled :class:`~qiskit.circuit.library.RZZGate` gates now display with their appropriate symbols instead of in a box. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function controlled gates created using the :meth:`~qiskit.circuit.QuantumCircuit.to_gate` method were not properly spaced and could overlap with other gates in the circuit diagram. This issue has been fixed. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function gates with arrays as parameters, such as :class:`~qiskit.extensions.HamiltonianGate`, no longer display with excessive space around them. Fixes `#4352 <https://github.com/Qiskit/qiskit-terra/issues/4352>`__. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function generic gates created by directly instantiating :class:`qiskit.circuit.Gate` method now display the proper background color for the gate. Fixes `#4496 <https://github.com/Qiskit/qiskit-terra/issues/4496>`__. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function an ``AttributeError`` that occurred when using :class:`~qiskit.extensions.Isometry` or :class:`~qiskit.extensions.Initialize` has been fixed. Fixes `#4439 <https://github.com/Qiskit/qiskit-terra/issues/4439>`__. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function some open-controlled gates did not properly display the open controls. This has been corrected so that open controls are properly displayed as open circles. Fixes `#4248 <https://github.com/Qiskit/qiskit-terra/issues/4248>`__. - | When using the ``'mpl'`` output backend for the :meth:`qiskit.circuit.QuantumCircuit.draw` method and :func:`qiskit.visualization.circuit_drawer` function setting the ``fold`` kwarg to -1 will now properly display the circuit without folding. Fixes `#4506 <https://github.com/Qiskit/qiskit-terra/issues/4506>`__.
qiskit/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml", "repo_id": "qiskit", "token_count": 2527 }
229
--- fixes: - | Previously, calling :meth:`~qiskit.circuit.library.BlueprintCircuit.inverse` on a :class:`~qiskit.circuit.library.BlueprintCircuit` object could fail if its internal data property was not yet populated. This has been fixed so that the calling :meth:`~qiskit.circuit.library.BlueprintCircuit.inverse` will populate the internal data before generating the inverse of the circuit. Fixes `#5140 <https://github.com/Qiskit/qiskit-terra/issues/5140>`__
qiskit/releasenotes/notes/0.16/build-blueprintcircuit-before-inverse-8ef85f6389588fe0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/build-blueprintcircuit-before-inverse-8ef85f6389588fe0.yaml", "repo_id": "qiskit", "token_count": 171 }
230
--- features: - | A new transpiler pass, :class:`~qiskit.transpiler.passes.Optimize1qGatesDecomposition`, has been added. This transpiler pass is an alternative to the existing :class:`~qiskit.transpiler.passes.Optimize1qGates` that uses the :class:`~qiskit.quantum_info.OneQubitEulerDecomposer` class to decompose and simplify a chain of single qubit gates. This method is compatible with any basis set, while :class:`~qiskit.transpiler.passes.Optimize1qGates` only works for u1, u2, and u3. The default pass managers for ``optimization_level`` 1, 2, and 3 have been updated to use this new pass if the basis set doesn't include u1, u2, or u3. - | The :class:`~qiskit.quantum_info.OneQubitEulerDecomposer` now supports two new basis, ``'PSX'`` and ``'U'``. These can be specified with the ``basis`` kwarg on the constructor. This will decompose the matrix into a circuit using :class:`~qiskit.circuit.library.PGate` and :class:`~qiskit.circuit.library.SXGate` for ``'PSX'``, and :class:`~qiskit.circuit.library.UGate` for ``'U'``.
qiskit/releasenotes/notes/0.16/optimize-1q-decomposition-53c78d7430b07c0c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/optimize-1q-decomposition-53c78d7430b07c0c.yaml", "repo_id": "qiskit", "token_count": 419 }
231
--- fixes: - | Fixed an issue where the :func:`~qiskit.execute_function.execute` function would raise :class:`~qiskit.exceptions.QiskitError` exception when a :class:`~qiskit.circuit.ParameterVector` object was passed in for the ``parameter_bind`` kwarg. parameter. For example, it is now possible to call something like:: execute(circuit, backend, parameter_binds=[{pv1: [...], pv2: [...]}]) where ``pv1`` and ``pv2`` are :class:`~qiskit.circuit.ParameterVector` objects. Fixed `#5467 <https://github.com/Qiskit/qiskit-terra/issues/5467>`__
qiskit/releasenotes/notes/0.17/ParameterVectors-aren't-unrolled-by-execute-c8bd393818e926b0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/ParameterVectors-aren't-unrolled-by-execute-c8bd393818e926b0.yaml", "repo_id": "qiskit", "token_count": 222 }
232
--- features: - | A new class, :class:`~qiskit.circuit.classicalfunction.BooleanExpression`, has been added to the :mod:`qiskit.circuit.classicalfunction` module. This class allows for creating an oracle from a Python boolean expression. For example: .. code-block:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.classicalfunction import BooleanExpression expression = BooleanExpression('~x & (y | z)') circuit = QuantumCircuit(4) circuit.append(expression, [0, 1, 2, 3]) circuit.draw('mpl') .. code-block:: circuit.decompose().draw('mpl') The :class:`~qiskit.circuit.classicalfunction.BooleanExpression` also includes a method, :meth:`~qiskit.circuit.classicalfunction.BooleanExpression.from_dimacs_file`, which allows loading formulas described in the `DIMACS-CNF <https://people.sc.fsu.edu/~jburkardt/data/cnf/cnf.html>`__ format. For example:: .. code-block:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.classicalfunction import BooleanExpression boolean_exp = BooleanExpression.from_dimacs_file("simple_v3_c2.cnf") circuit = QuantumCircuit(boolean_exp.num_qubits) circuit.append(boolean_exp, range(boolean_exp.num_qubits)) circuit.draw('text') .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œ β”‚ β”‚ q_1: ─1 β”œ β”‚ SIMPLE_V3_C2.CNF β”‚ q_2: ─2 β”œ β”‚ β”‚ q_3: ─3 β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ .. code-block:: circuit.decompose().draw('text') .. parsed-literal:: q_0: ──o────o──────────── β”‚ β”‚ q_1: ──■────o────■─────── β”‚ β”‚ β”‚ q_2: ──■────┼────o────■── β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β” q_3: ─ X β”œβ”€ X β”œβ”€ X β”œβ”€ X β”œ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ - | Added a new class, :class:`~qiskit.circuit.library.PhaseOracle`, has been added to the :mod:`qiskit.circuit.library` module. This class enables the construction of phase oracle circuits from Python boolean expressions. .. code-block:: from qiskit.circuit.library.phase_oracle import PhaseOracle oracle = PhaseOracle('x1 & x2 & (not x3)') oracle.draw('mpl') These phase oracles can be used as part of a larger algorithm, for example with :class:`qiskit.algorithms.AmplificationProblem`: .. code-block:: from qiskit.algorithms import AmplificationProblem, Grover from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = Grover(quantum_instance=backend) result = grover.amplify(problem) result.top_measurement would generate '011'. The :class:`~qiskit.circuit.library.PhaseOracle` class also includes a :meth:`~qiskit.circuit.library.PhaseOracle.from_dimacs_file` method which enables constructing a phase oracle from a file describing a formula in the `DIMACS-CNF <https://people.sc.fsu.edu/~jburkardt/data/cnf/cnf.html>`__ format. .. code-block:: from qiskit.circuit.library.phase_oracle import PhaseOracle oracle = PhaseOracle.from_dimacs_file("simple_v3_c2.cnf") oracle.draw('text') .. parsed-literal:: state_0: ─o───────o────────────── β”‚ β”Œβ”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β” state_1: ─■── X β”œβ”€β– β”€β”€ X β”œβ”€β– β”€β”€β”€β”€β”€β”€ β”‚ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” state_2: ─■───────────────o── Z β”œ β””β”€β”€β”€β”˜
qiskit/releasenotes/notes/0.17/bool_expression_phaseoracle-1802be3016c83fa8.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/bool_expression_phaseoracle-1802be3016c83fa8.yaml", "repo_id": "qiskit", "token_count": 1737 }
233
--- deprecations: - | The ``qiskit.pulse.schedule.ParameterizedSchedule`` class has been deprecated and will be removed in a future release. Instead you can directly parameterize pulse :class:`~qiskit.pulse.Schedule` objects with a :class:`~qiskit.circuit.Parameter` object, for example:: from qiskit.circuit import Parameter from qiskit.pulse import Schedule from qiskit.pulse import ShiftPhase, DriveChannel theta = Parameter('theta') target_schedule = Schedule() target_schedule.insert(0, ShiftPhase(theta, DriveChannel(0)), inplace=True) upgrade: - | The :class:`~qiskit.providers.models.PulseDefaults` returned by the fake pulse backends :py:class:`qiskit.test.mock.FakeOpenPulse2Q` and :py:class:`qiskit.test.mock.FakeOpenPulse3Q` have been updated to have more realistic pulse sequence definitions. If you are using these fake backend classes you may need to update your usage because of these changes.
qiskit/releasenotes/notes/0.17/deprecate-parameterized-schedule-b917c6692dff518d.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/deprecate-parameterized-schedule-b917c6692dff518d.yaml", "repo_id": "qiskit", "token_count": 342 }
234
--- fixes: - | Previously, when the option ``layout_method`` kwarg was provided to the :func:`~qiskit.compiler.transpile` function and the ``optimization_level`` kwarg was set to >= 2 so that the pass :class:`qiskit.transpiler.passes.CSPLayout` would run, if :class:`~qiskit.transpiler.passes.CSPLayout` found a solution then the method in ``layout_method`` was not executed. This has been fixed so that if specified, the ``layout_method`` is always honored. Fixed `#5409 <https://github.com/Qiskit/qiskit-terra/issues/5409>`__
qiskit/releasenotes/notes/0.17/if_layout_method_no_csplayout-a63d8e419e7f94e0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/if_layout_method_no_csplayout-a63d8e419e7f94e0.yaml", "repo_id": "qiskit", "token_count": 203 }
235
--- features: - | Improved the performance of :meth:`qiskit.quantum_info.Statevector.expectation_value` and :meth:`qiskit.quantum_info.DensityMatrix.expectation_value` when the argument operator is a :class:`~qiskit.quantum_info.Pauli` or :class:`~qiskit.quantum_info.SparsePauliOp` operator.
qiskit/releasenotes/notes/0.17/optimize_pauli_expval-afb9833d60bf417e.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/optimize_pauli_expval-afb9833d60bf417e.yaml", "repo_id": "qiskit", "token_count": 130 }
236
--- upgrade: - | The :class:`qiskit.quantum_info.Quaternion` class was moved from the ``qiskit.quantum_info.operator`` submodule to the ``qiskit.quantum_info.synthesis`` submodule to better reflect it's purpose. No change is required if you were importing it from the root :mod:`qiskit.quantum_info` module, but if you were importing from ``qiskit.quantum_info.operator`` you will need to update your import path.
qiskit/releasenotes/notes/0.17/quaternion-906f490b42fc034c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/quaternion-906f490b42fc034c.yaml", "repo_id": "qiskit", "token_count": 151 }
237
--- upgrade: - | The interpretation of ``meas_map`` (which is an attribute of a :class:`~qiskit.providers.models.PulseBackendConfiguration` object or as the corresponding ``meas_map`` kwarg on the :func:`~qiskit.compiler.schedule`, :func:`~qiskit.compiler.assemble`, :func:`~qiskit.compiler.sequence`, or :func:`~qiskit.execute_function.execute` functions) has been updated to better match the true constraints of the hardware. The format of this data is a list of lists, where the items in the inner list are integers specifying qubit labels. For instance:: [[A, B, C], [D, E, F, G]] Previously, the ``meas_map`` constraint was interpreted such that if one qubit was acquired (e.g. A), then all other qubits sharing a subgroup with that qubit (B and C) would have to be acquired at the same time and for the same duration. This constraint has been relaxed. One acquisition does not require more acquisitions. (If A is acquired, B and C do **not** need to be acquired.) Instead, qubits in the same measurement group cannot be acquired in a partially overlapping way -- think of the ``meas_map`` as specifying a shared acquisition resource (If we acquire A from ``t=1000`` to ``t=2000``, we cannot acquire B starting from ``1000<t<2000``). For example: .. code-block:: python # Good meas_map = [[0, 1]] # Acquire a subset of [0, 1] sched = pulse.Schedule() sched = sched.append(pulse.Acquire(10, acq_q0)) # Acquire 0 and 1 together (same start time, same duration) sched = pulse.Schedule() sched = sched.append(pulse.Acquire(10, acq_q0)) sched = sched.append(pulse.Acquire(10, acq_q1)) # Acquire 0 and 1 disjointly sched = pulse.Schedule() sched = sched.append(pulse.Acquire(10, acq_q0)) sched = sched.append(pulse.Acquire(10, acq_q1)) << 10 # Acquisitions overlap, but 0 and 1 aren't in the same measurement # grouping meas_map = [[0], [1]] sched = pulse.Schedule() sched = sched.append(pulse.Acquire(10, acq_q0)) sched = sched.append(pulse.Acquire(10, acq_q1)) << 1 # Bad: 0 and 1 are in the same grouping, but acquisitions # partially overlap meas_map = [[0, 1]] sched = pulse.Schedule() sched = sched.append(pulse.Acquire(10, acq_q0)) sched = sched.append(pulse.Acquire(10, acq_q1)) << 1
qiskit/releasenotes/notes/0.17/update-meas-map-interpretation-53795a9bc7d42857.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/update-meas-map-interpretation-53795a9bc7d42857.yaml", "repo_id": "qiskit", "token_count": 960 }
238
--- fixes: - | Fixed an issue with the :class:`~qiskit.circuit.library.NLocal` class in the :mod:`qiskit.circuit.library` module where it wouldn't properly raise an exception at object initialization if an invalid type was used for the ``reps`` kwarg which would result in an unexpected runtime error later. A ``TypeError`` will now be properly raised if the ``reps`` kwarg is not an ``int`` value. Fixed `#6515 <https://github.com/Qiskit/qiskit-terra/issues/6515>`__
qiskit/releasenotes/notes/0.18/bugfix-proper-exception-twolocal-4a348f45f5e2ad75.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/bugfix-proper-exception-twolocal-4a348f45f5e2ad75.yaml", "repo_id": "qiskit", "token_count": 169 }
239
--- fixes: - | Fixed an issue where adding a control to a :class:`~qiskit.circuit.ControlledGate` with open controls would unset the inner open controls. Fixes `#5857 <https://github.com/Qiskit/qiskit-terra/issues/5857>`__
qiskit/releasenotes/notes/0.18/fix-control-of-open-controlled-gate-7a036e42ef5c1b72.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/fix-control-of-open-controlled-gate-7a036e42ef5c1b72.yaml", "repo_id": "qiskit", "token_count": 91 }
240