diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index eb97a3b95259..03e8ca957fe6 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="0.46.0", additional_msg="Use BackendEstimatorV2 instead.") def __init__( self, backend: BackendV1 | BackendV2, @@ -236,7 +238,6 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> EstimatorResult: - # Transpile self._grouping = list(zip(circuits, observables)) transpiled_circuits = self.transpiled_circuits @@ -368,7 +369,6 @@ def _postprocessing( shots_list = [] for i, j in zip(accum, accum[1:]): - combined_expval = 0.0 combined_var = 0.0 diff --git a/qiskit/primitives/backend_sampler.py b/qiskit/primitives/backend_sampler.py index 140a3091f34a..7dfcb90eef43 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="0.46.0", additional_msg="Use BackendSamplerV2 instead.") def __init__( self, backend: BackendV1 | BackendV2, @@ -135,7 +137,6 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> SamplerResult: - # This line does the actual transpilation transpiled_circuits = self.transpiled_circuits bound_circuits = [ diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index 93b497f02049..a61ea69f6606 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -86,15 +86,15 @@ from copy import copy from typing import Generic, TypeVar -from qiskit.utils.deprecation import deprecate_func from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterView 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 .base_primitive import BasePrimitive from . import validation +from .base_primitive import BasePrimitive T = TypeVar("T", bound=Job) @@ -107,6 +107,7 @@ class BaseEstimator(BasePrimitive, Generic[T]): __hash__ = None + @deprecate_func(since="0.46.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 c161ca8094fa..e2671617911a 100644 --- a/qiskit/primitives/base/base_primitive.py +++ b/qiskit/primitives/base/base_primitive.py @@ -27,6 +27,7 @@ class BasePrimitive(ABC): """Primitive abstract base class.""" + @deprecate_func(since="0.46.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 2c23ea1d7b59..b9cabf1ec06b 100644 --- a/qiskit/primitives/base/base_result.py +++ b/qiskit/primitives/base/base_result.py @@ -19,10 +19,10 @@ from collections.abc import Iterator, Sequence from dataclasses import fields from typing import Any, Dict +from warnings import warn from numpy import ndarray - ExperimentData = Dict[str, Any] @@ -45,6 +45,12 @@ 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 0.46.0. " + "It will be removed no earlier than 3 months after the release date. " + "Use PrimitiveResult in PrimitiveV2 instead.", + DeprecationWarning, + ) for value in self._field_values: # type: Sequence # TODO: enforce all data fields to be tuples instead of sequences if not isinstance(value, (Sequence, ndarray)) or isinstance(value, (str, bytes)): diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index d21487261091..d169233ec2a3 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -100,6 +100,7 @@ class BaseSampler(BasePrimitive, Generic[T]): __hash__ = None + @deprecate_func(since="0.46.0", additional_msg="Use BaseSamplerV2 instead.") def __init__( self, *, diff --git a/qiskit/primitives/estimator.py b/qiskit/primitives/estimator.py index 9edfe35d7eb2..691bc8598825 100644 --- a/qiskit/primitives/estimator.py +++ b/qiskit/primitives/estimator.py @@ -24,15 +24,11 @@ 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 -from .utils import ( - _circuit_key, - _observable_key, - bound_circuit_to_instruction, - init_observable, -) +from .utils import _circuit_key, _observable_key, bound_circuit_to_instruction, init_observable class Estimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): @@ -51,6 +47,7 @@ class Estimator(BaseEstimator[PrimitiveJob[EstimatorResult]]): this option is ignored. """ + @deprecate_func(since="0.46.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 9ffe42165d96..9cd01717793d 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="0.46.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 75d25abbbe30..9ee40a56e887 100644 --- a/qiskit/primitives/utils.py +++ b/qiskit/primitives/utils.py @@ -22,11 +22,13 @@ from qiskit.circuit import Instruction, QuantumCircuit from qiskit.circuit.bit import Bit from qiskit.circuit.library.data_preparation import Initialize -from qiskit.quantum_info import SparsePauliOp, Statevector, PauliList +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="0.46.0") 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="0.46.0") def init_observable(observable: BaseOperator | str) -> SparsePauliOp: """Initialize observable by converting the input to a :class:`~qiskit.quantum_info.SparsePauliOp`. @@ -73,6 +76,7 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp: return SparsePauliOp(observable) +@deprecate_func(since="0.46.0") def final_measurement_mapping(circuit: QuantumCircuit) -> dict[int, int]: """Return the final measurement mapping for the circuit. diff --git a/releasenotes/notes/deprecate-v1-3cdeb826e55f98cb.yaml b/releasenotes/notes/deprecate-v1-3cdeb826e55f98cb.yaml new file mode 100644 index 000000000000..f5e856594db0 --- /dev/null +++ b/releasenotes/notes/deprecate-v1-3cdeb826e55f98cb.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + PrimitivesV1 has been deprecated. Use PrimitivesV2 instead. diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index 0df15f590728..10a818277bdc 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -13,11 +13,10 @@ """Tests for Estimator.""" import unittest -from unittest.mock import patch from multiprocessing import Manager - from test import combine from test.python.transpiler._dummy_passes import DummyAP +from unittest.mock import patch import numpy as np from ddt import ddt @@ -86,13 +85,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) # Specify the circuit and observable by indices. # calculate [ ] - job = estimator.run([psi1], [hamiltonian1], [theta1]) + with self.assertWarns(DeprecationWarning): + job = estimator.run([psi1], [hamiltonian1], [theta1]) + result = job.result() self.assertIsInstance(job, JobV1) - result = job.result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956], rtol=0.5, atol=0.2) @@ -101,19 +102,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 ) @@ -123,8 +131,9 @@ def test_estimator_run_no_params(self, backend): """test for estimator without parameters""" backend.set_options(seed_simulator=123) circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) - est = BackendEstimator(backend=backend) - result = est.run([circuit], [self.observable]).result() + with self.assertWarns(DeprecationWarning): + est = BackendEstimator(backend=backend) + result = est.run([circuit], [self.observable]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733], rtol=0.05) @@ -139,20 +148,24 @@ def test_run_1qubit(self, backend, creg): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("Z", 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([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) @@ -168,28 +181,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) @@ -203,17 +222,18 @@ def test_run_errors(self, backend): op = SparsePauliOp.from_list([("I", 1)]) op2 = SparsePauliOp.from_list([("II", 1)]) - est = BackendEstimator(backend=backend) - 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) + 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): @@ -225,30 +245,34 @@ def test_run_numpy_params(self, backend): params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) - estimator = BackendEstimator(backend=backend) - target = estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) + 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) @@ -256,18 +280,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) @@ -288,9 +314,11 @@ def max_circuits(self): k = 5 params_array = np.random.rand(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): @@ -305,9 +333,11 @@ def test_job_size_limit_v1(self): k = 5 params_array = np.random.rand(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_no_max_circuits(self): @@ -323,15 +353,18 @@ def test_no_max_circuits(self): params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) - estimator = BackendEstimator(backend=backend) - target = estimator.run([qc] * k, [op] * k, params_list).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=backend) + 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) @@ -349,8 +382,9 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=FakeNairobi(), bound_pass_manager=bound_pass) - _ = estimator.run(qc, op).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend=FakeNairobi(), bound_pass_manager=bound_pass) + _ = estimator.run(qc, op).result() expected = [ "bound_pass_manager", ] @@ -369,8 +403,11 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=FakeNairobi(), bound_pass_manager=bound_pass) - _ = estimator.run([qc, qc], [op, op]).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator( + backend=FakeNairobi(), bound_pass_manager=bound_pass + ) + _ = estimator.run([qc, qc], [op, op]).result() expected = [ "bound_pass_manager", "bound_pass_manager", @@ -387,9 +424,11 @@ def test_layout(self, backend): qc.cx(0, 2) op = SparsePauliOp("IZI") backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend) estimator.set_transpile_options(seed_transpiler=15) - value = estimator.run(qc, op, shots=10000).result().values[0] + with self.assertWarns(DeprecationWarning): + value = estimator.run(qc, op, shots=10000).result().values[0] if optionals.HAS_AER and not isinstance(backend, FakeBackendSimple): self.assertEqual(value, -0.916) else: @@ -402,9 +441,11 @@ def test_layout(self, backend): qc.cx(0, 2) op = SparsePauliOp("IZI") backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend) estimator.set_transpile_options(initial_layout=[0, 1, 2], seed_transpiler=15) - value = estimator.run(qc, op, shots=10000).result().values[0] + with self.assertWarns(DeprecationWarning): + value = estimator.run(qc, op, shots=10000).result().values[0] if optionals.HAS_AER and not isinstance(backend, FakeBackendSimple): self.assertEqual(value, -0.8902) else: @@ -423,9 +464,11 @@ def test_circuit_with_measurement(self): backend = AerSimulator() backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend, skip_transpilation=True) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend, skip_transpilation=True) estimator.set_transpile_options(seed_transpiler=15) - result = estimator.run(bell, observable).result() + with self.assertWarns(DeprecationWarning): + 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") @@ -444,9 +487,11 @@ def test_dynamic_circuit(self): backend = AerSimulator() backend.set_options(seed_simulator=15) - estimator = BackendEstimator(backend, skip_transpilation=True) + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator(backend, skip_transpilation=True) estimator.set_transpile_options(seed_transpiler=15) - result = estimator.run(qc, observable).result() + with self.assertWarns(DeprecationWarning): + 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 b4b8d79e32a3..6f13a3470e37 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -15,7 +15,6 @@ import math import unittest from multiprocessing import Manager - from test import combine from test.python.transpiler._dummy_passes import DummyAP @@ -26,8 +25,8 @@ from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import BackendSampler, SamplerResult from qiskit.providers import JobStatus, JobV1 -from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2 from qiskit.providers.basicaer import QasmSimulatorPy +from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2 from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.utils import optionals @@ -113,10 +112,12 @@ 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) self.assertIsInstance(job, JobV1) - result = job.result() + with self.assertWarns(DeprecationWarning): + 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)) @@ -128,8 +129,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]) @@ -143,8 +145,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 = { @@ -182,8 +185,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) @@ -205,8 +209,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) @@ -223,13 +228,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): @@ -237,9 +243,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} @@ -247,7 +255,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,17 +272,20 @@ def test_run_numpy_params(self, backend): params_array = np.random.rand(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() + 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) @@ -282,19 +294,21 @@ def test_run_numpy_params(self, backend): def test_run_with_shots_option(self, backend): """test with shots option.""" params, target = self._generate_params_target([1]) - sampler = BackendSampler(backend=backend) - result = sampler.run( - circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 - ).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + result = sampler.run( + circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 + ).result() self._compare_probs(result.quasi_dists, target) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell = self._circuit[1] - sampler = BackendSampler(backend=backend) - job = sampler.run(circuits=[bell]) - _ = job.result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + job = sampler.run(circuits=[bell]) + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_primitive_job_size_limit_backend_v2(self): @@ -312,8 +326,9 @@ def max_circuits(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=FakeNairobiLimitedCircuits()) - result = sampler.run([qc, qc2]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeNairobiLimitedCircuits()) + result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) @@ -331,8 +346,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,9 +370,11 @@ def test_circuit_with_dynamic_circuit(self): backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=15) - sampler = BackendSampler(backend, skip_transpilation=True) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend, skip_transpilation=True) sampler.set_transpile_options(seed_transpiler=15) - result = sampler.run(qc).result() + with self.assertWarns(DeprecationWarning): + result = sampler.run(qc).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 0.5029296875, 1: 0.4970703125}) def test_sequential_run(self): @@ -366,12 +384,15 @@ def test_sequential_run(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=FakeNairobi()) - result = sampler.run([qc]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeNairobi()) + 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) @@ -387,9 +408,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=QasmSimulatorPy()) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=QasmSimulatorPy()) - result = sampler.run(qc).result() + result = sampler.run(qc).result() probs = result.quasi_dists[0].binary_probabilities() self.assertIn("0001", probs.keys()) @@ -406,8 +428,9 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) - _ = sampler.run([self._circuit[0]]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) + _ = sampler.run([self._circuit[0]]).result() expected = [ "bound_pass_manager", ] @@ -426,8 +449,9 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) - _ = sampler.run([self._circuit[0], self._circuit[0]]).result() + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeNairobi(), 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 7a190cbe0034..a2d1cfa30ff5 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -63,13 +63,15 @@ 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]) + with self.assertWarns(DeprecationWarning): + job = estimator.run([psi1], [hamiltonian1], [theta1]) + result = job.result() self.assertIsInstance(job, JobV1) - result = job.result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [1.5555572817900956]) @@ -78,32 +80,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) @@ -113,7 +124,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) @@ -132,7 +144,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) @@ -149,7 +162,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) @@ -162,20 +176,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]) @@ -189,28 +207,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]) @@ -222,17 +246,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""" @@ -242,16 +267,19 @@ def test_run_numpy_params(self): params_array = np.random.rand(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) @@ -266,58 +294,63 @@ def test_run_with_operator(self): [0.1809312, 0.0, 0.0, -1.06365335], ] ) - est = Estimator() - result = est.run([circuit], [matrix]).result() + with self.assertWarns(DeprecationWarning): + est = Estimator() + result = est.run([circuit], [matrix]).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.284366511861733]) 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) 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]) @@ -325,8 +358,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) @@ -365,7 +399,8 @@ 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( (PauliList("IXYZ"), (SparsePauliOp("IXYZ"),)), @@ -384,13 +419,15 @@ def test_validate_observables_deprecated(self, obsevables, expected): 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_result.py b/test/python/primitives/test_result.py index 3f4904ada58f..a491b6388516 100644 --- a/test/python/primitives/test_result.py +++ b/test/python/primitives/test_result.py @@ -45,18 +45,21 @@ 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)) @data(0, 1, 2, 3) def test_num_experiments(self, num_experiments): """Tests {num_experiments} num_experiments.""" - result = Result([0] * num_experiments, [1] * num_experiments) + with self.assertWarns(DeprecationWarning): + result = Result([0] * num_experiments, [1] * num_experiments) self.assertEqual(num_experiments, result.num_experiments) @data(0, 1, 2, 3) @@ -64,7 +67,8 @@ def test_experiments(self, num_experiments): """Test experiment data.""" field_1 = list(range(num_experiments)) field_2 = [i + 1 for i in range(num_experiments)] - experiments = Result(field_1, field_2).experiments + with self.assertWarns(DeprecationWarning): + experiments = Result(field_1, field_2).experiments self.assertIsInstance(experiments, tuple) for i, exp in enumerate(experiments): self.assertEqual(exp, {"field_1": i, "field_2": i + 1}) @@ -74,20 +78,23 @@ def test_decompose(self, num_experiments): """Test decompose.""" field_1 = list(range(num_experiments)) field_2 = [i + 1 for i in range(num_experiments)] - result = Result(field_1, field_2) - for i, res in enumerate(result.decompose()): - self.assertIsInstance(res, Result) - f1, f2 = (i,), (i + 1,) - self.assertEqual(res, Result(f1, f2)) + with self.assertWarns(DeprecationWarning): + result = Result(field_1, field_2) + for i, res in enumerate(result.decompose()): + self.assertIsInstance(res, Result) + f1, f2 = (i,), (i + 1,) + self.assertEqual(res, Result(f1, f2)) 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 fac9a250a9e9..19dbfcc73c3c 100644 --- a/test/python/primitives/test_sampler.py +++ b/test/python/primitives/test_sampler.py @@ -88,10 +88,11 @@ def _compare_probs(self, prob, target): def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] - sampler = Sampler() - job = sampler.run(circuits=[bell]) + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + job = sampler.run(circuits=[bell]) + result = job.result() self.assertIsInstance(job, JobV1) - result = job.result() self.assertIsInstance(result, SamplerResult) self._compare_probs(result.quasi_dists, self._target[1]) @@ -100,8 +101,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]) @@ -114,8 +116,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 = { @@ -152,8 +155,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) @@ -176,8 +180,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) @@ -189,7 +194,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] @@ -197,7 +203,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) @@ -216,7 +223,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) @@ -232,7 +240,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) @@ -249,8 +258,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) @@ -276,37 +286,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} @@ -314,7 +327,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} @@ -329,17 +343,20 @@ def test_run_numpy_params(self): params_array = np.random.rand(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]) @@ -347,21 +364,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): @@ -371,8 +390,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) @@ -380,15 +400,17 @@ def test_run_shots_result_size(self): def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] - sampler = Sampler() - job = sampler.run(circuits=[bell]) - _ = job.result() + with self.assertWarns(DeprecationWarning): + sampler = Sampler() + job = sampler.run(circuits=[bell]) + _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): - sampler = Sampler(options={"shots": 3000}) + with self.assertWarns(DeprecationWarning): + sampler = Sampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) @@ -396,7 +418,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) @@ -408,8 +431,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 c158ae05c037..165a03ef8d3b 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 c519855faa6f..b2839233bff7 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 @@ -1050,12 +1050,14 @@ def test_permute_sparse_pauli_op_estimator_example(self): op = SparsePauliOp.from_list([("IIII", 1), ("IZZZ", 2), ("XXXI", 3)]) backend = FakeNairobiV2() 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 np.testing.assert_allclose(res, [1.35351562], rtol=0.5, atol=0.2) def test_apply_layout_invalid_qubits_list(self):