From 48e7182b3cd08ae13d2420cbc9d250b4b49fb74c Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Thu, 13 Jun 2024 23:34:27 +0200 Subject: [PATCH 01/21] Deprecate V1 Primitives and their utils --- qiskit/primitives/backend_estimator.py | 2 + qiskit/primitives/backend_sampler.py | 2 + qiskit/primitives/base/base_estimator.py | 2 + qiskit/primitives/base/base_primitive.py | 2 + qiskit/primitives/base/base_result.py | 8 + qiskit/primitives/base/base_sampler.py | 2 + qiskit/primitives/estimator.py | 2 + qiskit/primitives/sampler.py | 2 + qiskit/primitives/utils.py | 4 + .../notes/deprecate-primitives-v1.yaml | 14 ++ .../primitives/test_backend_estimator.py | 204 +++++++++++------- .../python/primitives/test_backend_sampler.py | 112 ++++++---- test/python/primitives/test_estimator.py | 181 +++++++++------- test/python/primitives/test_result.py | 12 +- test/python/primitives/test_sampler.py | 152 +++++++------ test/python/primitives/test_utils.py | 18 +- .../symplectic/test_sparse_pauli_op.py | 8 +- 17 files changed, 449 insertions(+), 278 deletions(-) create mode 100644 releasenotes/notes/deprecate-primitives-v1.yaml diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index b91ea7068be1..959d9bb8031b 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 @@ -102,6 +103,7 @@ class BackendEstimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): precludes doing any provider- or backend-specific optimizations. """ + @deprecate_func(since="1.0", 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..26806dc46e51 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.0", 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 9191b4162d92..0d0448b9b396 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -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, @@ -103,6 +104,7 @@ class BaseEstimatorV1(BasePrimitive, Generic[T]): __hash__ = None + @deprecate_func(since="1.0", additional_msg="Use BaseEstimatorV2 instead.") def __init__( self, *, diff --git a/qiskit/primitives/base/base_primitive.py b/qiskit/primitives/base/base_primitive.py index 4519f6eb24e3..b4e041f9c617 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -17,11 +17,13 @@ from abc import ABC from qiskit.providers import Options +from qiskit.utils.deprecation import deprecate_func class BasePrimitive(ABC): """Primitive abstract base class.""" + @deprecate_func(since="1.0", additional_msg="Use BasePrimitiveV2 instead.") def __init__(self, options: dict | None = None): self._run_options = Options() if options is not None: diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index b14c682a83f0..359a07d9dedc 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -19,6 +19,7 @@ from collections.abc import Sequence from dataclasses import fields from typing import Any, Dict +from warnings import warn from numpy import ndarray @@ -42,6 +43,13 @@ def __post_init__(self) -> None: TypeError: If one of the data fields is not a Sequence or ``numpy.ndarray``. ValueError: Inconsistent number of experiments across data fields. """ + warn( + "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.0. " + "It will be removed no earlier than 3 months after the release date. " + "Use PrimitiveResult class in `qiskit.primitives.containers` instead.", + DeprecationWarning, + ) + num_experiments = None for value in self._field_values: # type: Sequence if num_experiments is None: diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 94c9a7681d06..5ebfa4f4d51a 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 @@ -96,6 +97,7 @@ class BaseSamplerV1(BasePrimitive, Generic[T]): __hash__ = None + @deprecate_func(since="1.0", additional_msg="Use BaseSamplerV2 instead.") def __init__( self, *, diff --git a/qiskit/primitives/estimator.py b/qiskit/primitives/estimator.py index f300d377874d..b615cadd277c 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.0", 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..9f00e3c8c199 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.0", 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..cd3c0d72febc 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -25,8 +25,10 @@ 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.0", additional_msg="There is no replacement for this.") def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state by converting the input to a quantum circuit. @@ -45,6 +47,7 @@ def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: return qc +@deprecate_func(since="1.0", additional_msg="There is no replacement for this.") def init_observable(observable: BaseOperator | str) -> SparsePauliOp: """Initialize observable by converting the input to a :class:`~qiskit.quantum_info.SparsePauliOp`. @@ -68,6 +71,7 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: return SparsePauliOp(observable) +@deprecate_func(since="1.0", additional_msg="There is no replacement for this.") 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..4d43cfedf5ba --- /dev/null +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -0,0 +1,14 @@ +--- +deprecation: + - | + BackendEstimator has been deprecated. Use BackendEstimatorV2 instead. + BackendSampler has been deprecated. Use BackendSamplerV2 instead. + Estimator has been deprecated. Use StatevectorEstimator instead. + Sampler has been deprecated. Use StatevectorSampler instead. + + BaseEstimatorV1 has been deprecated. Use BaseEstimatorV2 instead. + BasePrimitive has been deprecated. Use BasePrimitiveV2 instead. + BasePrimitiveResult has been deprecated. Use PrimitiveResult class in `qiskit.primitives.containers` instead. + BaseSamplerV1 has been deprecated. Use BaseSamplerV2 instead. + + Functions: init_circuit, init_observable and final_measurement_mapping has been deprecated. There is no replacement. diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index 9725b865b4c4..54444804c423 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -88,13 +88,15 @@ 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() + 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) @@ -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,9 +133,10 @@ 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() + 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) @@ -140,21 +150,25 @@ 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() + 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() + 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() + 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() + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @@ -170,28 +184,34 @@ 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() + 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() + 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() + 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() + 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() + 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() + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op3], [[]]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @@ -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,32 +247,36 @@ 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() + 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) @@ -259,18 +284,20 @@ def test_run_with_shots_option(self, backend): 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() + 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) @@ -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..c532d8f5d2d0 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -113,8 +113,9 @@ 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) + 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) @@ -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,8 +184,9 @@ def test_run_1qubit(self, backend): qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=backend) - result = sampler.run([qc, qc2]).result() + 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) @@ -204,8 +208,9 @@ 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() + 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) @@ -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,9 +242,11 @@ 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() + 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} @@ -246,7 +254,8 @@ def test_run_empty_parameter(self, backend): self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): - result = sampler.run([qc, qc], shots=1000).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} @@ -263,8 +272,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,18 +292,20 @@ 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]) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) @@ -312,8 +324,9 @@ 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() + 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) @@ -331,8 +344,9 @@ 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() + 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) @@ -354,10 +368,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,12 +381,15 @@ 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() + with self.assertWarns(DeprecationWarning): + result2 = sampler.run([qc2]).result() self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) - result3 = sampler.run([qc, qc2]).result() + with self.assertWarns(DeprecationWarning): + result3 = sampler.run([qc, qc2]).result() self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1) @@ -388,9 +405,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 +425,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 +446,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 80045dee0d67..d6dd3223f347 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -62,11 +62,12 @@ 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]) + # 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]) @@ -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() + 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,20 +173,24 @@ 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() + 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() + 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() + 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() + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op2], [[]]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) @@ -187,28 +204,34 @@ 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() + 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() + 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() + 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() + 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() + 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() + with self.assertWarns(DeprecationWarning): + result = est.run([qc2], [op3], [[]]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) @@ -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,66 +265,74 @@ 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() + 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) + with self.assertWarns(DeprecationWarning): + 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() + 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]) @@ -308,8 +340,9 @@ 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) diff --git a/test/python/primitives/test_result.py b/test/python/primitives/test_result.py index 15a9a8d3c781..49e79e5501e6 100644 --- a/test/python/primitives/test_result.py +++ b/test/python/primitives/test_result.py @@ -44,22 +44,26 @@ class TestBasePrimitiveResult(QiskitTestCase): @data(0, 1.2, True, "sequence", b"sequence", {"name": "value"}) def test_post_init_type_error(self, field_1): """Tests post init type error.""" - self.assertRaises(TypeError, Result, *(field_1, [])) + with self.assertWarns(DeprecationWarning): + self.assertRaises(TypeError, Result, *(field_1, [])) @data(([1], []), ([], [1]), ([1, 2], []), ([1], [1, 2])) @unpack def test_post_init_value_error(self, field_1, field_2): """Tests post init value error.""" - self.assertRaises(ValueError, Result, *(field_1, field_2)) + with self.assertWarns(DeprecationWarning): + self.assertRaises(ValueError, Result, *(field_1, field_2)) def test_field_names(self): """Tests field names ("field_1", "field_2").""" - result = Result([], []) + with self.assertWarns(DeprecationWarning): + result = Result([], []) self.assertEqual(result._field_names, ("field_1", "field_2")) @data(([], []), ([0], [0]), ([0], [1])) @unpack def test_field_values(self, field_1, field_2): """Tests field values ({field_1}, {field_2}).""" - result = Result(field_1, field_2) + with self.assertWarns(DeprecationWarning): + result = Result(field_1, field_2) self.assertEqual(result._field_values, (field_1, field_2)) diff --git a/test/python/primitives/test_sampler.py b/test/python/primitives/test_sampler.py index eac0886b30b1..c70f3cc40ede 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -87,8 +87,9 @@ 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]) + 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]) @@ -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,8 +153,9 @@ def test_run_1qubit(self): qc2.x(0) qc2.measure_all() - sampler = Sampler() - result = sampler.run([qc, qc2]).result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) @@ -174,8 +178,9 @@ def test_run_2qubit(self): qc3.x([0, 1]) qc3.measure_all() - sampler = Sampler() - result = sampler.run([qc0, qc1, qc2, qc3]).result() + 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) @@ -187,7 +192,8 @@ def test_run_2qubit(self): def test_run_single_circuit(self): """Test for single circuit case.""" - sampler = Sampler() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() with self.subTest("No parameter"): circuit = self._circuit[1] @@ -195,7 +201,8 @@ def test_run_single_circuit(self): 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): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -214,7 +221,8 @@ 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): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -230,7 +238,8 @@ 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): + result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) @@ -247,8 +256,9 @@ 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() + 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) @@ -274,37 +284,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} @@ -312,7 +325,8 @@ def test_run_empty_parameter(self): self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): - result = sampler.run([qc, qc], shots=1000).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} @@ -328,17 +342,20 @@ 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() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): - result = sampler.run([qc] * k, params_list_array).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) @@ -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]) + 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_sparse_pauli_op.py b/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py index e7a9b89b7318..0cc39153639d 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: From 6f7d1580721d93a3d78a13c64b369364349b7146 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Fri, 14 Jun 2024 00:16:04 +0200 Subject: [PATCH 02/21] Fix tests --- test/python/primitives/test_backend_sampler.py | 10 ++++++---- test/python/primitives/test_estimator.py | 14 ++++++++------ test/python/primitives/test_sampler.py | 2 +- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index c532d8f5d2d0..fb0b65d6dc5b 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -116,7 +116,7 @@ def test_sampler_run(self, backend): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell], shots=1000) - result = job.result() + 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)) @@ -277,13 +277,15 @@ def test_run_numpy_params(self, backend): target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): - result = sampler.run([qc] * k, params_array).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) with self.subTest("list of ndarray"): - result = sampler.run([qc] * k, params_list_array).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) @@ -306,7 +308,7 @@ def test_primitive_job_status_done(self, backend): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell]) - _ = job.result() + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_primitive_job_size_limit_backend_v2(self): diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index d6dd3223f347..13949dd8a929 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -68,7 +68,7 @@ def test_estimator_run(self): # Specify the circuit and observable by indices. # calculate [ ] job = estimator.run([psi1], [hamiltonian1], [theta1]) - result = job.result() + result = job.result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956]) @@ -322,8 +322,7 @@ def test_options(self): estimator = Estimator(options={"shots": 3000}) self.assertEqual(estimator.options.get("shots"), 3000) with self.subTest("set_options"): - with self.assertWarns(DeprecationWarning): - estimator.set_options(shots=1024, seed=15) + 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"): @@ -381,19 +380,22 @@ class TestObservableValidation(QiskitTestCase): @unpack def test_validate_observables(self, obsevables, expected): """Test obsevables standardization.""" - self.assertEqual(validation._validate_observables(obsevables), expected) + with self.assertWarns(DeprecationWarning): + self.assertEqual(validation._validate_observables(obsevables), 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 obsevables 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 c70f3cc40ede..cc587e4653a2 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -402,7 +402,7 @@ def test_primitive_job_status_done(self): with self.assertWarns(DeprecationWarning): sampler = Sampler() job = sampler.run(circuits=[bell]) - _ = job.result() + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): From 24c46090978b318d73436a0877a51d254d58f3b9 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Fri, 14 Jun 2024 00:18:59 +0200 Subject: [PATCH 03/21] Fix yaml error --- releasenotes/notes/deprecate-primitives-v1.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml index 4d43cfedf5ba..9cc083551a48 100644 --- a/releasenotes/notes/deprecate-primitives-v1.yaml +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -1,5 +1,5 @@ --- -deprecation: +deprecations_primitives: - | BackendEstimator has been deprecated. Use BackendEstimatorV2 instead. BackendSampler has been deprecated. Use BackendSamplerV2 instead. From 36787833615e015c1a93bc0fda4f6b4181e8295e Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Fri, 14 Jun 2024 01:00:00 +0200 Subject: [PATCH 04/21] Fix build --- test/python/primitives/test_sampler.py | 2 +- .../quantum_info/operators/symplectic/test_pauli.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/test/python/primitives/test_sampler.py b/test/python/primitives/test_sampler.py index cc587e4653a2..dbb4cb5f9878 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -90,7 +90,7 @@ def test_sampler_run(self): with self.assertWarns(DeprecationWarning): sampler = Sampler() job = sampler.run(circuits=[bell]) - result = job.result() + result = job.result() self.assertIsInstance(result, SamplerResult) self._compare_probs(result.quasi_dists, self._target[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: From 9e03a86b64cd2658e17590d6dd694dd15975b7e8 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Sun, 23 Jun 2024 18:45:39 +0200 Subject: [PATCH 05/21] Fix error after mc --- test/python/primitives/test_estimator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index 0633acc2d5fb..dfbfda5f094d 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -381,7 +381,7 @@ class TestObservableValidation(QiskitTestCase): def test_validate_observables(self, obsevables, expected): """Test observables standardization.""" with self.assertWarns(DeprecationWarning): - self.assertEqual(validation._validate_observables(obsevables), expected + self.assertEqual(validation._validate_observables(obsevables), expected) @data(None, "ERROR") def test_qiskit_error(self, observables): From c349353661c72502e6796cd0346b9b7f0de5d704 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Mon, 24 Jun 2024 21:17:56 +0200 Subject: [PATCH 06/21] Fix error after mc --- test/python/primitives/test_estimator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index dfbfda5f094d..d33a9aff86c8 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -378,10 +378,10 @@ class TestObservableValidation(QiskitTestCase): ), ) @unpack - def test_validate_observables(self, obsevables, expected): + def test_validate_observables(self, observables, expected): """Test observables standardization.""" with self.assertWarns(DeprecationWarning): - self.assertEqual(validation._validate_observables(obsevables), expected) + self.assertEqual(validation._validate_observables(observables), expected) @data(None, "ERROR") def test_qiskit_error(self, observables): From e81e86fe30323cfa59be7aa2b6f9947d82a18d80 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Mon, 24 Jun 2024 21:18:05 +0200 Subject: [PATCH 07/21] Apply comments --- qiskit/primitives/backend_estimator.py | 2 +- qiskit/primitives/backend_sampler.py | 2 +- qiskit/primitives/base/base_estimator.py | 2 +- qiskit/primitives/base/base_primitive.py | 2 +- qiskit/primitives/base/base_sampler.py | 2 +- qiskit/primitives/estimator.py | 2 +- qiskit/primitives/sampler.py | 2 +- qiskit/primitives/utils.py | 6 +++--- 8 files changed, 10 insertions(+), 10 deletions(-) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index bcd8c0991bcc..b217ff25665e 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -105,7 +105,7 @@ class BackendEstimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): precludes doing any provider- or backend-specific optimizations. """ - @deprecate_func(since="1.0", additional_msg="Use BackendEstimatorV2 instead.") + @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 26806dc46e51..98592e079cb7 100644 --- a/qiskit/primitives/backend_sampler.py +++ b/qiskit/primitives/backend_sampler.py @@ -47,7 +47,7 @@ class BackendSampler(BaseSampler[PrimitiveJob[SamplerResult]]): precludes doing any provider- or backend-specific optimizations. """ - @deprecate_func(since="1.0", additional_msg="Use BackendSamplerV2 instead.") + @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 4d08e039f03c..e4cac1b56d05 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -104,7 +104,7 @@ class BaseEstimatorV1(BasePrimitive, Generic[T]): __hash__ = None - @deprecate_func(since="1.0", additional_msg="Use BaseEstimatorV2 instead.") + @deprecate_func(since="1.2", additional_msg="Use BaseEstimatorV2 instead.") def __init__( self, *, diff --git a/qiskit/primitives/base/base_primitive.py b/qiskit/primitives/base/base_primitive.py index b4e041f9c617..ab8d2859920e 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -23,7 +23,7 @@ class BasePrimitive(ABC): """Primitive abstract base class.""" - @deprecate_func(since="1.0", additional_msg="Use BasePrimitiveV2 instead.") + @deprecate_func(since="1.2", additional_msg="Use BasePrimitiveV2 instead.") def __init__(self, options: dict | None = None): self._run_options = Options() if options is not None: diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 5ebfa4f4d51a..3a4b410c1367 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -97,7 +97,7 @@ class BaseSamplerV1(BasePrimitive, Generic[T]): __hash__ = None - @deprecate_func(since="1.0", additional_msg="Use BaseSamplerV2 instead.") + @deprecate_func(since="1.2", additional_msg="Use BaseSamplerV2 instead.") def __init__( self, *, diff --git a/qiskit/primitives/estimator.py b/qiskit/primitives/estimator.py index b615cadd277c..874b631379b2 100644 --- a/qiskit/primitives/estimator.py +++ b/qiskit/primitives/estimator.py @@ -52,7 +52,7 @@ class Estimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): this option is ignored. """ - @deprecate_func(since="1.0", additional_msg="Use StatevectorEstimator instead.") + @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 9f00e3c8c199..da0b4ed4d003 100644 --- a/qiskit/primitives/sampler.py +++ b/qiskit/primitives/sampler.py @@ -53,7 +53,7 @@ class Sampler(BaseSampler[PrimitiveJob[SamplerResult]]): option is ignored. """ - @deprecate_func(since="1.0", additional_msg="Use StatevectorSampler instead.") + @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 cd3c0d72febc..40b9e76f377f 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -28,7 +28,7 @@ from qiskit.utils.deprecation import deprecate_func -@deprecate_func(since="1.0", additional_msg="There is no replacement for this.") +@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state by converting the input to a quantum circuit. @@ -47,7 +47,7 @@ def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: return qc -@deprecate_func(since="1.0", additional_msg="There is no replacement for this.") +@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") def init_observable(observable: BaseOperator | str) -> SparsePauliOp: """Initialize observable by converting the input to a :class:`~qiskit.quantum_info.SparsePauliOp`. @@ -71,7 +71,7 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: return SparsePauliOp(observable) -@deprecate_func(since="1.0", additional_msg="There is no replacement for this.") +@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") def final_measurement_mapping(circuit: QuantumCircuit) -> dict[int, int]: """Return the final measurement mapping for the circuit. From 71ad3fb04bb554e2ddd90455bc32cce7f98a199a Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Tue, 25 Jun 2024 14:28:53 +0200 Subject: [PATCH 08/21] Use correct deprecate version for warning message --- qiskit/primitives/base/base_result.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index 359a07d9dedc..4b357c8ea865 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -44,7 +44,7 @@ def __post_init__(self) -> None: ValueError: Inconsistent number of experiments across data fields. """ warn( - "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.0. " + "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.2. " "It will be removed no earlier than 3 months after the release date. " "Use PrimitiveResult class in `qiskit.primitives.containers` instead.", DeprecationWarning, From 620707efea34f840a201fa8bd948bc8f098f8ecb Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Fri, 5 Jul 2024 00:09:52 +0200 Subject: [PATCH 09/21] Update deprecation messages --- qiskit/primitives/base/base_primitive.py | 2 +- qiskit/primitives/base/base_result.py | 2 +- qiskit/primitives/utils.py | 15 ++++++++++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/qiskit/primitives/base/base_primitive.py b/qiskit/primitives/base/base_primitive.py index ab8d2859920e..c9c80627f00c 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -23,7 +23,7 @@ class BasePrimitive(ABC): """Primitive abstract base class.""" - @deprecate_func(since="1.2", additional_msg="Use BasePrimitiveV2 instead.") + @deprecate_func(since="1.2", additional_msg="Use BaseSamplerV2 or BaseEstimatorV2 instead.") def __init__(self, options: dict | None = None): self._run_options = Options() if options is not None: diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index 4b357c8ea865..0db0cc852fd9 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -46,7 +46,7 @@ def __post_init__(self) -> None: warn( "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.2. " "It will be removed no earlier than 3 months after the release date. " - "Use PrimitiveResult class in `qiskit.primitives.containers` instead.", + "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers` instead.", DeprecationWarning, ) diff --git a/qiskit/primitives/utils.py b/qiskit/primitives/utils.py index 40b9e76f377f..5f19ca25ca33 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -28,7 +28,10 @@ from qiskit.utils.deprecation import deprecate_func -@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") +@deprecate_func( + since="1.2", + additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", +) def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state by converting the input to a quantum circuit. @@ -47,7 +50,10 @@ def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: return qc -@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") +@deprecate_func( + since="1.2", + additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", +) def init_observable(observable: BaseOperator | str) -> SparsePauliOp: """Initialize observable by converting the input to a :class:`~qiskit.quantum_info.SparsePauliOp`. @@ -71,7 +77,10 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: return SparsePauliOp(observable) -@deprecate_func(since="1.2", additional_msg="There is no replacement for this.") +@deprecate_func( + since="1.2", + additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", +) def final_measurement_mapping(circuit: QuantumCircuit) -> dict[int, int]: """Return the final measurement mapping for the circuit. From e3e0f5432580b446c92a480cae95f62b12adc660 Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Fri, 5 Jul 2024 00:10:53 +0200 Subject: [PATCH 10/21] Add missed `` --- qiskit/primitives/base/base_result.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index 0db0cc852fd9..095a95c6407f 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -46,7 +46,7 @@ def __post_init__(self) -> None: warn( "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.2. " "It will be removed no earlier than 3 months after the release date. " - "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers` instead.", + "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", DeprecationWarning, ) From 143960f04c1036d084dbe2efc366194f0391fdcf Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Fri, 5 Jul 2024 15:39:26 +0900 Subject: [PATCH 11/21] update releasenote --- .../notes/deprecate-primitives-v1.yaml | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml index 9cc083551a48..2d68524c3b0f 100644 --- a/releasenotes/notes/deprecate-primitives-v1.yaml +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -1,14 +1,27 @@ --- deprecations_primitives: - | - BackendEstimator has been deprecated. Use BackendEstimatorV2 instead. - BackendSampler has been deprecated. Use BackendSamplerV2 instead. - Estimator has been deprecated. Use StatevectorEstimator instead. - Sampler has been deprecated. Use StatevectorSampler instead. + Primitives V1 is now deprecated and will be removed in no less than 3 months from the release date. - BaseEstimatorV1 has been deprecated. Use BaseEstimatorV2 instead. - BasePrimitive has been deprecated. Use BasePrimitiveV2 instead. - BasePrimitiveResult has been deprecated. Use PrimitiveResult class in `qiskit.primitives.containers` instead. - BaseSamplerV1 has been deprecated. Use BaseSamplerV2 instead. + The following Primitives V1 classes are deprecated: + + * :class:`.BaseEstimatorV1`, use :class:`.BaseEstimatorV2` instead, + * :class:`.BaseSamplerV1`, use :class:`.BaseSamplerV2` instead, + * :class:`.BasePrimitive`, use :class:`.BaseEstimatorV2` or :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, + * :class:`.BasePrimitiveResult`, use :class:`.PrimitiveResult` instead, + * :class:`.EstimatorResult`, use :class:`.PrimitiveResult` instead, + * :class:`.SamplerResult`, use :class:`.PrimitiveResult` instead. + + + In addition, the following utility functions are deprecated: + + * :func:`.init_circuit`, use :meth:`.QuantumCircuit.initialize` instead, + * :func:`.init_observable`, use the constructor of :class:`.SparsePauliOp` instead, + * :func:`.final_measurement_mapping`, use ``mthree.utils.final_measurement_mapping`` instead. + See `Mthree Utility functions `__ + for details. - Functions: init_circuit, init_observable and final_measurement_mapping has been deprecated. There is no replacement. From c0103f7edb0926942fb415709436686afa4f94aa Mon Sep 17 00:00:00 2001 From: LeanderCS Date: Mon, 8 Jul 2024 23:46:44 +0200 Subject: [PATCH 12/21] Deprecate SamplerResult and EstimatorResult --- qiskit/primitives/base/estimator_result.py | 5 ++++ qiskit/primitives/base/sampler_result.py | 5 ++++ qiskit/primitives/utils.py | 7 +++-- .../primitives/test_backend_estimator.py | 28 +++++++++---------- .../python/primitives/test_backend_sampler.py | 10 +++---- test/python/primitives/test_estimator.py | 28 +++++++++---------- test/python/primitives/test_sampler.py | 8 +++--- 7 files changed, 51 insertions(+), 40 deletions(-) diff --git a/qiskit/primitives/base/estimator_result.py b/qiskit/primitives/base/estimator_result.py index 88dbf1862d49..bcc6735e80f8 100644 --- a/qiskit/primitives/base/estimator_result.py +++ b/qiskit/primitives/base/estimator_result.py @@ -17,6 +17,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any +from qiskit.utils.deprecation import deprecate_func from .base_result import _BasePrimitiveResult @@ -44,3 +45,7 @@ class EstimatorResult(_BasePrimitiveResult): values: "np.ndarray[Any, np.dtype[np.float64]]" metadata: list[dict[str, Any]] + + @deprecate_func(since="1.2", additional_msg="Use PrimitiveResult instead.") + def __init__(self): + pass diff --git a/qiskit/primitives/base/sampler_result.py b/qiskit/primitives/base/sampler_result.py index 4a472f0e2df9..8d70c4a4da0a 100644 --- a/qiskit/primitives/base/sampler_result.py +++ b/qiskit/primitives/base/sampler_result.py @@ -19,6 +19,7 @@ from typing import Any from qiskit.result import QuasiDistribution +from qiskit.utils.deprecation import deprecate_func from .base_result import _BasePrimitiveResult @@ -43,3 +44,7 @@ class SamplerResult(_BasePrimitiveResult): quasi_dists: list[QuasiDistribution] metadata: list[dict[str, Any]] + + @deprecate_func(since="1.2", additional_msg="Use PrimitiveResult instead.") + def __init__(self): + pass diff --git a/qiskit/primitives/utils.py b/qiskit/primitives/utils.py index 5f19ca25ca33..021d138f33e7 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -30,7 +30,7 @@ @deprecate_func( since="1.2", - additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", + additional_msg="Use ``QuantumCircuit.initialize`` instead.", ) def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state by converting the input to a quantum circuit. @@ -52,7 +52,7 @@ def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: @deprecate_func( since="1.2", - additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", + 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`. @@ -79,7 +79,8 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: @deprecate_func( since="1.2", - additional_msg="There is no replacement for this. Please adjust your code accordingly and use the new utils.", + additional_msg="Use ``mthree.utils.final_measurement_mapping`` instead. " + + "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/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index 54444804c423..c3deb0735ca1 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -97,7 +97,7 @@ def test_estimator_run(self, backend): with self.assertWarns(DeprecationWarning): job = estimator.run([psi1], [hamiltonian1], [theta1]) result = job.result() - self.assertIsInstance(result, EstimatorResult) + 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. @@ -137,7 +137,7 @@ def test_estimator_run_no_params(self, backend): est = BackendEstimator(backend=backend) est.set_options(seed_simulator=123) result = est.run([circuit], [self.observable]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733], rtol=0.05) @combine(backend=BACKENDS, creg=[True, False]) @@ -154,22 +154,22 @@ def test_run_1qubit(self, backend, creg): est = BackendEstimator(backend=backend) est.set_options(seed_simulator=123) result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @combine(backend=BACKENDS, creg=[True, False]) @@ -187,32 +187,32 @@ def test_run_2qubits(self, backend, creg): with self.assertWarns(DeprecationWarning): est = BackendEstimator(backend=backend) result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1], rtol=0.1) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1], rtol=0.1) @combine(backend=BACKENDS) @@ -277,7 +277,7 @@ def test_run_with_shots_option(self, backend): shots=1024, seed_simulator=15, ).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641], rtol=0.1) @combine(backend=BACKENDS) @@ -298,7 +298,7 @@ def test_options(self, backend): [self.observable], parameter_values=[[0, 1, 1, 2, 3, 5]], ).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641], rtol=0.1) def test_job_size_limit_v2(self): diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index fb0b65d6dc5b..8e626a5ad153 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -117,7 +117,7 @@ def test_sampler_run(self, backend): sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell], shots=1000) result = job.result() - self.assertIsInstance(result, SamplerResult) + 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]) @@ -187,7 +187,7 @@ def test_run_1qubit(self, backend): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -211,7 +211,7 @@ def test_run_2qubit(self, backend): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) result = sampler.run([qc0, qc1, qc2, qc3]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -329,7 +329,7 @@ def max_circuits(self): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5)) result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) @@ -349,7 +349,7 @@ def test_primitive_job_size_limit_backend_v1(self): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index d33a9aff86c8..783461c7e4ad 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -69,7 +69,7 @@ def test_estimator_run(self): # calculate [ ] job = estimator.run([psi1], [hamiltonian1], [theta1]) result = job.result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956]) # Objects can be passed instead of indices. @@ -105,7 +105,7 @@ def test_estiamtor_run_no_params(self): with self.assertWarns(DeprecationWarning): est = Estimator() result = est.run([circuit], [self.observable]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733]) def test_run_single_circuit_observable(self): @@ -176,22 +176,22 @@ def test_run_1qubit(self): with self.assertWarns(DeprecationWarning): est = Estimator() result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) def test_run_2qubits(self): @@ -207,32 +207,32 @@ def test_run_2qubits(self): with self.assertWarns(DeprecationWarning): est = Estimator() result = est.run([qc], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op2], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1]) with self.assertWarns(DeprecationWarning): result = est.run([qc2], [op3], [[]]).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1]) def test_run_errors(self): @@ -292,7 +292,7 @@ def test_run_with_shots_option(self): shots=1024, seed=15, ).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641]) def test_run_with_shots_option_none(self): @@ -332,7 +332,7 @@ def test_options(self): [self.observable], parameter_values=[[0, 1, 1, 2, 3, 5]], ).result() - self.assertIsInstance(result, EstimatorResult) + self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.307397243478641]) def test_negative_variance(self): diff --git a/test/python/primitives/test_sampler.py b/test/python/primitives/test_sampler.py index dbb4cb5f9878..a0d6eeb04347 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -91,7 +91,7 @@ def test_sampler_run(self): sampler = Sampler() job = sampler.run(circuits=[bell]) result = job.result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): @@ -156,7 +156,7 @@ def test_run_1qubit(self): with self.assertWarns(DeprecationWarning): sampler = Sampler() result = sampler.run([qc, qc2]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): @@ -181,7 +181,7 @@ def test_run_2qubit(self): with self.assertWarns(DeprecationWarning): sampler = Sampler() result = sampler.run([qc0, qc1, qc2, qc3]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): @@ -259,7 +259,7 @@ def test_run_reverse_meas_order(self): with self.assertWarns(DeprecationWarning): sampler = Sampler() result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() - self.assertIsInstance(result, SamplerResult) + self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) From e7094eb12a068184ef8dcc26076ac014f64674ff Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Tue, 9 Jul 2024 15:16:27 +0900 Subject: [PATCH 13/21] fix deprecation warning for SamplerResult and EstimatorResult --- qiskit/primitives/base/base_result.py | 1 + qiskit/primitives/base/estimator_result.py | 13 +++++++++---- qiskit/primitives/base/sampler_result.py | 13 +++++++++---- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index 095a95c6407f..b390f43853ea 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -48,6 +48,7 @@ def __post_init__(self) -> None: "It will be removed no earlier than 3 months after the release date. " "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", DeprecationWarning, + stacklevel=2, ) num_experiments = None diff --git a/qiskit/primitives/base/estimator_result.py b/qiskit/primitives/base/estimator_result.py index bcc6735e80f8..375fdb9e4289 100644 --- a/qiskit/primitives/base/estimator_result.py +++ b/qiskit/primitives/base/estimator_result.py @@ -17,7 +17,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from qiskit.utils.deprecation import deprecate_func +from warnings import warn from .base_result import _BasePrimitiveResult @@ -46,6 +46,11 @@ class EstimatorResult(_BasePrimitiveResult): values: "np.ndarray[Any, np.dtype[np.float64]]" metadata: list[dict[str, Any]] - @deprecate_func(since="1.2", additional_msg="Use PrimitiveResult instead.") - def __init__(self): - pass + def __post_init__(self) -> None: + warn( + "The class ``EstimatorResult`` is deprecated as of qiskit 1.2. " + "It will be removed no earlier than 3 months after the release date. " + "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", + DeprecationWarning, + stacklevel=2, + ) diff --git a/qiskit/primitives/base/sampler_result.py b/qiskit/primitives/base/sampler_result.py index 8d70c4a4da0a..4b133e99415c 100644 --- a/qiskit/primitives/base/sampler_result.py +++ b/qiskit/primitives/base/sampler_result.py @@ -17,9 +17,9 @@ from dataclasses import dataclass from typing import Any +from warnings import warn from qiskit.result import QuasiDistribution -from qiskit.utils.deprecation import deprecate_func from .base_result import _BasePrimitiveResult @@ -45,6 +45,11 @@ class SamplerResult(_BasePrimitiveResult): quasi_dists: list[QuasiDistribution] metadata: list[dict[str, Any]] - @deprecate_func(since="1.2", additional_msg="Use PrimitiveResult instead.") - def __init__(self): - pass + def __post_init__(self) -> None: + warn( + "The class ``SamplerResult`` is deprecated as of qiskit 1.2. " + "It will be removed no earlier than 3 months after the release date. " + "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", + DeprecationWarning, + stacklevel=2, + ) From 94486dd4b7b1068bbff4f9921a7403266f439425 Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Tue, 16 Jul 2024 22:58:16 +0900 Subject: [PATCH 14/21] apply review comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Matthew Treinish Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/primitives/utils.py | 6 ++++-- releasenotes/notes/deprecate-primitives-v1.yaml | 7 +++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/qiskit/primitives/utils.py b/qiskit/primitives/utils.py index 021d138f33e7..db3fcbd132dc 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -30,7 +30,8 @@ @deprecate_func( since="1.2", - additional_msg="Use ``QuantumCircuit.initialize`` instead.", + 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. @@ -79,7 +80,8 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: @deprecate_func( since="1.2", - additional_msg="Use ``mthree.utils.final_measurement_mapping`` instead. " + 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]: diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml index 2d68524c3b0f..e24e650d010e 100644 --- a/releasenotes/notes/deprecate-primitives-v1.yaml +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -19,9 +19,12 @@ deprecations_primitives: In addition, the following utility functions are deprecated: - * :func:`.init_circuit`, use :meth:`.QuantumCircuit.initialize` instead, + * :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 ``mthree.utils.final_measurement_mapping`` 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. From 696a1963833cae1564c419e19c34059a622cd635 Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Wed, 24 Jul 2024 15:56:01 +0900 Subject: [PATCH 15/21] Applying the agreement of deprecations. - Revert BaseSamplerV1 and BaseEstimatorV1 - Deprecate BaseSampler and BaseEstimator https://github.com/Qiskit/qiskit/issues/12497#issuecomment-2228393758 --- qiskit/primitives/base/base_estimator.py | 24 +++++++++++++++++++++--- qiskit/primitives/base/base_sampler.py | 19 +++++++++++++++++-- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index e4cac1b56d05..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 @@ -104,7 +104,6 @@ class BaseEstimatorV1(BasePrimitive, Generic[T]): __hash__ = None - @deprecate_func(since="1.2", additional_msg="Use BaseEstimatorV2 instead.") def __init__( self, *, @@ -189,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_sampler.py b/qiskit/primitives/base/base_sampler.py index 3a4b410c1367..81a1754ae35b 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -97,7 +97,6 @@ class BaseSamplerV1(BasePrimitive, Generic[T]): __hash__ = None - @deprecate_func(since="1.2", additional_msg="Use BaseSamplerV2 instead.") def __init__( self, *, @@ -152,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): From 0b66c6a71b25fe19fd8c6e70e1607452db085104 Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Wed, 24 Jul 2024 21:26:39 +0900 Subject: [PATCH 16/21] revert SamplerResult, EstimatorResult, and BasePrimitiveResult --- qiskit/primitives/base/base_primitive.py | 6 ++---- qiskit/primitives/base/base_result.py | 13 ++----------- qiskit/primitives/base/estimator_result.py | 14 ++------------ qiskit/primitives/base/sampler_result.py | 14 ++------------ .../notes/deprecate-primitives-v1.yaml | 4 ---- test/python/primitives/test_result.py | 12 ++++-------- test/python/primitives/test_sampler.py | 18 +++++++++--------- 7 files changed, 21 insertions(+), 60 deletions(-) diff --git a/qiskit/primitives/base/base_primitive.py b/qiskit/primitives/base/base_primitive.py index c9c80627f00c..dff019aceeba 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -10,20 +10,18 @@ # 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 from abc import ABC from qiskit.providers import Options -from qiskit.utils.deprecation import deprecate_func class BasePrimitive(ABC): - """Primitive abstract base class.""" + """Primitive V1 abstract base class.""" - @deprecate_func(since="1.2", additional_msg="Use BaseSamplerV2 or BaseEstimatorV2 instead.") def __init__(self, options: dict | None = None): self._run_options = Options() if options is not None: diff --git a/qiskit/primitives/base/base_result.py b/qiskit/primitives/base/base_result.py index b390f43853ea..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 @@ -19,7 +19,6 @@ from collections.abc import Sequence from dataclasses import fields from typing import Any, Dict -from warnings import warn from numpy import ndarray @@ -28,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: @@ -43,14 +42,6 @@ def __post_init__(self) -> None: TypeError: If one of the data fields is not a Sequence or ``numpy.ndarray``. ValueError: Inconsistent number of experiments across data fields. """ - warn( - "The class ``BasePrimitiveResult`` is deprecated as of qiskit 1.2. " - "It will be removed no earlier than 3 months after the release date. " - "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", - DeprecationWarning, - stacklevel=2, - ) - num_experiments = None for value in self._field_values: # type: Sequence if num_experiments is None: diff --git a/qiskit/primitives/base/estimator_result.py b/qiskit/primitives/base/estimator_result.py index 375fdb9e4289..dea72484d7df 100644 --- a/qiskit/primitives/base/estimator_result.py +++ b/qiskit/primitives/base/estimator_result.py @@ -10,14 +10,13 @@ # 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 from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from warnings import warn from .base_result import _BasePrimitiveResult @@ -27,7 +26,7 @@ @dataclass(frozen=True) class EstimatorResult(_BasePrimitiveResult): - """Result of Estimator. + """Result of Estimator V1. .. code-block:: python @@ -45,12 +44,3 @@ class EstimatorResult(_BasePrimitiveResult): values: "np.ndarray[Any, np.dtype[np.float64]]" metadata: list[dict[str, Any]] - - def __post_init__(self) -> None: - warn( - "The class ``EstimatorResult`` is deprecated as of qiskit 1.2. " - "It will be removed no earlier than 3 months after the release date. " - "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", - DeprecationWarning, - stacklevel=2, - ) diff --git a/qiskit/primitives/base/sampler_result.py b/qiskit/primitives/base/sampler_result.py index 4b133e99415c..d27a0f6ba70d 100644 --- a/qiskit/primitives/base/sampler_result.py +++ b/qiskit/primitives/base/sampler_result.py @@ -10,14 +10,13 @@ # 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 from dataclasses import dataclass from typing import Any -from warnings import warn from qiskit.result import QuasiDistribution @@ -26,7 +25,7 @@ @dataclass(frozen=True) class SamplerResult(_BasePrimitiveResult): - """Result of Sampler. + """Result of Sampler V1. .. code-block:: python @@ -44,12 +43,3 @@ class SamplerResult(_BasePrimitiveResult): quasi_dists: list[QuasiDistribution] metadata: list[dict[str, Any]] - - def __post_init__(self) -> None: - warn( - "The class ``SamplerResult`` is deprecated as of qiskit 1.2. " - "It will be removed no earlier than 3 months after the release date. " - "Use ``PrimitiveResult`` class in ``qiskit.primitives.containers`` instead.", - DeprecationWarning, - stacklevel=2, - ) diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml index e24e650d010e..71116197d9c2 100644 --- a/releasenotes/notes/deprecate-primitives-v1.yaml +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -7,14 +7,10 @@ deprecations_primitives: * :class:`.BaseEstimatorV1`, use :class:`.BaseEstimatorV2` instead, * :class:`.BaseSamplerV1`, use :class:`.BaseSamplerV2` instead, - * :class:`.BasePrimitive`, use :class:`.BaseEstimatorV2` or :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, - * :class:`.BasePrimitiveResult`, use :class:`.PrimitiveResult` instead, - * :class:`.EstimatorResult`, use :class:`.PrimitiveResult` instead, - * :class:`.SamplerResult`, use :class:`.PrimitiveResult` instead. In addition, the following utility functions are deprecated: diff --git a/test/python/primitives/test_result.py b/test/python/primitives/test_result.py index 49e79e5501e6..15a9a8d3c781 100644 --- a/test/python/primitives/test_result.py +++ b/test/python/primitives/test_result.py @@ -44,26 +44,22 @@ class TestBasePrimitiveResult(QiskitTestCase): @data(0, 1.2, True, "sequence", b"sequence", {"name": "value"}) def test_post_init_type_error(self, field_1): """Tests post init type error.""" - with self.assertWarns(DeprecationWarning): - self.assertRaises(TypeError, Result, *(field_1, [])) + self.assertRaises(TypeError, Result, *(field_1, [])) @data(([1], []), ([], [1]), ([1, 2], []), ([1], [1, 2])) @unpack def test_post_init_value_error(self, field_1, field_2): """Tests post init value error.""" - with self.assertWarns(DeprecationWarning): - self.assertRaises(ValueError, Result, *(field_1, field_2)) + self.assertRaises(ValueError, Result, *(field_1, field_2)) def test_field_names(self): """Tests field names ("field_1", "field_2").""" - with self.assertWarns(DeprecationWarning): - result = Result([], []) + result = Result([], []) self.assertEqual(result._field_names, ("field_1", "field_2")) @data(([], []), ([0], [0]), ([0], [1])) @unpack def test_field_values(self, field_1, field_2): """Tests field values ({field_1}, {field_2}).""" - with self.assertWarns(DeprecationWarning): - result = Result(field_1, field_2) + result = Result(field_1, field_2) self.assertEqual(result._field_values, (field_1, field_2)) diff --git a/test/python/primitives/test_sampler.py b/test/python/primitives/test_sampler.py index a0d6eeb04347..58ab97689748 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -192,15 +192,14 @@ def test_run_2qubit(self): def test_run_single_circuit(self): """Test for single circuit case.""" - with self.assertWarns(DeprecationWarning): - 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}"): + with self.assertWarns(DeprecationWarning): + sampler = Sampler() with self.assertWarns(DeprecationWarning): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) @@ -221,6 +220,8 @@ def test_run_single_circuit(self): ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): + with self.assertWarns(DeprecationWarning): + sampler = Sampler() with self.assertWarns(DeprecationWarning): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) @@ -238,6 +239,8 @@ def test_run_single_circuit(self): ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): + with self.assertWarns(DeprecationWarning): + sampler = Sampler() with self.assertWarns(DeprecationWarning): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) @@ -325,8 +328,7 @@ def test_run_empty_parameter(self): self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc, qc], shots=1000).result() + result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} @@ -347,15 +349,13 @@ def test_run_numpy_params(self): target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc] * k, params_array).result() + result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc] * k, params_list_array).result() + result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) From 17c34b44fbe136295797c8d9c1dc666e6bd5e97f Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Wed, 24 Jul 2024 23:30:09 +0900 Subject: [PATCH 17/21] fix test_backend_sampler --- test/python/primitives/test_backend_sampler.py | 18 ++++++------------ tox.ini | 4 ++++ 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 8e626a5ad153..8bc5f76ed095 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -245,8 +245,7 @@ def test_run_empty_parameter(self, backend): with self.assertWarns(DeprecationWarning): sampler = BackendSampler(backend=backend) with self.subTest("one circuit"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc], shots=1000).result() + 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} @@ -254,8 +253,7 @@ def test_run_empty_parameter(self, backend): self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc, qc], shots=1000).result() + result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} @@ -277,15 +275,13 @@ def test_run_numpy_params(self, backend): target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc] * k, params_array).result() + result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) with self.subTest("list of ndarray"): - with self.assertWarns(DeprecationWarning): - result = sampler.run([qc] * k, params_list_array).result() + result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) @@ -387,11 +383,9 @@ def test_sequential_run(self): sampler = BackendSampler(backend=Fake7QPulseV1()) result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) - with self.assertWarns(DeprecationWarning): - result2 = sampler.run([qc2]).result() + result2 = sampler.run([qc2]).result() self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) - with self.assertWarns(DeprecationWarning): - result3 = sampler.run([qc, qc2]).result() + result3 = sampler.run([qc, qc2]).result() self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1) diff --git a/tox.ini b/tox.ini index 3ee544538a09..f83ff426620d 100644 --- a/tox.ini +++ b/tox.ini @@ -71,6 +71,10 @@ deps = -r requirements-dev.txt commands = black {posargs} qiskit test tools examples setup.py +[testenv:test] +skip_install = true +commands = stestr run -n test/python/primitives/test_backend_sampler.py + [testenv:coverage] basepython = python3 setenv = From 593e7510956e32bf7cd2c024c83cbb7f01bcf4e3 Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Wed, 24 Jul 2024 23:30:58 +0900 Subject: [PATCH 18/21] revert tox.ini --- tox.ini | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tox.ini b/tox.ini index f83ff426620d..3ee544538a09 100644 --- a/tox.ini +++ b/tox.ini @@ -71,10 +71,6 @@ deps = -r requirements-dev.txt commands = black {posargs} qiskit test tools examples setup.py -[testenv:test] -skip_install = true -commands = stestr run -n test/python/primitives/test_backend_sampler.py - [testenv:coverage] basepython = python3 setenv = From 02a288f7d40517477780684014f7a94857f0c72b Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Thu, 25 Jul 2024 19:13:32 +0900 Subject: [PATCH 19/21] revise deprecation warning for BaseSampler and BaseEstimator --- qiskit/primitives/base/base_estimator.py | 41 +++++++++++------------- qiskit/primitives/base/base_sampler.py | 38 +++++++++++----------- 2 files changed, 36 insertions(+), 43 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index 33ec40300b2a..580fbd036092 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -23,7 +23,6 @@ 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, @@ -188,28 +187,6 @@ def _run( raise NotImplementedError("The subclass of BaseEstimator must implement `_run` method.") -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): r"""Estimator V2 base class. @@ -243,3 +220,21 @@ def run( Returns: A job object that contains results. """ + + +# Deprecation warning for importing BaseEstimator directly + + +def __getattr__(name): + if name == "BaseEstimator": + import warnings + + warnings.warn( + "BaseEstimator class is deprecated as of Qiskit 1.2" + " and will be removed no earlier than 3 months after the release date. " + " Use BaseEstimatorV2 instead", + DeprecationWarning, + stacklevel=2, + ) + return BaseEstimatorV1 + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 81a1754ae35b..87d02c84686b 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -21,7 +21,6 @@ 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 @@ -151,25 +150,6 @@ def _run( raise NotImplementedError("The subclass of BaseSampler must implement `_run` method.") -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): r"""Sampler V2 base class. @@ -195,3 +175,21 @@ def run( Returns: The job object of Sampler's result. """ + + +# Deprecation warning for importing BaseSampler directly + + +def __getattr__(name): + if name == "BaseSampler": + import warnings + + warnings.warn( + "BaseSampler class is deprecated as of Qiskit 1.2" + " and will be removed no earlier than 3 months after the release date. " + " Use BaseSamplerV2 instead", + DeprecationWarning, + stacklevel=2, + ) + return BaseSamplerV1 + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") From 4de78e2f1733d8bc24cacc0daa850da03bad4ab7 Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Thu, 25 Jul 2024 19:17:57 +0900 Subject: [PATCH 20/21] update reno --- qiskit/primitives/base/base_estimator.py | 2 +- qiskit/primitives/base/base_sampler.py | 2 +- releasenotes/notes/deprecate-primitives-v1.yaml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index 580fbd036092..fd725f50d13f 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -231,7 +231,7 @@ def __getattr__(name): warnings.warn( "BaseEstimator class is deprecated as of Qiskit 1.2" - " and will be removed no earlier than 3 months after the release date. " + " and will be removed no earlier than 3 months after the release date." " Use BaseEstimatorV2 instead", DeprecationWarning, stacklevel=2, diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 87d02c84686b..9404ee3d3bf0 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -186,7 +186,7 @@ def __getattr__(name): warnings.warn( "BaseSampler class is deprecated as of Qiskit 1.2" - " and will be removed no earlier than 3 months after the release date. " + " and will be removed no earlier than 3 months after the release date." " Use BaseSamplerV2 instead", DeprecationWarning, stacklevel=2, diff --git a/releasenotes/notes/deprecate-primitives-v1.yaml b/releasenotes/notes/deprecate-primitives-v1.yaml index 71116197d9c2..9526c12d6eca 100644 --- a/releasenotes/notes/deprecate-primitives-v1.yaml +++ b/releasenotes/notes/deprecate-primitives-v1.yaml @@ -5,8 +5,8 @@ deprecations_primitives: The following Primitives V1 classes are deprecated: - * :class:`.BaseEstimatorV1`, use :class:`.BaseEstimatorV2` instead, - * :class:`.BaseSamplerV1`, use :class:`.BaseSamplerV2` instead, + * :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, From 3704f350a75512c2b7d928c1a43f8bf1ba4766fa Mon Sep 17 00:00:00 2001 From: Takashi Imamichi Date: Thu, 25 Jul 2024 22:46:33 +0900 Subject: [PATCH 21/21] revert BaseSampler and BaseEstimator --- qiskit/primitives/base/base_estimator.py | 41 +++++++++++++----------- qiskit/primitives/base/base_sampler.py | 38 +++++++++++----------- 2 files changed, 43 insertions(+), 36 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index fd725f50d13f..33ec40300b2a 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -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,6 +188,28 @@ def _run( raise NotImplementedError("The subclass of BaseEstimator must implement `_run` method.") +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): r"""Estimator V2 base class. @@ -220,21 +243,3 @@ def run( Returns: A job object that contains results. """ - - -# Deprecation warning for importing BaseEstimator directly - - -def __getattr__(name): - if name == "BaseEstimator": - import warnings - - warnings.warn( - "BaseEstimator class is deprecated as of Qiskit 1.2" - " and will be removed no earlier than 3 months after the release date." - " Use BaseEstimatorV2 instead", - DeprecationWarning, - stacklevel=2, - ) - return BaseEstimatorV1 - raise AttributeError(f"module '{__name__}' has no attribute '{name}'") diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 9404ee3d3bf0..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,6 +151,25 @@ def _run( raise NotImplementedError("The subclass of BaseSampler must implement `_run` method.") +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): r"""Sampler V2 base class. @@ -175,21 +195,3 @@ def run( Returns: The job object of Sampler's result. """ - - -# Deprecation warning for importing BaseSampler directly - - -def __getattr__(name): - if name == "BaseSampler": - import warnings - - warnings.warn( - "BaseSampler class is deprecated as of Qiskit 1.2" - " and will be removed no earlier than 3 months after the release date." - " Use BaseSamplerV2 instead", - DeprecationWarning, - stacklevel=2, - ) - return BaseSamplerV1 - raise AttributeError(f"module '{__name__}' has no attribute '{name}'")