diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 8446c870b1fd..b217ff25665e 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -35,6 +35,7 @@ Optimize1qGatesDecomposition, SetLayout, ) +from qiskit.utils.deprecation import deprecate_func from .base import BaseEstimator, EstimatorResult from .primitive_job import PrimitiveJob @@ -104,6 +105,7 @@ class BackendEstimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): precludes doing any provider- or backend-specific optimizations. """ + @deprecate_func(since="1.2", additional_msg="Use BackendEstimatorV2 instead.") def __init__( self, backend: BackendV1 | BackendV2, diff --git a/qiskit/primitives/backend_sampler.py b/qiskit/primitives/backend_sampler.py index f1399a548939..98592e079cb7 100644 --- a/qiskit/primitives/backend_sampler.py +++ b/qiskit/primitives/backend_sampler.py @@ -23,6 +23,7 @@ from qiskit.providers.options import Options from qiskit.result import QuasiDistribution, Result from qiskit.transpiler.passmanager import PassManager +from qiskit.utils.deprecation import deprecate_func from .backend_estimator import _prepare_counts, _run_circuits from .base import BaseSampler, SamplerResult @@ -46,6 +47,7 @@ class BackendSampler(BaseSampler[PrimitiveJob[SamplerResult]]): precludes doing any provider- or backend-specific optimizations. """ + @deprecate_func(since="1.2", additional_msg="Use BackendSamplerV2 instead.") def __init__( self, backend: BackendV1 | BackendV2, diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index 0a7c0ec86289..33ec40300b2a 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -r"""Base Estimator Classes""" +"""Base Estimator Classes""" from __future__ import annotations @@ -23,6 +23,7 @@ from qiskit.providers import JobV1 as Job from qiskit.quantum_info.operators import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator +from qiskit.utils.deprecation import deprecate_func from ..containers import ( DataBin, @@ -187,7 +188,26 @@ def _run( raise NotImplementedError("The subclass of BaseEstimator must implement `_run` method.") -BaseEstimator = BaseEstimatorV1 +class BaseEstimator(BaseEstimatorV1[T]): + """DEPRECATED. Type alias of Estimator V1 base class. + + See :class:`.BaseEstimatorV1` for details. + """ + + @deprecate_func(since="1.2", additional_msg="Use BaseEstimatorV2 instead.") + def __init__( + self, + *, + options: dict | None = None, + ): + """ + Creating an instance of an Estimator, or using one in a ``with`` context opens a session that + holds resources until the instance is ``close()`` ed or the context is exited. + + Args: + options: Default options. + """ + super().__init__(options=options) class BaseEstimatorV2(ABC): diff --git a/qiskit/primitives/base/base_primitive.py b/qiskit/primitives/base/base_primitive.py index 4519f6eb24e3..dff019aceeba 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Primitive abstract base class.""" +"""Primitive V1 abstract base class.""" from __future__ import annotations @@ -20,7 +20,7 @@ class BasePrimitive(ABC): - """Primitive abstract base class.""" + """Primitive V1 abstract base class.""" def __init__(self, options: dict | None = None): self._run_options = Options() diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index b14c682a83f0..6a0d25c83151 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ -Primitive result abstract base class +Primitive V1 result abstract base class """ from __future__ import annotations @@ -27,7 +27,7 @@ class _BasePrimitiveResult(ABC): """ - Base class for deprecated Primitive result methods. + Base class for deprecated Primitive V1 result methods. """ def __post_init__(self) -> None: diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 94c9a7681d06..81a1754ae35b 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -21,6 +21,7 @@ from qiskit.circuit import QuantumCircuit from qiskit.providers import JobV1 as Job +from qiskit.utils.deprecation import deprecate_func from ..containers.primitive_result import PrimitiveResult from ..containers.sampler_pub import SamplerPubLike @@ -150,7 +151,23 @@ def _run( raise NotImplementedError("The subclass of BaseSampler must implement `_run` method.") -BaseSampler = BaseSamplerV1 +class BaseSampler(BaseSamplerV1[T]): + """DEPRECATED. Type alias of Sampler V1 base class + + See :class:`.BaseSamplerV1` for details. + """ + + @deprecate_func(since="1.2", additional_msg="Use BaseSamplerV2 instead.") + def __init__( + self, + *, + options: dict | None = None, + ): + """ + Args: + options: Default options. + """ + super().__init__(options=options) class BaseSamplerV2(ABC): diff --git a/qiskit/primitives/base/estimator_result.py b/qiskit/primitives/base/estimator_result.py index 88dbf1862d49..dea72484d7df 100644 --- a/qiskit/primitives/base/estimator_result.py +++ b/qiskit/primitives/base/estimator_result.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ -Estimator result class +Estimator V1 result class """ from __future__ import annotations @@ -26,7 +26,7 @@ @dataclass(frozen=True) class EstimatorResult(_BasePrimitiveResult): - """Result of Estimator. + """Result of Estimator V1. .. code-block:: python diff --git a/qiskit/primitives/base/sampler_result.py b/qiskit/primitives/base/sampler_result.py index 4a472f0e2df9..d27a0f6ba70d 100644 --- a/qiskit/primitives/base/sampler_result.py +++ b/qiskit/primitives/base/sampler_result.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ -Sampler result class +Sampler V1 result class """ from __future__ import annotations @@ -25,7 +25,7 @@ @dataclass(frozen=True) class SamplerResult(_BasePrimitiveResult): - """Result of Sampler. + """Result of Sampler V1. .. code-block:: python diff --git a/qiskit/primitives/estimator.py b/qiskit/primitives/estimator.py index f300d377874d..874b631379b2 100644 --- a/qiskit/primitives/estimator.py +++ b/qiskit/primitives/estimator.py @@ -24,6 +24,7 @@ from qiskit.exceptions import QiskitError from qiskit.quantum_info import Statevector from qiskit.quantum_info.operators.base_operator import BaseOperator +from qiskit.utils.deprecation import deprecate_func from .base import BaseEstimator, EstimatorResult from .primitive_job import PrimitiveJob @@ -51,6 +52,7 @@ class Estimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): this option is ignored. """ + @deprecate_func(since="1.2", additional_msg="Use StatevectorEstimator instead.") def __init__(self, *, options: dict | None = None): """ Args: diff --git a/qiskit/primitives/sampler.py b/qiskit/primitives/sampler.py index 23a901603bef..da0b4ed4d003 100644 --- a/qiskit/primitives/sampler.py +++ b/qiskit/primitives/sampler.py @@ -24,6 +24,7 @@ from qiskit.exceptions import QiskitError from qiskit.quantum_info import Statevector from qiskit.result import QuasiDistribution +from qiskit.utils.deprecation import deprecate_func from .base import BaseSampler, SamplerResult from .primitive_job import PrimitiveJob @@ -52,6 +53,7 @@ class Sampler(BaseSampler[PrimitiveJob[SamplerResult]]): option is ignored. """ + @deprecate_func(since="1.2", additional_msg="Use StatevectorSampler instead.") def __init__(self, *, options: dict | None = None): """ Args: diff --git a/qiskit/primitives/utils.py b/qiskit/primitives/utils.py index d94e3355d201..db3fcbd132dc 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -25,8 +25,14 @@ from qiskit.quantum_info import PauliList, SparsePauliOp, Statevector from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli +from qiskit.utils.deprecation import deprecate_func +@deprecate_func( + since="1.2", + additional_msg="To initialize a circuit from a ``Statevector`` instance, " + + "use ``QuantumCircuit.initialize`` instead.", +) def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state by converting the input to a quantum circuit. @@ -45,6 +51,10 @@ def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: return qc +@deprecate_func( + since="1.2", + additional_msg="Use the constructor of ``SparsePauliOp`` instead.", +) def init_observable(observable: BaseOperator | str) -> SparsePauliOp: """Initialize observable by converting the input to a :class:`~qiskit.quantum_info.SparsePauliOp`. @@ -68,6 +78,12 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: return SparsePauliOp(observable) +@deprecate_func( + since="1.2", + additional_msg="Use ``QuantumCircuit.layout`` and ``SparsePauliOp.apply_layout`` " + + "to adjust an operator for a layout. Otherwise, use ``mthree.utils.final_measurement_mapping``. " + + "See https://qiskit-extensions.github.io/mthree/apidocs/utils.html for details.", +) def final_measurement_mapping(circuit: QuantumCircuit) -> dict[int, int]: """Return the final measurement mapping for the circuit. diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml new file mode 100644 index 000000000000..9526c12d6eca --- /dev/null +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -0,0 +1,26 @@ +--- +deprecations_primitives: + - | + Primitives V1 is now deprecated and will be removed in no less than 3 months from the release date. + + The following Primitives V1 classes are deprecated: + + * :class:`.BaseEstimator`, use :class:`.BaseEstimatorV2` instead, + * :class:`.BaseSampler`, use :class:`.BaseSamplerV2` instead, + * :class:`.Estimator`, use :class:`.StatevectorEstimator` instead, + * :class:`.Sampler`, use :class:`.StatevectorSampler` instead, + * :class:`.BackendEstimator`, use :class:`.BackendEstimatorV2` instead, + * :class:`.BackendSampler`, use :class:`.BackendSamplerV2` instead, + + + In addition, the following utility functions are deprecated: + + * :func:`.init_circuit`, to initialize a circuit from a :class:`.Statevector`, + use :meth:`.QuantumCircuit.initialize` instead, + * :func:`.init_observable`, use the constructor of :class:`.SparsePauliOp` instead, + * :func:`.final_measurement_mapping`, use :meth:`.QuantumCircuit.layout` and + :meth:`.SparsePauliOp.apply_layout` to adjust an operator for a layout. + Otherwise, use ``mthree.utils.final_measurement_mapping``. + See `Mthree Utility functions `__ + for details. + diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index 9725b865b4c4..c3deb0735ca1 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -88,14 +88,16 @@ def test_estimator_run(self, backend): psi1, psi2 = self.psi hamiltonian1, hamiltonian2, hamiltonian3 = self.hamiltonian theta1, theta2, theta3 = self.theta - estimator = BackendEstimator(backend=backend) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) estimator.set_options(seed_simulator=123) # Specify the circuit and observable by indices. # calculate [ ] - job = estimator.run([psi1], [hamiltonian1], [theta1]) - result = job.result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + job = estimator.run([psi1], [hamiltonian1], [theta1]) + result = job.result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956], rtol=0.5, atol=0.2) # Objects can be passed instead of indices. @@ -103,19 +105,26 @@ def test_estimator_run(self, backend): # since the corresponding indices need to be searched. # User can append a circuit and observable. # calculate [ ] - result2 = estimator.run([psi2], [hamiltonian1], [theta2]).result() + with self.assertWarns(DeprecationWarning): + result2 = estimator.run([psi2], [hamiltonian1], [theta2]).result() np.testing.assert_allclose(result2.values, [2.97797666], rtol=0.5, atol=0.2) # calculate [ , ] - result3 = estimator.run([psi1, psi1], [hamiltonian2, hamiltonian3], [theta1] * 2).result() + with self.assertWarns(DeprecationWarning): + result3 = estimator.run( + [psi1, psi1], [hamiltonian2, hamiltonian3], [theta1] * 2 + ).result() np.testing.assert_allclose(result3.values, [-0.551653, 0.07535239], rtol=0.5, atol=0.2) # calculate [ , # , # ] - result4 = estimator.run( - [psi1, psi2, psi1], [hamiltonian1, hamiltonian2, hamiltonian3], [theta1, theta2, theta3] - ).result() + with self.assertWarns(DeprecationWarning): + result4 = estimator.run( + [psi1, psi2, psi1], + [hamiltonian1, hamiltonian2, hamiltonian3], + [theta1, theta2, theta3], + ).result() np.testing.assert_allclose( result4.values, [1.55555728, 0.17849238, -1.08766318], rtol=0.5, atol=0.2 ) @@ -124,10 +133,11 @@ def test_estimator_run(self, backend): def test_estimator_run_no_params(self, backend): """test for estimator without parameters""" circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) - est = BackendEstimator(backend=backend) - est.set_options(seed_simulator=123) - result = est.run([circuit], [self.observable]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + est.set_options(seed_simulator=123) + result = est.run([circuit], [self.observable]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733], rtol=0.05) @combine(backend=BACKENDS, creg=[True, False]) @@ -140,22 +150,26 @@ def test_run_1qubit(self, backend, creg): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("Z", 1)]) - est = BackendEstimator(backend=backend) - est.set_options(seed_simulator=123) - result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + est.set_options(seed_simulator=123) + result = est.run([qc], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @combine(backend=BACKENDS, creg=[True, False]) @@ -170,29 +184,35 @@ def test_run_2qubits(self, backend, creg): op2 = SparsePauliOp.from_list([("ZI", 1)]) op3 = SparsePauliOp.from_list([("IZ", 1)]) - est = BackendEstimator(backend=backend) - result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + result = est.run([qc], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op3], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) - result = est.run([qc2], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op3], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @combine(backend=BACKENDS) @@ -204,18 +224,19 @@ def test_run_errors(self, backend): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("II", 1)]) - est = BackendEstimator(backend=backend) - est.set_options(seed_simulator=123) - with self.assertRaises(ValueError): - est.run([qc], [op2], [[]]).result() - with self.assertRaises(ValueError): - est.run([qc], [op], [[1e4]]).result() - with self.assertRaises(ValueError): - est.run([qc2], [op2], [[1, 2]]).result() - with self.assertRaises(ValueError): - est.run([qc, qc2], [op2], [[1]]).result() - with self.assertRaises(ValueError): - est.run([qc], [op, op2], [[1]]).result() + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + est.set_options(seed_simulator=123) + with self.assertRaises(ValueError): + est.run([qc], [op2], [[]]).result() + with self.assertRaises(ValueError): + est.run([qc], [op], [[1e4]]).result() + with self.assertRaises(ValueError): + est.run([qc2], [op2], [[1, 2]]).result() + with self.assertRaises(ValueError): + est.run([qc, qc2], [op2], [[1]]).result() + with self.assertRaises(ValueError): + est.run([qc], [op, op2], [[1]]).result() @combine(backend=BACKENDS) def test_run_numpy_params(self, backend): @@ -226,52 +247,58 @@ def test_run_numpy_params(self, backend): params_array = self._rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) - estimator = BackendEstimator(backend=backend) - estimator.set_options(seed_simulator=123) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) + estimator.set_options(seed_simulator=123) - target = estimator.run([qc] * k, [op] * k, params_list).result() + target = estimator.run([qc] * k, [op] * k, params_list).result() with self.subTest("ndarrary"): - result = estimator.run([qc] * k, [op] * k, params_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values, rtol=0.2, atol=0.2) with self.subTest("list of ndarray"): - result = estimator.run([qc] * k, [op] * k, params_list_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values, rtol=0.2, atol=0.2) @combine(backend=BACKENDS) def test_run_with_shots_option(self, backend): """test with shots option.""" - est = BackendEstimator(backend=backend) - result = est.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=1024, - seed_simulator=15, - ).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + result = est.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + shots=1024, + seed_simulator=15, + ).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641], rtol=0.1) @combine(backend=BACKENDS) def test_options(self, backend): """Test for options""" with self.subTest("init"): - estimator = BackendEstimator(backend=backend, options={"shots": 3000}) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend, options={"shots": 3000}) self.assertEqual(estimator.options.get("shots"), 3000) with self.subTest("set_options"): estimator.set_options(shots=1024, seed_simulator=15) self.assertEqual(estimator.options.get("shots"), 1024) self.assertEqual(estimator.options.get("seed_simulator"), 15) with self.subTest("run"): - result = estimator.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - ).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = estimator.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + ).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641], rtol=0.1) def test_job_size_limit_v2(self): @@ -291,9 +318,11 @@ def max_circuits(self): k = 5 params_array = self._rng.random((k, qc.num_parameters)) params_list = params_array.tolist() - estimator = BackendEstimator(backend=backend) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) with patch.object(backend, "run") as run_mock: - estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator.run([qc] * k, [op] * k, params_list).result() self.assertEqual(run_mock.call_count, 10) def test_job_size_limit_v1(self): @@ -307,10 +336,12 @@ def test_job_size_limit_v1(self): k = 5 params_array = self._rng.random((k, qc.num_parameters)) params_list = params_array.tolist() - estimator = BackendEstimator(backend=backend) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) estimator.set_options(seed_simulator=123) with patch.object(backend, "run") as run_mock: - estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator.run([qc] * k, [op] * k, params_list).result() self.assertEqual(run_mock.call_count, 10) def test_no_max_circuits(self): @@ -325,16 +356,19 @@ def test_no_max_circuits(self): params_array = self._rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) - estimator = BackendEstimator(backend=backend) - estimator.set_options(seed_simulator=123) - target = estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) + estimator.set_options(seed_simulator=123) + target = estimator.run([qc] * k, [op] * k, params_list).result() with self.subTest("ndarrary"): - result = estimator.run([qc] * k, [op] * k, params_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values, rtol=0.2, atol=0.2) with self.subTest("list of ndarray"): - result = estimator.run([qc] * k, [op] * k, params_list_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values, rtol=0.2, atol=0.2) @@ -352,8 +386,9 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) - _ = estimator.run(qc, op).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + _ = estimator.run(qc, op).result() expected = [ "bound_pass_manager", ] @@ -372,8 +407,11 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) - _ = estimator.run([qc, qc], [op, op]).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator( + backend=Fake7QPulseV1(), bound_pass_manager=bound_pass + ) + _ = estimator.run([qc, qc], [op, op]).result() expected = [ "bound_pass_manager", "bound_pass_manager", @@ -390,9 +428,10 @@ def test_layout(self, backend): qc.cx(0, 2) op = SparsePauliOp("IZI") backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend) - estimator.set_transpile_options(seed_transpiler=15) - value = estimator.run(qc, op, shots=10000).result().values[0] + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend) + estimator.set_transpile_options(seed_transpiler=15) + value = estimator.run(qc, op, shots=10000).result().values[0] if optionals.HAS_AER: ref_value = -0.9954 if isinstance(backend, GenericBackendV2) else -0.916 else: @@ -405,10 +444,11 @@ def test_layout(self, backend): qc.cx(0, 1) qc.cx(0, 2) op = SparsePauliOp("IZI") - estimator = BackendEstimator(backend) - estimator.set_transpile_options(initial_layout=[0, 1, 2], seed_transpiler=15) - estimator.set_options(seed_simulator=15) - value = estimator.run(qc, op, shots=10000).result().values[0] + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend) + estimator.set_transpile_options(initial_layout=[0, 1, 2], seed_transpiler=15) + estimator.set_options(seed_simulator=15) + value = estimator.run(qc, op, shots=10000).result().values[0] if optionals.HAS_AER: ref_value = -0.9954 if isinstance(backend, GenericBackendV2) else -0.8902 else: @@ -428,9 +468,10 @@ def test_circuit_with_measurement(self): backend = AerSimulator() backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend, skip_transpilation=True) - estimator.set_transpile_options(seed_transpiler=15) - result = estimator.run(bell, observable).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend, skip_transpilation=True) + estimator.set_transpile_options(seed_transpiler=15) + result = estimator.run(bell, observable).result() self.assertAlmostEqual(result.values[0], 1, places=1) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") @@ -449,9 +490,10 @@ def test_dynamic_circuit(self): backend = AerSimulator() backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend, skip_transpilation=True) - estimator.set_transpile_options(seed_transpiler=15) - result = estimator.run(qc, observable).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend, skip_transpilation=True) + estimator.set_transpile_options(seed_transpiler=15) + result = estimator.run(qc, observable).result() self.assertAlmostEqual(result.values[0], 0, places=1) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 8d1a3e2aab2b..8bc5f76ed095 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -113,10 +113,11 @@ def _compare_probs(self, prob, target): def test_sampler_run(self, backend): """Test Sampler.run().""" bell = self._circuit[1] - sampler = BackendSampler(backend=backend) - job = sampler.run(circuits=[bell], shots=1000) - result = job.result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + job = sampler.run(circuits=[bell], shots=1000) + result = job.result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(result.quasi_dists[0].shots, 1000) self.assertEqual(result.quasi_dists[0].stddev_upper_bound, math.sqrt(1 / 1000)) self._compare_probs(result.quasi_dists, self._target[1]) @@ -127,8 +128,9 @@ def test_sample_run_multiple_circuits(self, backend): # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] - sampler = BackendSampler(backend=backend) - result = sampler.run([bell, bell, bell]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run([bell, bell, bell]).result() self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) @@ -142,8 +144,9 @@ def test_sampler_run_with_parameterized_circuits(self, backend): pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta - sampler = BackendSampler(backend=backend) - result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { @@ -181,9 +184,10 @@ def test_run_1qubit(self, backend): qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=backend) - result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run([qc, qc2]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -204,9 +208,10 @@ def test_run_2qubit(self, backend): qc3.x([0, 1]) qc3.measure_all() - sampler = BackendSampler(backend=backend) - result = sampler.run([qc0, qc1, qc2, qc3]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run([qc0, qc1, qc2, qc3]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -222,13 +227,14 @@ def test_run_errors(self, backend): qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() - sampler = BackendSampler(backend=backend) - with self.assertRaises(ValueError): - sampler.run([qc1], [[1e2]]).result() - with self.assertRaises(ValueError): - sampler.run([qc2], [[]]).result() - with self.assertRaises(ValueError): - sampler.run([qc2], [[1e2]]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + with self.assertRaises(ValueError): + sampler.run([qc1], [[1e2]]).result() + with self.assertRaises(ValueError): + sampler.run([qc2], [[]]).result() + with self.assertRaises(ValueError): + sampler.run([qc2], [[1e2]]).result() @combine(backend=BACKENDS) def test_run_empty_parameter(self, backend): @@ -236,7 +242,8 @@ def test_run_empty_parameter(self, backend): n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) - sampler = BackendSampler(backend=backend) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) @@ -263,8 +270,9 @@ def test_run_numpy_params(self, backend): params_array = rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) - sampler = BackendSampler(backend=backend) - target = sampler.run([qc] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() @@ -282,19 +290,21 @@ def test_run_numpy_params(self, backend): def test_run_with_shots_option(self, backend): """test with shots option.""" params, target = self._generate_params_target([1]) - sampler = BackendSampler(backend=backend) - result = sampler.run( - circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 - ).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run( + circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 + ).result() self._compare_probs(result.quasi_dists, target) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell = self._circuit[1] - sampler = BackendSampler(backend=backend) - job = sampler.run(circuits=[bell]) - _ = job.result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + job = sampler.run(circuits=[bell]) + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_primitive_job_size_limit_backend_v2(self): @@ -312,9 +322,10 @@ def max_circuits(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5)) - result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5)) + result = sampler.run([qc, qc2]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -331,9 +342,10 @@ def test_primitive_job_size_limit_backend_v1(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=backend) - result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run([qc, qc2]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -354,10 +366,10 @@ def test_circuit_with_dynamic_circuit(self): with self.assertWarns(DeprecationWarning): backend = Aer.get_backend("aer_simulator") - sampler = BackendSampler(backend, skip_transpilation=True) - sampler.set_options(seed_simulator=15) - sampler.set_transpile_options(seed_transpiler=15) - result = sampler.run(qc).result() + sampler = BackendSampler(backend, skip_transpilation=True) + sampler.set_options(seed_simulator=15) + sampler.set_transpile_options(seed_transpiler=15) + result = sampler.run(qc).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 0.5029296875, 1: 0.4970703125}) def test_sequential_run(self): @@ -367,8 +379,9 @@ def test_sequential_run(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=Fake7QPulseV1()) - result = sampler.run([qc]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=Fake7QPulseV1()) + result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) result2 = sampler.run([qc2]).result() self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) @@ -388,9 +401,10 @@ def test_outcome_bitstring_size(self): # We need a noise-free backend here (shot noise is fine) to ensure that # the only bit string measured is "0001". With device noise, it could happen that # strings with a leading 1 are measured and then the truncation cannot be tested. - sampler = BackendSampler(backend=BasicSimulator()) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=BasicSimulator()) - result = sampler.run(qc).result() + result = sampler.run(qc).result() probs = result.quasi_dists[0].binary_probabilities() self.assertIn("0001", probs.keys()) @@ -407,8 +421,9 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) - _ = sampler.run([self._circuit[0]]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + _ = sampler.run([self._circuit[0]]).result() expected = [ "bound_pass_manager", ] @@ -427,8 +442,9 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) - _ = sampler.run([self._circuit[0], self._circuit[0]]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + _ = sampler.run([self._circuit[0], self._circuit[0]]).result() expected = [ "bound_pass_manager", "bound_pass_manager", diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index 535841cc90f7..783461c7e4ad 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -62,13 +62,14 @@ def test_estimator_run(self): psi1, psi2 = self.psi hamiltonian1, hamiltonian2, hamiltonian3 = self.hamiltonian theta1, theta2, theta3 = self.theta - estimator = Estimator() + with self.assertWarns(DeprecationWarning): + estimator = Estimator() - # Specify the circuit and observable by indices. - # calculate [ ] - job = estimator.run([psi1], [hamiltonian1], [theta1]) - result = job.result() - self.assertIsInstance(result, EstimatorResult) + # Specify the circuit and observable by indices. + # calculate [ ] + job = estimator.run([psi1], [hamiltonian1], [theta1]) + result = job.result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956]) # Objects can be passed instead of indices. @@ -76,32 +77,41 @@ def test_estimator_run(self): # since the corresponding indices need to be searched. # User can append a circuit and observable. # calculate [ ] - result2 = estimator.run([psi2], [hamiltonian1], [theta2]).result() + with self.assertWarns(DeprecationWarning): + result2 = estimator.run([psi2], [hamiltonian1], [theta2]).result() np.testing.assert_allclose(result2.values, [2.97797666]) # calculate [ , ] - result3 = estimator.run([psi1, psi1], [hamiltonian2, hamiltonian3], [theta1] * 2).result() + with self.assertWarns(DeprecationWarning): + result3 = estimator.run( + [psi1, psi1], [hamiltonian2, hamiltonian3], [theta1] * 2 + ).result() np.testing.assert_allclose(result3.values, [-0.551653, 0.07535239]) # calculate [ , # , # ] - result4 = estimator.run( - [psi1, psi2, psi1], [hamiltonian1, hamiltonian2, hamiltonian3], [theta1, theta2, theta3] - ).result() + with self.assertWarns(DeprecationWarning): + result4 = estimator.run( + [psi1, psi2, psi1], + [hamiltonian1, hamiltonian2, hamiltonian3], + [theta1, theta2, theta3], + ).result() np.testing.assert_allclose(result4.values, [1.55555728, 0.17849238, -1.08766318]) def test_estiamtor_run_no_params(self): """test for estimator without parameters""" circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) - est = Estimator() - result = est.run([circuit], [self.observable]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = Estimator() + result = est.run([circuit], [self.observable]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733]) def test_run_single_circuit_observable(self): """Test for single circuit and single observable case.""" - est = Estimator() + with self.assertWarns(DeprecationWarning): + est = Estimator() with self.subTest("No parameter"): qc = QuantumCircuit(1) @@ -111,7 +121,8 @@ def test_run_single_circuit_observable(self): target = [-1] for val in param_vals: self.subTest(f"{val}") - result = est.run(qc, op, val).result() + with self.assertWarns(DeprecationWarning): + result = est.run(qc, op, val).result() np.testing.assert_allclose(result.values, target) self.assertEqual(len(result.metadata), 1) @@ -130,7 +141,8 @@ def test_run_single_circuit_observable(self): target = [-1] for val in param_vals: self.subTest(f"{val}") - result = est.run(qc, op, val).result() + with self.assertWarns(DeprecationWarning): + result = est.run(qc, op, val).result() np.testing.assert_allclose(result.values, target) self.assertEqual(len(result.metadata), 1) @@ -147,7 +159,8 @@ def test_run_single_circuit_observable(self): target = [1.5555572817900956] for val in param_vals: self.subTest(f"{val}") - result = est.run(qc, op, val).result() + with self.assertWarns(DeprecationWarning): + result = est.run(qc, op, val).result() np.testing.assert_allclose(result.values, target) self.assertEqual(len(result.metadata), 1) @@ -160,21 +173,25 @@ def test_run_1qubit(self): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("Z", 1)]) - est = Estimator() - result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = Estimator() + result = est.run([qc], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) def test_run_2qubits(self): @@ -187,29 +204,35 @@ def test_run_2qubits(self): op2 = SparsePauliOp.from_list([("ZI", 1)]) op3 = SparsePauliOp.from_list([("IZ", 1)]) - est = Estimator() - result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = Estimator() + result = est.run([qc], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc], [op3], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) - result = est.run([qc2], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op3], [[]]).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) def test_run_errors(self): @@ -220,17 +243,18 @@ def test_run_errors(self): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("II", 1)]) - est = Estimator() - with self.assertRaises(ValueError): - est.run([qc], [op2], [[]]).result() - with self.assertRaises(ValueError): - est.run([qc], [op], [[1e4]]).result() - with self.assertRaises(ValueError): - est.run([qc2], [op2], [[1, 2]]).result() - with self.assertRaises(ValueError): - est.run([qc, qc2], [op2], [[1]]).result() - with self.assertRaises(ValueError): - est.run([qc], [op, op2], [[1]]).result() + with self.assertWarns(DeprecationWarning): + est = Estimator() + with self.assertRaises(ValueError): + est.run([qc], [op2], [[]]).result() + with self.assertRaises(ValueError): + est.run([qc], [op], [[1e4]]).result() + with self.assertRaises(ValueError): + est.run([qc2], [op2], [[1, 2]]).result() + with self.assertRaises(ValueError): + est.run([qc, qc2], [op2], [[1]]).result() + with self.assertRaises(ValueError): + est.run([qc], [op, op2], [[1]]).result() def test_run_numpy_params(self): """Test for numpy array as parameter values""" @@ -241,75 +265,83 @@ def test_run_numpy_params(self): params_array = rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) - estimator = Estimator() - target = estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator = Estimator() + target = estimator.run([qc] * k, [op] * k, params_list).result() with self.subTest("ndarrary"): - result = estimator.run([qc] * k, [op] * k, params_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values) with self.subTest("list of ndarray"): - result = estimator.run([qc] * k, [op] * k, params_list_array).result() + with self.assertWarns(DeprecationWarning): + result = estimator.run([qc] * k, [op] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values) def test_run_with_shots_option(self): """test with shots option.""" - est = Estimator() - result = est.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=1024, - seed=15, - ).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + est = Estimator() + result = est.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + shots=1024, + seed=15, + ).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641]) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" - est = Estimator() - result_42 = est.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=None, - seed=42, - ).result() - result_15 = est.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=None, - seed=15, - ).result() + with self.assertWarns(DeprecationWarning): + est = Estimator() + result_42 = est.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + shots=None, + seed=42, + ).result() + result_15 = est.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + shots=None, + seed=15, + ).result() np.testing.assert_allclose(result_42.values, result_15.values) def test_options(self): """Test for options""" with self.subTest("init"): - estimator = Estimator(options={"shots": 3000}) + with self.assertWarns(DeprecationWarning): + estimator = Estimator(options={"shots": 3000}) self.assertEqual(estimator.options.get("shots"), 3000) with self.subTest("set_options"): estimator.set_options(shots=1024, seed=15) self.assertEqual(estimator.options.get("shots"), 1024) self.assertEqual(estimator.options.get("seed"), 15) with self.subTest("run"): - result = estimator.run( - [self.ansatz], - [self.observable], - parameter_values=[[0, 1, 1, 2, 3, 5]], - ).result() - self.assertIsInstance(result, EstimatorResult) + with self.assertWarns(DeprecationWarning): + result = estimator.run( + [self.ansatz], + [self.observable], + parameter_values=[[0, 1, 1, 2, 3, 5]], + ).result() + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641]) def test_negative_variance(self): """Test for negative variance caused by numerical error.""" qc = QuantumCircuit(1) - estimator = Estimator() - result = estimator.run(qc, 1e-4 * SparsePauliOp("I"), shots=1024).result() + with self.assertWarns(DeprecationWarning): + estimator = Estimator() + result = estimator.run(qc, 1e-4 * SparsePauliOp("I"), shots=1024).result() self.assertEqual(result.values[0], 1e-4) self.assertEqual(result.metadata[0]["variance"], 0.0) @@ -348,19 +380,22 @@ class TestObservableValidation(QiskitTestCase): @unpack def test_validate_observables(self, observables, expected): """Test observables standardization.""" - self.assertEqual(validation._validate_observables(observables), expected) + with self.assertWarns(DeprecationWarning): + self.assertEqual(validation._validate_observables(observables), expected) @data(None, "ERROR") def test_qiskit_error(self, observables): """Test qiskit error if invalid input.""" with self.assertRaises(QiskitError): - validation._validate_observables(observables) + with self.assertWarns(DeprecationWarning): + validation._validate_observables(observables) @data((), []) def test_value_error(self, observables): """Test value error if no observables are provided.""" with self.assertRaises(ValueError): - validation._validate_observables(observables) + with self.assertWarns(DeprecationWarning): + validation._validate_observables(observables) if __name__ == "__main__": diff --git a/test/python/primitives/test_sampler.py b/test/python/primitives/test_sampler.py index eac0886b30b1..58ab97689748 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -87,10 +87,11 @@ def _compare_probs(self, prob, target): def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] - sampler = Sampler() - job = sampler.run(circuits=[bell]) - result = job.result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + job = sampler.run(circuits=[bell]) + result = job.result() + self.assertIsInstance(result, SamplerResult) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): @@ -98,8 +99,9 @@ def test_sample_run_multiple_circuits(self): # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] - sampler = Sampler() - result = sampler.run([bell, bell, bell]).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([bell, bell, bell]).result() self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) @@ -112,8 +114,9 @@ def test_sampler_run_with_parameterized_circuits(self): pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta - sampler = Sampler() - result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { @@ -150,9 +153,10 @@ def test_run_1qubit(self): qc2.x(0) qc2.measure_all() - sampler = Sampler() - result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([qc, qc2]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): @@ -174,9 +178,10 @@ def test_run_2qubit(self): qc3.x([0, 1]) qc3.measure_all() - sampler = Sampler() - result = sampler.run([qc0, qc1, qc2, qc3]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([qc0, qc1, qc2, qc3]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): @@ -187,15 +192,16 @@ def test_run_2qubit(self): def test_run_single_circuit(self): """Test for single circuit case.""" - sampler = Sampler() - with self.subTest("No parameter"): circuit = self._circuit[1] target = self._target[1] param_vals = [None, [], [[]], np.array([]), np.array([[]])] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): - result = sampler.run(circuit, val).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + with self.assertWarns(DeprecationWarning): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -214,7 +220,10 @@ def test_run_single_circuit(self): ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): - result = sampler.run(circuit, val).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + with self.assertWarns(DeprecationWarning): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -230,7 +239,10 @@ def test_run_single_circuit(self): ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): - result = sampler.run(circuit, val).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + with self.assertWarns(DeprecationWarning): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -247,9 +259,10 @@ def test_run_reverse_meas_order(self): qc.measure(1, 1) qc.measure(2, 0) - sampler = Sampler() - result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() - self.assertIsInstance(result, SamplerResult) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) @@ -274,37 +287,40 @@ def test_run_errors(self): with qc5.for_loop(range(5)): qc5.h(0) - sampler = Sampler() - with self.subTest("set parameter values to a non-parameterized circuit"): - with self.assertRaises(ValueError): - _ = sampler.run([qc1], [[1e2]]) - with self.subTest("missing all parameter values for a parameterized circuit"): - with self.assertRaises(ValueError): - _ = sampler.run([qc2], [[]]) - with self.subTest("missing some parameter values for a parameterized circuit"): - with self.assertRaises(ValueError): - _ = sampler.run([qc2], [[1e2]]) - with self.subTest("too many parameter values for a parameterized circuit"): - with self.assertRaises(ValueError): - _ = sampler.run([qc2], [[1e2]] * 100) - with self.subTest("no classical bits"): - with self.assertRaises(ValueError): - _ = sampler.run([qc3], [[]]) - with self.subTest("no measurement"): - with self.assertRaises(ValueError): - _ = sampler.run([qc4], [[]]) - with self.subTest("no measurement in control flow"): - with self.assertRaises(ValueError): - _ = sampler.run([qc5], [[]]) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + with self.subTest("set parameter values to a non-parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([qc1], [[1e2]]) + with self.subTest("missing all parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([qc2], [[]]) + with self.subTest("missing some parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([qc2], [[1e2]]) + with self.subTest("too many parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([qc2], [[1e2]] * 100) + with self.subTest("no classical bits"): + with self.assertRaises(ValueError): + _ = sampler.run([qc3], [[]]) + with self.subTest("no measurement"): + with self.assertRaises(ValueError): + _ = sampler.run([qc4], [[]]) + with self.subTest("no measurement in control flow"): + with self.assertRaises(ValueError): + _ = sampler.run([qc5], [[]]) def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) - sampler = Sampler() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() with self.subTest("one circuit"): - result = sampler.run([qc], shots=1000).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} @@ -328,8 +344,9 @@ def test_run_numpy_params(self): params_array = rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) - sampler = Sampler() - target = sampler.run([qc] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() @@ -346,21 +363,23 @@ def test_run_numpy_params(self): def test_run_with_shots_option(self): """test with shots option.""" params, target = self._generate_params_target([1]) - sampler = Sampler() - result = sampler.run( - circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 - ).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run( + circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 + ).result() self._compare_probs(result.quasi_dists, target) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" - sampler = Sampler() - result_42 = sampler.run( - [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 - ).result() - result_15 = sampler.run( - [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 - ).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result_42 = sampler.run( + [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 + ).result() + result_15 = sampler.run( + [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 + ).result() self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists) def test_run_shots_result_size(self): @@ -370,8 +389,9 @@ def test_run_shots_result_size(self): qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() - sampler = Sampler() - result = sampler.run(qc, [], shots=shots, seed=42).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run(qc, [], shots=shots, seed=42).result() self.assertEqual(len(result.quasi_dists), 1) self.assertLessEqual(len(result.quasi_dists[0]), shots) self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0) @@ -379,15 +399,17 @@ def test_run_shots_result_size(self): def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] - sampler = Sampler() - job = sampler.run(circuits=[bell]) - _ = job.result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + job = sampler.run(circuits=[bell]) + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): - sampler = Sampler(options={"shots": 3000}) + with self.assertWarns(DeprecationWarning): + sampler = Sampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) @@ -395,7 +417,8 @@ def test_options(self): self.assertEqual(sampler.options.get("seed"), 15) with self.subTest("run"): params, target = self._generate_params_target([1]) - result = sampler.run([self._pqc], parameter_values=params).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([self._pqc], parameter_values=params).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(result.quasi_dists[0].shots, 1024) @@ -407,8 +430,9 @@ def test_circuit_with_unitary(self): circuit.append(gate, [0]) circuit.measure_all() - sampler = Sampler() - sampler_result = sampler.run([circuit]).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + sampler_result = sampler.run([circuit]).result() self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0}) diff --git a/test/python/primitives/test_utils.py b/test/python/primitives/test_utils.py index 9f1c53091f2f..9a9d27a62bf1 100644 --- a/test/python/primitives/test_utils.py +++ b/test/python/primitives/test_utils.py @@ -27,20 +27,23 @@ class TestMapping(QiskitTestCase): def test_empty_circ(self): """Empty circuit has no mapping""" qc = QuantumCircuit() - self.assertDictEqual(final_measurement_mapping(qc), {}) + with self.assertWarns(DeprecationWarning): + self.assertDictEqual(final_measurement_mapping(qc), {}) def test_sime_circ(self): """Just measures""" qc = QuantumCircuit(5) qc.measure_all() - self.assertDictEqual(final_measurement_mapping(qc), {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}) + with self.assertWarns(DeprecationWarning): + self.assertDictEqual(final_measurement_mapping(qc), {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}) def test_simple2_circ(self): """Meas followed by Hadamards""" qc = QuantumCircuit(5) qc.measure_all() qc.h(range(5)) - self.assertDictEqual(final_measurement_mapping(qc), {}) + with self.assertWarns(DeprecationWarning): + self.assertDictEqual(final_measurement_mapping(qc), {}) def test_multi_qreg(self): """Test multiple qregs""" @@ -55,7 +58,8 @@ def test_multi_qreg(self): qc.measure(range(2, 4), range(2, 4)) qc.barrier(range(5)) qc.measure(1, 4) - self.assertDictEqual(final_measurement_mapping(qc), {2: 2, 3: 3, 1: 4}) + with self.assertWarns(DeprecationWarning): + self.assertDictEqual(final_measurement_mapping(qc), {2: 2, 3: 3, 1: 4}) def test_multi_creg(self): """Test multiple qregs""" @@ -71,7 +75,8 @@ def test_multi_creg(self): qc.measure(range(2, 4), range(2, 4)) qc.barrier(range(5)) qc.measure(1, 4) - self.assertDictEqual(final_measurement_mapping(qc), {2: 2, 3: 3, 1: 4}) + with self.assertWarns(DeprecationWarning): + self.assertDictEqual(final_measurement_mapping(qc), {2: 2, 3: 3, 1: 4}) def test_mapping_w_delays(self): """Check that measurements followed by delays get in the mapping""" @@ -81,5 +86,6 @@ def test_mapping_w_delays(self): qc.measure(1, 0) qc.barrier() - maps = final_measurement_mapping(qc) + with self.assertWarns(DeprecationWarning): + maps = final_measurement_mapping(qc) self.assertDictEqual(maps, {1: 0, 0: 1}) diff --git a/test/python/quantum_info/operators/symplectic/test_pauli.py b/test/python/quantum_info/operators/symplectic/test_pauli.py index 35acd46a4d02..91568ac32a4b 100644 --- a/test/python/quantum_info/operators/symplectic/test_pauli.py +++ b/test/python/quantum_info/operators/symplectic/test_pauli.py @@ -545,12 +545,14 @@ def test_permute_pauli_estimator_example(self): op = Pauli("XXXI") backend = GenericBackendV2(num_qubits=7, seed=0) backend.set_options(seed_simulator=123) - estimator = BackendEstimator(backend=backend, skip_transpilation=True) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend, skip_transpilation=True) thetas = list(range(len(psi.parameters))) transpiled_psi = transpile(psi, backend, optimization_level=3) permuted_op = op.apply_layout(transpiled_psi.layout) - job = estimator.run(transpiled_psi, permuted_op, thetas) - res = job.result().values + with self.assertWarns(DeprecationWarning): + job = estimator.run(transpiled_psi, permuted_op, thetas) + res = job.result().values if optionals.HAS_AER: np.testing.assert_allclose(res, [0.20898438], rtol=0.5, atol=0.2) else: diff --git a/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py b/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py index c4f09ec2d795..4964b0c6a609 100644 --- a/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py +++ b/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py @@ -1118,12 +1118,14 @@ def test_permute_sparse_pauli_op_estimator_example(self): op = SparsePauliOp.from_list([("IIII", 1), ("IZZZ", 2), ("XXXI", 3)]) backend = GenericBackendV2(num_qubits=7, seed=0) backend.set_options(seed_simulator=123) - estimator = BackendEstimator(backend=backend, skip_transpilation=True) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend, skip_transpilation=True) thetas = list(range(len(psi.parameters))) transpiled_psi = transpile(psi, backend, optimization_level=3) permuted_op = op.apply_layout(transpiled_psi.layout) - job = estimator.run(transpiled_psi, permuted_op, thetas) - res = job.result().values + with self.assertWarns(DeprecationWarning): + job = estimator.run(transpiled_psi, permuted_op, thetas) + res = job.result().values if optionals.HAS_AER: np.testing.assert_allclose(res, [1.419922], rtol=0.5, atol=0.2) else: